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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::errors::{Error, Result};
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Debug, Display, Formatter},
str::FromStr,
};
const COIN_TO_RAW_POWER_OF_10_CONVERSION: u32 = 9;
const COIN_TO_RAW_CONVERSION: u64 = 1_000_000_000;
pub const MAX_COINS_VALUE: Coins =
Coins((u32::max_value() as u64 + 1) * COIN_TO_RAW_CONVERSION - 1);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Coins(u64);
impl Coins {
pub fn from_nano(value: u64) -> Result<Self> {
if value > MAX_COINS_VALUE.0 {
return Err(Error::ExcessiveValue);
}
Ok(Self(value))
}
pub fn max_value() -> Self {
MAX_COINS_VALUE
}
pub fn as_nano(self) -> u64 {
self.0
}
pub fn checked_add(self, rhs: Coins) -> Option<Coins> {
self.0
.checked_add(rhs.0)
.and_then(|nano| Coins::from_nano(nano).ok())
}
pub fn checked_sub(self, rhs: Coins) -> Option<Coins> {
self.0
.checked_sub(rhs.0)
.and_then(|nano| Coins::from_nano(nano).ok())
}
}
impl FromStr for Coins {
type Err = Error;
fn from_str(value_str: &str) -> Result<Self> {
let mut itr = value_str.splitn(2, '.');
let converted_units = {
let units = itr
.next()
.and_then(|s| s.parse::<u64>().ok())
.ok_or_else(|| Error::FailedToParse("Can't parse coin units".to_string()))?;
units
.checked_mul(COIN_TO_RAW_CONVERSION)
.ok_or_else(|| Error::ExcessiveValue)?
};
let remainder = {
let remainder_str = itr.next().unwrap_or_default().trim_end_matches('0');
if remainder_str.is_empty() {
0
} else {
let parsed_remainder = remainder_str
.parse::<u64>()
.map_err(|_| Error::FailedToParse("Can't parse coin remainder".to_string()))?;
let remainder_conversion = COIN_TO_RAW_POWER_OF_10_CONVERSION
.checked_sub(remainder_str.len() as u32)
.ok_or_else(|| Error::LossOfPrecision)?;
parsed_remainder * 10_u64.pow(remainder_conversion)
}
};
Self::from_nano(converted_units + remainder)
}
}
impl Debug for Coins {
#[allow(trivial_casts)]
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
(self as &dyn Display).fmt(formatter)
}
}
impl Display for Coins {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
let unit = self.0 / COIN_TO_RAW_CONVERSION;
let remainder = self.0 % COIN_TO_RAW_CONVERSION;
write!(formatter, "{}.{}", unit, format!("{:09}", remainder))
}
}
#[cfg(test)]
mod tests {
use super::*;
use unwrap::unwrap;
#[test]
fn from_str() {
assert_eq!(Coins(0), unwrap!(Coins::from_str("0")));
assert_eq!(Coins(0), unwrap!(Coins::from_str("0.")));
assert_eq!(Coins(0), unwrap!(Coins::from_str("0.0")));
assert_eq!(Coins(1), unwrap!(Coins::from_str("0.000000001")));
assert_eq!(Coins(1_000_000_000), unwrap!(Coins::from_str("1")));
assert_eq!(Coins(1_000_000_000), unwrap!(Coins::from_str("1.")));
assert_eq!(Coins(1_000_000_000), unwrap!(Coins::from_str("1.0")));
assert_eq!(
Coins(1_000_000_001),
unwrap!(Coins::from_str("1.000000001"))
);
assert_eq!(Coins(1_100_000_000), unwrap!(Coins::from_str("1.1")));
assert_eq!(
Coins(1_100_000_001),
unwrap!(Coins::from_str("1.100000001"))
);
assert_eq!(
Coins(4_294_967_295_000_000_000),
unwrap!(Coins::from_str("4294967295"))
);
assert_eq!(
MAX_COINS_VALUE,
unwrap!(Coins::from_str("4294967295.999999999")),
);
assert_eq!(
MAX_COINS_VALUE,
unwrap!(Coins::from_str("4294967295.9999999990000")),
);
assert_eq!(
Err(Error::FailedToParse("Can't parse coin units".to_string())),
Coins::from_str("a")
);
assert_eq!(
Err(Error::FailedToParse(
"Can't parse coin remainder".to_string()
)),
Coins::from_str("0.a")
);
assert_eq!(
Err(Error::FailedToParse(
"Can't parse coin remainder".to_string()
)),
Coins::from_str("0.0.0")
);
assert_eq!(Err(Error::LossOfPrecision), Coins::from_str("0.0000000009"));
assert_eq!(Err(Error::ExcessiveValue), Coins::from_str("4294967296"));
}
#[test]
fn display() {
assert_eq!("0.000000000", format!("{}", Coins(0)));
assert_eq!("0.000000001", format!("{}", Coins(1)));
assert_eq!("0.000000010", format!("{}", Coins(10)));
assert_eq!("1.000000000", format!("{}", Coins(1_000_000_000)));
assert_eq!("1.000000001", format!("{}", Coins(1_000_000_001)));
assert_eq!(
"4294967295.000000000",
format!("{}", Coins(4_294_967_295_000_000_000))
);
assert_eq!("4294967295.999999999", format!("{}", MAX_COINS_VALUE));
}
#[test]
fn checked_add_sub() {
assert_eq!(
Some(MAX_COINS_VALUE),
Coins(MAX_COINS_VALUE.0 - 1).checked_add(Coins(1))
);
assert_eq!(None, MAX_COINS_VALUE.checked_add(Coins(1)));
assert_eq!(None, MAX_COINS_VALUE.checked_add(MAX_COINS_VALUE));
assert_eq!(Some(Coins(0)), MAX_COINS_VALUE.checked_sub(MAX_COINS_VALUE));
assert_eq!(None, Coins(0).checked_sub(MAX_COINS_VALUE));
assert_eq!(None, Coins(10).checked_sub(Coins(11)));
}
}