1use std::cmp::Ordering;
5use std::fmt;
6
7use num_bigint::BigInt;
8use num_integer::Integer;
9use num_traits::{One, Pow, Signed, Zero};
10
11use crate::error::Fault;
12use crate::int::Int;
13
14pub const DIVISION_DIGITS: u32 = 34;
16
17#[derive(Clone, PartialEq, Eq, Hash)]
33pub struct Decimal {
34 coefficient: BigInt,
35 exponent: i64,
36}
37
38impl Decimal {
39 pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
45 if coefficient.is_zero() {
46 return Ok(Decimal {
47 coefficient,
48 exponent: 0,
49 });
50 }
51 let digits = coefficient.magnitude().to_string();
52 let zeros = digits.len() - digits.trim_end_matches('0').len();
53 let raised = i64::try_from(zeros)
54 .ok()
55 .and_then(|zeros| exponent.checked_add(zeros))
56 .ok_or(Fault::Limit)?;
57 let zeros = u64::try_from(zeros).expect("a count of digits fits 64 bits");
59 Ok(Decimal {
60 coefficient: coefficient / pow10(zeros),
61 exponent: raised,
62 })
63 }
64
65 pub fn parse(spelling: &str) -> Option<Self> {
71 let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
72 Int::parse(whole)?;
73 if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
74 return None;
75 }
76 let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
77 let exponent = i64::try_from(fraction.len()).ok()?;
78 Decimal::new(coefficient, -exponent).ok()
79 }
80
81 pub fn coefficient(&self) -> &BigInt {
83 &self.coefficient
84 }
85
86 pub fn exponent(&self) -> i64 {
88 self.exponent
89 }
90
91 pub fn is_zero(&self) -> bool {
93 self.coefficient.is_zero()
94 }
95
96 pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
102 if self.is_zero() {
105 return Ok(other.clone());
106 }
107 if other.is_zero() {
108 return Ok(self.clone());
109 }
110 let exponent = self.exponent.min(other.exponent);
111 let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
112 let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
113 Decimal::new(left + right, exponent)
114 }
115
116 pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
118 self.add(&other.neg())
119 }
120
121 #[must_use]
123 pub fn neg(&self) -> Decimal {
124 Decimal {
125 coefficient: -&self.coefficient,
126 exponent: self.exponent,
127 }
128 }
129
130 pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
132 let exponent = self
133 .exponent
134 .checked_add(other.exponent)
135 .ok_or(Fault::Limit)?;
136 Decimal::new(&self.coefficient * &other.coefficient, exponent)
137 }
138
139 pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
147 if divisor.is_zero() {
148 return Err(Fault::DivisionByZero);
149 }
150 let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
151 let shared = self.coefficient.gcd(&divisor.coefficient);
152 let numerator = self.coefficient.abs() / &shared;
153 let denominator = divisor.coefficient.abs() / &shared;
154 let exponent = self
155 .exponent
156 .checked_sub(divisor.exponent)
157 .ok_or(Fault::Limit)?;
158
159 let (twos, fives, rest) = twos_and_fives(&denominator);
160 let (magnitude, exponent) = if rest.is_one() {
161 let k = twos.max(fives);
164 let factor = pow10(k) / &denominator;
165 let shifted = exponent
166 .checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
167 .ok_or(Fault::Limit)?;
168 (numerator * factor, shifted)
169 } else {
170 rounded_quotient(&numerator, &denominator, exponent)?
171 };
172 let signed = if negative { -magnitude } else { magnitude };
173 Decimal::new(signed, exponent)
174 }
175
176 pub fn floor(&self) -> Int {
178 if self.adjusted_exponent() <= 0 {
179 return Int::from(if self.coefficient.is_negative() {
183 BigInt::from(-1)
184 } else {
185 BigInt::zero()
186 });
187 }
188 let up = pow10(self.exponent.max(0).unsigned_abs());
189 let down = pow10(self.exponent.min(0).unsigned_abs());
190 Int::from((&self.coefficient * up).div_floor(&down))
191 }
192
193 pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
200 if self.adjusted_exponent() > i128::from(max_bits) {
201 return None;
202 }
203 let floor = self.floor();
204 (floor.bits() <= max_bits).then_some(floor)
205 }
206
207 pub fn text_len(&self) -> u128 {
210 let digits = u128::from(digit_count(&self.coefficient));
211 let places = u128::from(self.exponent.unsigned_abs());
212 let plain = if self.exponent >= 0 {
213 digits + places
214 } else if digits > places {
215 digits + 1
217 } else {
218 places + 2
220 };
221 plain + u128::from(self.coefficient.is_negative())
222 }
223
224 fn adjusted_exponent(&self) -> i128 {
226 i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
227 }
228}
229
230impl From<&Int> for Decimal {
231 fn from(value: &Int) -> Self {
232 Decimal::new(value.as_bigint().clone(), 0)
233 .expect("an integer has fewer trailing zeros than an exponent can count")
234 }
235}
236
237impl Ord for Decimal {
239 fn cmp(&self, other: &Self) -> Ordering {
240 let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
241 if by_sign != Ordering::Equal {
242 return by_sign;
243 }
244 let magnitude = self
250 .adjusted_exponent()
251 .cmp(&other.adjusted_exponent())
252 .then_with(|| {
253 let left = self.coefficient.magnitude().to_string();
254 left.cmp(&other.coefficient.magnitude().to_string())
255 });
256 if self.coefficient.is_negative() {
257 magnitude.reverse()
258 } else {
259 magnitude
260 }
261 }
262}
263
264impl PartialOrd for Decimal {
265 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
266 Some(self.cmp(other))
267 }
268}
269
270impl fmt::Display for Decimal {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 let sign = if self.coefficient.is_negative() {
276 "-"
277 } else {
278 ""
279 };
280 let digits = self.coefficient.magnitude().to_string();
281 let Ok(places) = usize::try_from(-self.exponent) else {
282 let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
284 return write!(f, "{sign}{digits}{zeros}");
285 };
286 if places >= digits.len() {
287 let zeros = "0".repeat(places - digits.len());
288 write!(f, "{sign}0.{zeros}{digits}")
289 } else {
290 let (whole, fraction) = digits.split_at(digits.len() - places);
291 if fraction.is_empty() {
292 write!(f, "{sign}{whole}")
293 } else {
294 write!(f, "{sign}{whole}.{fraction}")
295 }
296 }
297 }
298}
299
300impl fmt::Debug for Decimal {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 fmt::Display::fmt(self, f)
303 }
304}
305
306fn pow10(places: u64) -> BigInt {
311 Pow::pow(BigInt::from(10), places)
312}
313
314fn digit_count(value: &BigInt) -> u64 {
316 u64::try_from(value.magnitude().to_string().len()).unwrap_or(u64::MAX)
317}
318
319fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
321 let mut rest = value.clone();
322 let twos = rest.trailing_zeros().unwrap_or(0);
323 rest >>= twos;
324 let five = BigInt::from(5);
325 let mut fives = 0;
326 for _ in 0..value.bits() {
329 let (quotient, remainder) = rest.div_rem(&five);
330 if !remainder.is_zero() {
331 break;
332 }
333 rest = quotient;
334 fives += 1;
335 }
336 (twos, fives, rest)
337}
338
339fn rounded_quotient(
344 numerator: &BigInt,
345 denominator: &BigInt,
346 exponent: i64,
347) -> Result<(BigInt, i64), Fault> {
348 let digits = i64::from(DIVISION_DIGITS);
349 let low = pow10(u64::from(DIVISION_DIGITS));
350 let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
354 let mut guarded = shifted_quotient(numerator, denominator, shift);
355 if guarded < low {
356 shift += 1;
357 guarded = shifted_quotient(numerator, denominator, shift);
358 }
359 let rounded = (guarded + 5) / 10;
363 let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
364 Ok((rounded, exponent))
365}
366
367fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
369 let places = shift.unsigned_abs();
370 if shift >= 0 {
371 (numerator * pow10(places)) / denominator
372 } else {
373 numerator / (denominator * pow10(places))
374 }
375}
376
377fn digits_i64(value: &BigInt) -> i64 {
378 i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
379}