1use std::fmt;
2use std::hash::{Hash, Hasher};
3
4#[derive(Clone, Copy, Debug)]
6pub struct Decimal {
7 mantissa: i64,
8 exponent: i8,
9}
10
11impl Decimal {
12 pub const fn new(mantissa: i64, exponent: i8) -> Self {
14 Self { mantissa, exponent }
15 }
16
17 pub const fn mantissa(&self) -> i64 {
19 self.mantissa
20 }
21
22 pub const fn exponent(&self) -> i8 {
24 self.exponent
25 }
26
27 pub(crate) fn parse(text: &[u8]) -> Option<Self> {
29 let (negative, unsigned) = match text.strip_prefix(b"-") {
30 Some(rest) => (true, rest),
31 None => (false, text),
32 };
33 let mut parts = unsigned.splitn(2, |&byte| byte == b'.');
34 let whole = parts.next().unwrap_or_default();
35 let fraction = parts.next().unwrap_or_default();
36 if whole.is_empty() && fraction.is_empty() {
37 return None;
38 }
39 let exponent = -i8::try_from(fraction.len()).ok()?;
40 let mut mantissa: i64 = 0;
41 for &byte in whole.iter().chain(fraction) {
42 if !byte.is_ascii_digit() {
43 return None;
44 }
45 mantissa = mantissa
46 .checked_mul(10)?
47 .checked_add(i64::from(byte - b'0'))?;
48 }
49 let mantissa = if negative { -mantissa } else { mantissa };
50 Some(Self::new(mantissa, exponent))
51 }
52
53 fn normalized(self) -> (i64, i8) {
55 if self.mantissa == 0 {
56 return (0, 0);
57 }
58 let (mut mantissa, mut exponent) = (self.mantissa, self.exponent);
59 while mantissa % 10 == 0 && exponent < i8::MAX {
60 mantissa /= 10;
61 exponent += 1;
62 }
63 (mantissa, exponent)
64 }
65}
66
67impl PartialEq for Decimal {
68 fn eq(&self, other: &Self) -> bool {
69 self.normalized() == other.normalized()
70 }
71}
72
73impl Eq for Decimal {}
74
75impl Hash for Decimal {
76 fn hash<H: Hasher>(&self, state: &mut H) {
77 self.normalized().hash(state);
78 }
79}
80
81impl fmt::Display for Decimal {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 let digits = self.mantissa.unsigned_abs().to_string();
84 let scale = usize::from(self.exponent.unsigned_abs());
85 let text = if self.exponent >= 0 {
86 format!("{digits}{}", "0".repeat(scale))
87 } else if digits.len() > scale {
88 let (whole, fraction) = digits.split_at(digits.len() - scale);
89 format!("{whole}.{fraction}")
90 } else {
91 format!("0.{digits:0>scale$}")
92 };
93 f.pad_integral(self.mantissa >= 0, "", &text)
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 fn parse(text: &str) -> Option<Decimal> {
102 Decimal::parse(text.as_bytes())
103 }
104
105 fn parts(text: &str) -> (i64, i8) {
106 let value = parse(text).unwrap();
107 (value.mantissa(), value.exponent())
108 }
109
110 mod parsing {
111 use super::*;
112
113 #[test]
114 fn reads_the_scale_from_the_fraction() {
115 assert_eq!(parts("101.25"), (10125, -2));
116 }
117
118 #[test]
119 fn keeps_trailing_zeros() {
120 assert_eq!(parts("1.50"), (150, -2));
121 }
122
123 #[test]
124 fn reads_a_negative_value() {
125 assert_eq!(parts("-0.005"), (-5, -3));
126 }
127
128 #[test]
129 fn reads_an_integer() {
130 assert_eq!(parts("100"), (100, 0));
131 }
132
133 #[test]
134 fn accepts_a_point_on_either_end() {
135 assert_eq!(parts("23."), (23, 0));
136 assert_eq!(parts(".5"), (5, -1));
137 assert_eq!(parts("-.5"), (-5, -1));
138 }
139
140 #[test]
141 fn skips_leading_zeros() {
142 assert_eq!(parts("00023.23"), (2323, -2));
143 }
144
145 #[test]
146 fn rejects_text_without_digits() {
147 for text in ["", "-", ".", "-."] {
148 assert_eq!(parse(text), None, "{text:?}");
149 }
150 }
151
152 #[test]
153 fn rejects_other_characters() {
154 for text in ["+5", "1e5", " 1", "1 ", "1.2.3", "--1", "1-"] {
155 assert_eq!(parse(text), None, "{text:?}");
156 }
157 }
158
159 #[test]
160 fn rejects_a_mantissa_beyond_i64() {
161 assert_eq!(parts("9223372036854775807"), (i64::MAX, 0));
162 assert_eq!(parse("9223372036854775808"), None);
163 assert_eq!(parse("1.0000000000000000000"), None);
164 }
165
166 #[test]
167 fn rejects_more_than_127_fraction_digits() {
168 assert_eq!(parts(&format!("0.{}", "0".repeat(127))), (0, -127));
169 assert_eq!(parse(&format!("0.{}", "0".repeat(128))), None);
170 }
171 }
172
173 mod display {
174 use super::*;
175
176 #[test]
177 fn keeps_the_scale() {
178 assert_eq!(Decimal::new(150, -2).to_string(), "1.50");
179 }
180
181 #[test]
182 fn pads_a_small_fraction() {
183 assert_eq!(Decimal::new(-5, -3).to_string(), "-0.005");
184 assert_eq!(Decimal::new(0, -2).to_string(), "0.00");
185 }
186
187 #[test]
188 fn writes_an_integer_without_a_point() {
189 assert_eq!(Decimal::new(23, 0).to_string(), "23");
190 assert_eq!(Decimal::new(15, 3).to_string(), "15000");
191 }
192
193 #[test]
194 fn round_trips_the_wire_text() {
195 for text in ["101.25", "-1.50", "0.005", "100"] {
196 assert_eq!(parse(text).unwrap().to_string(), text);
197 }
198 }
199
200 #[test]
201 fn honours_width_and_alignment() {
202 assert_eq!(format!("{:>8}", Decimal::new(150, -2)), " 1.50");
203 assert_eq!(format!("{:08}", Decimal::new(-150, -2)), "-0001.50");
204 }
205 }
206
207 mod equality {
208 use super::*;
209 use std::hash::DefaultHasher;
210
211 fn hash_of(value: Decimal) -> u64 {
212 let mut hasher = DefaultHasher::new();
213 value.hash(&mut hasher);
214 hasher.finish()
215 }
216
217 #[test]
218 fn compares_by_value_across_scales() {
219 assert_eq!(Decimal::new(150, -2), Decimal::new(15, -1));
220 assert_eq!(Decimal::new(0, -2), Decimal::new(0, 0));
221 assert_ne!(Decimal::new(150, -2), Decimal::new(151, -2));
222 }
223
224 #[test]
225 fn equal_values_hash_alike() {
226 assert_eq!(
227 hash_of(Decimal::new(150, -2)),
228 hash_of(Decimal::new(15, -1))
229 );
230 }
231 }
232}