decimal64 0.0.8

Fast fixed point arithmetic that only uses u64 as internal representation.
Documentation
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
use crate::error::{Error, InvalidInputKind};
use std::fmt::{Display, Formatter};
use std::marker::PhantomData;

mod arithmetic;
pub mod error;
mod macros;
pub mod math;
pub mod round;
#[cfg(feature = "serde")]
pub mod serde;

pub trait ScaleMetrics {
    const SCALE: u8;
    const SCALE_FACTOR: u64;
    const REQUIRED_BUFFER_LEN: usize;
}

gen_scale!(U0, 0, 20);
gen_scale!(U1, 1, 21);
gen_scale!(U2, 2, 21);
gen_scale!(U3, 3, 21);
gen_scale!(U4, 4, 21);
gen_scale!(U5, 5, 21);
gen_scale!(U6, 6, 21);
gen_scale!(U7, 7, 21);
gen_scale!(U8, 8, 21);

const SCALE_FACTORS: [u64; 9] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000];
const POW5_U128: [u128; 9] = [1, 5, 25, 125, 625, 3125, 15625, 78125, 390625];

#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct DecimalU64<S>(pub u64, PhantomData<S>);

impl<S: ScaleMetrics> Display for DecimalU64<S> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // A buffer large enough for our formatted value.
        let mut buf = [0u8; 64];
        let len = self.write_to(&mut buf);
        // Since we know our data is all ASCII, this is safe.
        let s = unsafe { std::str::from_utf8_unchecked(&buf[..len]) };
        f.write_str(s)
    }
}

impl<S: ScaleMetrics> DecimalU64<S> {
    #[inline]
    pub const fn new(unscaled: u64) -> Self {
        Self(unscaled, PhantomData)
    }

    pub const ZERO: Self = DecimalU64::new(0);
    pub const ONE: Self = DecimalU64::new(S::SCALE_FACTOR);
    pub const TWO: Self = DecimalU64::new(2 * S::SCALE_FACTOR);
    pub const THREE: Self = DecimalU64::new(3 * S::SCALE_FACTOR);
    pub const FOUR: Self = DecimalU64::new(4 * S::SCALE_FACTOR);
    pub const FIVE: Self = DecimalU64::new(5 * S::SCALE_FACTOR);
    pub const SIX: Self = DecimalU64::new(6 * S::SCALE_FACTOR);
    pub const SEVEN: Self = DecimalU64::new(7 * S::SCALE_FACTOR);
    pub const EIGHT: Self = DecimalU64::new(8 * S::SCALE_FACTOR);
    pub const NINE: Self = DecimalU64::new(9 * S::SCALE_FACTOR);
    pub const TEN: Self = DecimalU64::new(10 * S::SCALE_FACTOR);
    pub const MAX: Self = DecimalU64::new(u64::MAX);

    /// Parses a decimal from an ASCII byte slice.
    ///
    /// # Example
    /// ```no_run
    /// use decimal64::{DecimalU64, U2};
    ///
    /// let value = DecimalU64::<U2>::from_slice(b"12.34").unwrap();
    /// assert_eq!("12.34", value.to_string());
    /// ```
    #[inline]
    pub const fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
        let mut unscaled: u64 = 0;
        let mut fractional_part_flag: u8 = 0;
        let mut scale_counter: u8 = 0;
        let mut index: usize = 0;

        while index < bytes.len() {
            let byte = bytes[index];
            match byte {
                b'0'..=b'9' => {
                    let next = match unscaled.checked_mul(10) {
                        Some(value) => value,
                        None => return Err(Error::Overflow),
                    };
                    let digit = (byte - b'0') as u64;
                    unscaled = match next.checked_add(digit) {
                        Some(value) => value,
                        None => return Err(Error::Overflow),
                    };

                    scale_counter += fractional_part_flag;
                }
                b'.' => fractional_part_flag = 1,
                other => return Err(Error::InvalidInput(InvalidInputKind::InvalidCharacter(other as char))),
            }

            index += 1;
        }

        let remaining_scale = match S::SCALE.checked_sub(scale_counter) {
            Some(remaining_scale) => remaining_scale,
            None => return Err(Error::Overflow),
        };
        let factor = SCALE_FACTORS[remaining_scale as usize];
        let unscaled = match unscaled.checked_mul(factor) {
            Some(unscaled) => unscaled,
            None => return Err(Error::Overflow),
        };

        Ok(Self(unscaled, PhantomData))
    }

    /// Parses a decimal from a UTF-8 string slice.
    ///
    /// # Example
    /// ```no_run
    /// use decimal64::{DecimalU64, U2};
    ///
    /// let value = DecimalU64::<U2>::from_str("12.34").unwrap();
    /// assert_eq!("12.34", value.to_string());
    /// ```
    pub const fn from_str(s: &str) -> Result<Self, Error> {
        Self::from_slice(s.as_bytes())
    }

    /// Converts this decimal to `f64`.
    ///
    /// ## Examples
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, U2};
    ///
    /// let value = DecimalU64::<U2>::from_str("12.34").unwrap();
    /// assert_eq!(12.34, value.to_f64());
    /// ```
    pub const fn to_f64(self) -> f64 {
        self.0 as f64 / S::SCALE_FACTOR as f64
    }

    /// Creates a decimal from `f64`, rounding half-up at the target scale.
    /// Returns error on invalid input or overflow.
    ///
    /// ## Examples
    /// No rounding.
    /// ```no_run
    /// use decimal64::{DecimalU64, U3};
    ///
    /// let value = DecimalU64::<U3>::from_f64(12.345).unwrap();
    /// assert_eq!("12.345", value.to_string());
    /// ```
    ///
    /// With rounding.
    /// ```no_run
    /// use decimal64::{DecimalU64, U2};
    ///
    /// let value = DecimalU64::<U2>::from_f64(12.345).unwrap();
    /// assert_eq!("12.35", value.to_string());
    /// ```
    pub const fn from_f64(value: f64) -> Result<Self, Error> {
        const EXP_BITS: u64 = 0x7ff;
        const EXP_BIAS: i32 = 1023;
        const MANTISSA_BITS: u32 = 52;
        const MANTISSA_MASK: u64 = (1u64 << MANTISSA_BITS) - 1;

        let bits = value.to_bits();
        let sign = bits >> 63;
        let exp_bits = ((bits >> MANTISSA_BITS) & EXP_BITS) as u16;
        let frac_bits = bits & MANTISSA_MASK;

        if exp_bits == EXP_BITS as u16 {
            return Err(Error::InvalidInput(InvalidInputKind::InfiniteNumber));
        }
        if sign == 1 && (exp_bits != 0 || frac_bits != 0) {
            return Err(Error::InvalidInput(InvalidInputKind::NegativeNumber));
        }
        if exp_bits == 0 && frac_bits == 0 {
            return Ok(Self::ZERO);
        }

        let (mantissa, exp2) = if exp_bits == 0 {
            (frac_bits as u128, 1 - EXP_BIAS - MANTISSA_BITS as i32)
        } else {
            let mantissa = ((1u64 << MANTISSA_BITS) | frac_bits) as u128;
            (mantissa, exp_bits as i32 - EXP_BIAS - MANTISSA_BITS as i32)
        };

        // value = mantissa * 2^exp2; scaling by 10^S becomes 5^S * 2^(exp2 + S).
        let base = mantissa * POW5_U128[S::SCALE as usize];
        let exp2 = exp2 + S::SCALE as i32;

        if exp2 >= 0 {
            let shift = exp2 as u32;
            if shift >= 128 {
                return Err(Error::Overflow);
            }
            if base > (u64::MAX as u128 >> shift) {
                return Err(Error::Overflow);
            }
            let unscaled = base << shift;
            Ok(DecimalU64::new(unscaled as u64))
        } else {
            let shift = (-exp2) as u32;
            if shift >= 128 {
                // Denominator exceeds u128; remainder cannot reach half, so this rounds to zero.
                return Ok(Self::ZERO);
            }
            let denom = 1u128 << shift;
            let mut unscaled = base / denom;
            let remainder = base % denom;

            if remainder != 0 && (remainder << 1) >= denom {
                if unscaled == u64::MAX as u128 {
                    return Err(Error::Overflow);
                }
                unscaled += 1;
            }

            if unscaled > u64::MAX as u128 {
                return Err(Error::Overflow);
            }

            Ok(DecimalU64::new(unscaled as u64))
        }
    }

    /// Rescales this decimal to a different scale, returning an error on overflow.
    /// Downscaling rounds half-up when fractional digits are dropped.
    ///
    /// # Example
    /// Scale up (will error on overflow).
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, U2, U4};
    ///
    /// let amount = DecimalU64::<U2>::from_str("12.34").unwrap();
    /// let upscaled = amount.rescale::<U4>().unwrap();
    /// assert_eq!("12.3400", upscaled.to_string());
    /// ```
    ///
    /// Scale down (can result in precision loss).
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, U2, U4};
    ///
    /// let amount = DecimalU64::<U4>::from_str("1.2050").unwrap();
    /// let downscaled = amount.rescale::<U2>().unwrap();
    /// assert_eq!("1.21", downscaled.to_string());
    /// ```
    pub const fn rescale<T: ScaleMetrics>(&self) -> Result<DecimalU64<T>, self::Error> {
        if T::SCALE >= S::SCALE {
            // upscale
            let factor = match 10u64.checked_pow((T::SCALE - S::SCALE) as u32) {
                Some(value) => value,
                None => return Err(Error::Overflow),
            };
            let unscaled = match self.0.checked_mul(factor) {
                Some(value) => value,
                None => return Err(Error::Overflow),
            };

            Ok(DecimalU64::<T>::new(unscaled))
        } else {
            // downscale
            let factor = match 10u64.checked_pow((S::SCALE - T::SCALE) as u32) {
                Some(value) => value,
                None => return Err(Error::Overflow),
            };
            let truncated = self.0 / factor;
            let remainder = self.0 % factor;
            let mut rounded = truncated;
            if remainder != 0 {
                let double = (remainder as u128) * 2;
                if double >= factor as u128 {
                    rounded = match truncated.checked_add(1) {
                        Some(value) => value,
                        None => return Err(Error::Overflow),
                    };
                }
            }
            Ok(DecimalU64::<T>::new(rounded))
        }
    }

    /// Split `unscaled` value into integer and fractional parts.
    ///
    /// # Example
    /// ```no_run
    ///
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, U6};
    ///
    /// let (int_part, frac_part) = DecimalU64::<U6>::from_str("123.45").unwrap().split();
    /// assert_eq!(123, int_part);
    /// assert_eq!(450000, frac_part);
    /// ```
    #[inline]
    pub const fn split(&self) -> (u64, u64) {
        let integer_part = self.0 / S::SCALE_FACTOR;
        let fractional_part = self.0 % S::SCALE_FACTOR;
        (integer_part, fractional_part)
    }

    #[inline]
    /// Writes this decimal into `buffer` and returns the number of bytes written.  The buffer must
    /// be at least `S::REQUIRED_BUFFER_LEN` bytes. Output includes trailing zeros to match the scale.
    ///
    /// If you required trimmed output, use [`Self::write_to_trimmed`].
    ///
    /// ## Examples
    /// No trailing zeroes.
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, ScaleMetrics, U2};
    ///
    /// let value = DecimalU64::<U2>::from_str("12.34").unwrap();
    /// let mut buffer = [0u8; U2::REQUIRED_BUFFER_LEN];
    /// let len = value.write_to(&mut buffer);
    /// assert_eq!("12.34", std::str::from_utf8(&buffer[..len]).unwrap());
    /// ```
    /// With trailing zeroes
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, ScaleMetrics, U2};
    ///
    /// let value = DecimalU64::<U2>::from_str("1.2").unwrap();
    /// let mut buffer = [0u8; U2::REQUIRED_BUFFER_LEN];
    /// let len = value.write_to(&mut buffer);
    /// assert_eq!("1.20", std::str::from_utf8(&buffer[..len]).unwrap());
    /// ```
    pub fn write_to(&self, buffer: &mut [u8]) -> usize {
        #[cold]
        #[inline(never)]
        fn insufficient_buffer_len(len: usize, required: usize) -> ! {
            panic!("provided buffer length {} is too small, requires at least {} bytes", len, required);
        }

        // ensure the provided buffer has enough length to write the max value
        if S::REQUIRED_BUFFER_LEN > buffer.len() {
            insufficient_buffer_len(buffer.len(), S::REQUIRED_BUFFER_LEN)
        }

        // Compute the scale factor: 10^PRECISION.
        let (int_part, frac_part) = self.split();
        let mut pos = 0;

        // Write the integer part.
        if int_part == 0 {
            // SAFETY we already checked the destination buffer is of sufficient size
            unsafe {
                *buffer.get_unchecked_mut(pos) = b'0';
            }
            pos += 1;
        } else {
            let mut tmp = int_part;
            let mut digit_count = 0;
            while tmp != 0 {
                digit_count += 1;
                tmp /= 10;
            }
            pos += digit_count;
            let mut idx = pos;
            tmp = int_part;
            while tmp != 0 {
                idx -= 1;
                // SAFETY we already checked the destination buffer is of sufficient size
                unsafe {
                    *buffer.get_unchecked_mut(idx) = b'0' + (tmp % 10) as u8;
                }
                tmp /= 10;
            }
        }

        // If there is a fractional part, write the decimal point and fractional digits.
        if S::SCALE > 0 {
            // SAFETY we already checked the destination buffer is of sufficient size
            unsafe {
                *buffer.get_unchecked_mut(pos) = b'.';
            }
            pos += 1;
            // Start with the highest power of 10 for the fractional part.
            let mut divisor = 10u64.pow((S::SCALE - 1) as u32);
            let mut frac = frac_part;
            for _ in 0..S::SCALE {
                let digit = frac / divisor;
                // SAFETY we already checked the destination buffer is of sufficient size
                unsafe {
                    *buffer.get_unchecked_mut(pos) = b'0' + (digit as u8);
                }
                pos += 1;
                frac %= divisor;
                divisor /= 10;
            }
        }

        pos
    }

    /// Writes this decimal into `buffer` without trailing fractional zeros.
    ///
    /// If you required untrimmed output, use [`Self::write_to`].
    ///
    /// # Example
    /// ```no_run
    /// use std::str::FromStr;
    /// use decimal64::{DecimalU64, U4};
    ///
    /// let value = DecimalU64::<U4>::from_str("12.3400").unwrap();
    /// let mut buffer = [0u8; 32];
    /// let len = value.write_to_trimmed(&mut buffer);
    /// assert_eq!("12.34", std::str::from_utf8(&buffer[..len]).unwrap());
    /// ```
    pub fn write_to_trimmed(&self, buffer: &mut [u8]) -> usize {
        let len = self.write_to(buffer);
        if S::SCALE == 0 {
            return len;
        }

        let mut end = len;
        while end > 0 {
            // SAFETY: end > 0 and end <= len <= buffer.len()
            let byte = unsafe { *buffer.get_unchecked(end - 1) };
            if byte != b'0' {
                break;
            }
            end -= 1;
        }
        if end > 0 {
            // SAFETY: end > 0 and end <= len <= buffer.len()
            let byte = unsafe { *buffer.get_unchecked(end - 1) };
            if byte == b'.' {
                end -= 1;
            }
        }

        end
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_not_increase_size() {
        assert_eq!(std::mem::size_of::<u64>(), std::mem::size_of::<DecimalU64<U0>>());
        assert_eq!(std::mem::size_of::<u64>(), std::mem::size_of::<DecimalU64<U4>>());
        assert_eq!(std::mem::size_of::<u64>(), std::mem::size_of::<DecimalU64<U8>>());
    }

    #[test]
    fn should_parse_from_bytes() -> anyhow::Result<()> {
        assert_eq!(18446744073709551615, DecimalU64::<U0>::from_str("18446744073709551615")?.0);
        assert_eq!(18446744073709551615, DecimalU64::<U8>::from_str("184467440737.09551615")?.0);
        assert_eq!(12345000000, DecimalU64::<U8>::from_str("123.45000000")?.0);
        assert_eq!(12300000000, DecimalU64::<U8>::from_str("123")?.0);
        assert_eq!(12300000000, DecimalU64::<U8>::from_str("123.")?.0);
        assert_eq!(12300000000, DecimalU64::<U8>::from_str("123.0")?.0);
        assert_eq!(18446744073709551615, DecimalU64::<U8>::from_str("184467440737.09551615")?.0);
        assert_eq!(0, DecimalU64::<U8>::from_str("0.0")?.0);
        assert_eq!(0, DecimalU64::<U8>::from_str("0")?.0);
        Ok(())
    }

    #[test]
    fn should_use_target_scale() -> anyhow::Result<()> {
        assert_eq!(12345600000, DecimalU64::<U8>::from_str("123.456")?.0);
        assert_eq!(1234560000, DecimalU64::<U7>::from_str("123.456")?.0);
        assert_eq!(123456000, DecimalU64::<U6>::from_str("123.456")?.0);
        assert_eq!(12345600, DecimalU64::<U5>::from_str("123.456")?.0);
        assert_eq!(1234560, DecimalU64::<U4>::from_str("123.456")?.0);
        assert_eq!(123456, DecimalU64::<U3>::from_str("123.456")?.0);
        assert!(DecimalU64::<U2>::from_str("123.456").is_err());
        assert!(DecimalU64::<U1>::from_str("123.456").is_err());
        assert!(DecimalU64::<U0>::from_str("123.456").is_err());
        Ok(())
    }

    #[test]
    fn should_split() -> anyhow::Result<()> {
        assert_eq!((123, 45000000), DecimalU64::<U8>::from_str("123.45000000")?.split());
        assert_eq!((0, 45000000), DecimalU64::<U8>::from_str("0.45000000")?.split());
        assert_eq!((0, 0), DecimalU64::<U8>::from_str("0.0")?.split());
        assert_eq!((123, 45000001), DecimalU64::<U8>::from_str("123.45000001")?.split());
        assert_eq!((123, 45100000), DecimalU64::<U8>::from_str("123.451")?.split());
        Ok(())
    }

    #[test]
    fn should_compare_for_eq() -> anyhow::Result<()> {
        let one = DecimalU64::<U8>::from_str("123.45000000")?;
        let two = DecimalU64::<U8>::from_str("123.45000000")?;
        assert_eq!(one, two);
        let one = DecimalU64::<U8>::from_str("123.45000000")?;
        let two = DecimalU64::<U8>::from_str("123.45000001")?;
        assert_ne!(one, two);
        let one = DecimalU64::<U8>::from_str("0.0")?;
        let two = DecimalU64::<U8>::from_str("0.0")?;
        assert_eq!(one, two);
        Ok(())
    }

    #[test]
    fn should_compare_for_ord() -> anyhow::Result<()> {
        let one = DecimalU64::<U8>::from_str("123.45000001")?;
        let two = DecimalU64::<U8>::from_str("123.45000000")?;
        assert!(one > two);
        let one = DecimalU64::<U8>::from_str("123.45000000")?;
        let two = DecimalU64::<U8>::from_str("123.45000001")?;
        assert!(one < two);
        let one = DecimalU64::<U8>::from_str("0.0")?;
        let two = DecimalU64::<U8>::from_str("0.0")?;
        assert!(one >= two);
        let one = DecimalU64::<U8>::from_str("0.0")?;
        let two = DecimalU64::<U8>::from_str("0.0")?;
        assert!(one <= two);
        Ok(())
    }

    #[test]
    fn should_err_if_number_too_large() {
        let err = DecimalU64::<U8>::from_str("184467440737.09551616");
        assert!(err.is_err());
        if let Err(err) = err {
            assert!(matches!(err, Error::Overflow));
        }
    }

    #[test]
    fn should_create_from_str() {
        assert_eq!(12345000001, DecimalU64::<U8>::from_str("123.45000001").unwrap().0);
    }

    #[test]
    fn should_error_on_from_f64_overflow() {
        let err = DecimalU64::<U0>::from_f64(1e30);
        assert!(matches!(err, Err(Error::Overflow)));
    }

    #[test]
    fn should_write_to_buffer() -> anyhow::Result<()> {
        let mut buf = [0u8; 1024];

        let dec = DecimalU64::<U8>::from_str("123.45000001")?;
        assert_eq!(12, dec.write_to(&mut buf));
        assert_eq!("123.45000001", std::str::from_utf8(&buf[..12])?);

        let dec = DecimalU64::<U6>::from_str("123.45")?;
        assert_eq!(10, dec.write_to(&mut buf));
        assert_eq!("123.450000", std::str::from_utf8(&buf[..10])?);

        let dec = DecimalU64::<U0>::from_str("12345")?;
        assert_eq!(5, dec.write_to(&mut buf));
        assert_eq!("12345", std::str::from_utf8(&buf[..5])?);

        let dec = DecimalU64::<U0>::from_str("0")?;
        assert_eq!(1, dec.write_to(&mut buf));
        assert_eq!("0", std::str::from_utf8(&buf[..1])?);

        let dec = DecimalU64::<U8>::from_str("0")?;
        assert_eq!(10, dec.write_to(&mut buf));
        assert_eq!("0.00000000", std::str::from_utf8(&buf[..10])?);

        Ok(())
    }

    #[test]
    fn should_display_to_string() -> anyhow::Result<()> {
        assert_eq!("123.450000", DecimalU64::<U6>::from_str("123.45")?.to_string());
        assert_eq!("123.45", DecimalU64::<U2>::from_str("123.45")?.to_string());
        assert_eq!("123.45000000", DecimalU64::<U8>::from_str("123.45")?.to_string());
        assert_eq!("0.00000000", DecimalU64::<U8>::from_str("0")?.to_string());
        assert_eq!("0", DecimalU64::<U0>::from_str("0")?.to_string());
        assert_eq!("10", DecimalU64::<U0>::from_str("10")?.to_string());
        Ok(())
    }

    #[test]
    fn should_default_to_zero() {
        assert_eq!("0.00000000", DecimalU64::<U8>::default().to_string());
        assert_eq!("0.0000000", DecimalU64::<U7>::default().to_string());
        assert_eq!("0.000000", DecimalU64::<U6>::default().to_string());
        assert_eq!("0.00000", DecimalU64::<U5>::default().to_string());
        assert_eq!("0.0000", DecimalU64::<U4>::default().to_string());
        assert_eq!("0.000", DecimalU64::<U3>::default().to_string());
        assert_eq!("0.00", DecimalU64::<U2>::default().to_string());
        assert_eq!("0.0", DecimalU64::<U1>::default().to_string());
        assert_eq!("0", DecimalU64::<U0>::default().to_string());
    }

    #[test]
    fn should_create_from_raw() {
        assert_eq!("0.00000123", DecimalU64::<U8>::new(123).to_string());
        assert_eq!("0.0000123", DecimalU64::<U7>::new(123).to_string());
        assert_eq!("123", DecimalU64::<U0>::new(123).to_string());
    }

    #[test]
    fn should_use_constant_zero() {
        assert_eq!("0.00000000", DecimalU64::<U8>::ZERO.to_string());
        assert_eq!("0.0000000", DecimalU64::<U7>::ZERO.to_string());
        assert_eq!("0.000000", DecimalU64::<U6>::ZERO.to_string());
        assert_eq!("0.00000", DecimalU64::<U5>::ZERO.to_string());
        assert_eq!("0.0000", DecimalU64::<U4>::ZERO.to_string());
        assert_eq!("0.000", DecimalU64::<U3>::ZERO.to_string());
        assert_eq!("0.00", DecimalU64::<U2>::ZERO.to_string());
        assert_eq!("0.0", DecimalU64::<U1>::ZERO.to_string());
        assert_eq!("0", DecimalU64::<U0>::ZERO.to_string());
    }

    #[test]
    fn should_use_constant_one() {
        assert_eq!("1.00000000", DecimalU64::<U8>::ONE.to_string());
        assert_eq!("1.0000000", DecimalU64::<U7>::ONE.to_string());
        assert_eq!("1.000000", DecimalU64::<U6>::ONE.to_string());
        assert_eq!("1.00000", DecimalU64::<U5>::ONE.to_string());
        assert_eq!("1.0000", DecimalU64::<U4>::ONE.to_string());
        assert_eq!("1.000", DecimalU64::<U3>::ONE.to_string());
        assert_eq!("1.00", DecimalU64::<U2>::ONE.to_string());
        assert_eq!("1.0", DecimalU64::<U1>::ONE.to_string());
        assert_eq!("1", DecimalU64::<U0>::ONE.to_string());
    }

    #[test]
    fn should_use_constant_three() {
        assert_eq!("3.00000000", DecimalU64::<U8>::THREE.to_string());
        assert_eq!("3.0000000", DecimalU64::<U7>::THREE.to_string());
        assert_eq!("3.000000", DecimalU64::<U6>::THREE.to_string());
        assert_eq!("3.00000", DecimalU64::<U5>::THREE.to_string());
        assert_eq!("3.0000", DecimalU64::<U4>::THREE.to_string());
        assert_eq!("3.000", DecimalU64::<U3>::THREE.to_string());
        assert_eq!("3.00", DecimalU64::<U2>::THREE.to_string());
        assert_eq!("3.0", DecimalU64::<U1>::THREE.to_string());
        assert_eq!("3", DecimalU64::<U0>::THREE.to_string());
    }

    #[test]
    fn should_use_constant_max() {
        assert_eq!("184467440737.09551615", DecimalU64::<U8>::MAX.to_string());
        assert_eq!("1844674407370.9551615", DecimalU64::<U7>::MAX.to_string());
        assert_eq!("18446744073709.551615", DecimalU64::<U6>::MAX.to_string());
        assert_eq!("184467440737095.51615", DecimalU64::<U5>::MAX.to_string());
        assert_eq!("1844674407370955.1615", DecimalU64::<U4>::MAX.to_string());
        assert_eq!("18446744073709551.615", DecimalU64::<U3>::MAX.to_string());
        assert_eq!("184467440737095516.15", DecimalU64::<U2>::MAX.to_string());
        assert_eq!("1844674407370955161.5", DecimalU64::<U1>::MAX.to_string());
        assert_eq!("18446744073709551615", DecimalU64::<U0>::MAX.to_string());
    }

    #[test]
    fn should_write_max_to_buffer() {
        fn write_max<S: ScaleMetrics>(buffer: &mut [u8], value: DecimalU64<S>) -> usize {
            value.write_to(buffer)
        }

        let mut buffer = [0u8; 1024];

        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U8>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U7>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U6>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U5>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U4>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U3>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U2>::MAX));
        assert_eq!(21, write_max(&mut buffer, DecimalU64::<U1>::MAX));
        assert_eq!(20, write_max(&mut buffer, DecimalU64::<U0>::MAX));
    }

    #[test]
    #[should_panic(expected = "provided buffer length 1 is too small, requires at least 21 bytes")]
    fn should_panic_if_buffer_too_small() {
        let mut buffer = [0u8; 1];
        DecimalU64::<U8>::MAX.write_to(&mut buffer);
    }

    #[test]
    fn should_write_if_buffer_is_of_exact_size() {
        let mut buffer = [0u8; U8::REQUIRED_BUFFER_LEN];
        DecimalU64::<U8>::MAX.write_to(&mut buffer);
    }
}

#[cfg(test)]
mod rescale_tests {
    use crate::error::Error;
    use crate::{DecimalU64, ScaleMetrics, U0, U1, U2, U3, U4, U5, U7, U8};
    use rstest_macros::rstest;

    // Generic rescale test for checked rescale when no rounding is needed.
    fn rescale<S1: ScaleMetrics, S2: ScaleMetrics>(s: &'static str) {
        let s1 = DecimalU64::<S1>::from_str(s).unwrap();
        let s2 = s1.rescale::<S2>().unwrap();

        // Compare decimal strings ignoring trailing zeros
        assert_eq!(
            s1.to_string().trim_end_matches('0').trim_end_matches('.'),
            s2.to_string().trim_end_matches('0').trim_end_matches('.')
        );
    }

    #[rstest]
    #[case("0")]
    #[case("1")]
    #[case("0.01")]
    #[case("1.25")]
    #[case("123.45")]
    fn should_rescale_up(#[case] s: &'static str) {
        rescale::<U2, U5>(s);
        rescale::<U2, U8>(s);
        rescale::<U3, U5>(s);
        rescale::<U5, U8>(s);
    }

    #[rstest]
    #[case("0")]
    #[case("1")]
    #[case("10")]
    #[case("123")]
    #[case("1.20")]
    #[case("123.450")]
    fn should_rescale_down(#[case] s: &'static str) {
        rescale::<U8, U5>(s);
        rescale::<U8, U2>(s);
        rescale::<U5, U2>(s);
        rescale::<U7, U4>(s);
    }

    #[rstest]
    #[case("50", "50")]
    #[case("12345", "12345")]
    fn should_not_rescale_with_same_base(#[case] s: &'static str, #[case] expected: &str) {
        let d = DecimalU64::<U4>::from_str(s).unwrap();
        let res = d.rescale::<U4>().unwrap();

        // Compare decimal strings ignoring trailing zeros
        assert_eq!(res.to_string().trim_end_matches('0').trim_end_matches('.'), expected);
    }

    #[rstest]
    #[case("12345")]
    #[case("123400")]
    fn should_round_trip_invariant(#[case] s: &'static str) {
        let d = DecimalU64::<U2>::from_str(s).unwrap();
        let up: DecimalU64<U8> = d.rescale().unwrap();
        let down: DecimalU64<U2> = up.rescale().unwrap();

        // Compare decimal values, not unscaled
        assert_eq!(d.to_string().trim_end_matches('0'), down.to_string().trim_end_matches('0'));
    }

    #[rstest]
    #[case("1.234", "1.23")]
    #[case("1.235", "1.24")]
    #[case("1.236", "1.24")]
    #[case("9.995", "10.00")]
    #[case("0.004", "0.00")]
    #[case("0.005", "0.01")]
    fn should_round_downscale_u3_to_u2(#[case] input: &str, #[case] expected: &str) {
        let d = DecimalU64::<U3>::from_str(input).unwrap();
        let result: DecimalU64<U2> = d.rescale().unwrap();
        assert_eq!(expected, result.to_string());
    }

    #[test]
    fn should_round_downscale_u8_to_u0() {
        let d = DecimalU64::<U8>::from_str("1.50000000").unwrap();
        let result: DecimalU64<U0> = d.rescale().unwrap();
        assert_eq!("2", result.to_string());

        let d = DecimalU64::<U8>::from_str("1.49999999").unwrap();
        let result: DecimalU64<U0> = d.rescale().unwrap();
        assert_eq!("1", result.to_string());
    }

    #[test]
    fn should_round_on_downscale() {
        let d = DecimalU64::<U4>::from_str("101.2038").unwrap(); // 4 decimal places
        let result = d.rescale::<U2>().unwrap(); // Downscale to 2 decimals
        assert_eq!("101.20", result.to_string());

        let d = DecimalU64::<U4>::from_str("101.2050").unwrap(); // exactly half
        let result = d.rescale::<U2>().unwrap();
        assert_eq!("101.21", result.to_string());
    }

    #[test]
    fn should_error_on_overflow() {
        // Try to upscale MAX value at U0 to U1 (would multiply by 10, causing overflow)
        let d = DecimalU64::<U0>::MAX;
        let result: Result<DecimalU64<U1>, Error> = d.rescale();

        assert!(result.is_err());
        match result {
            Err(Error::Overflow) => {}
            _ => panic!("Expected Overflow error"),
        }
    }

    #[test]
    fn should_handle_upscale_overflow_boundary() {
        let max_ok = DecimalU64::<U0>::new(u64::MAX / 10);
        let up: DecimalU64<U1> = max_ok.rescale().unwrap();
        assert_eq!(max_ok.0 * 10, up.0);

        let too_big = DecimalU64::<U0>::new(u64::MAX / 10 + 1);
        let result: Result<DecimalU64<U1>, Error> = too_big.rescale();
        assert!(matches!(result, Err(Error::Overflow)));
    }
}

#[cfg(test)]
mod f64_tests {
    use crate::error::{Error, InvalidInputKind};
    use crate::{DecimalU64, U2};

    #[test]
    fn should_convert_to_f64() {
        const VALUE: f64 = DecimalU64::<U2>::new(1234).to_f64();
        assert!((VALUE - 12.34).abs() < f64::EPSILON);
    }

    #[test]
    fn should_create_from_f64() -> anyhow::Result<()> {
        let dec = DecimalU64::<U2>::from_f64(12.25)?;
        assert_eq!("12.25", dec.to_string());
        Ok(())
    }

    #[test]
    fn should_create_from_f64_as_const() {
        const VALUE: Result<DecimalU64<U2>, Error> = DecimalU64::from_f64(12.25);
        assert_eq!("12.25", VALUE.unwrap().to_string());
    }

    #[test]
    fn should_round_from_f64_half_up() -> anyhow::Result<()> {
        let dec = DecimalU64::<U2>::from_f64(0.125)?;
        assert_eq!("0.13", dec.to_string());
        Ok(())
    }

    #[test]
    fn should_error_on_from_f64_infinity() {
        let err = DecimalU64::<U2>::from_f64(f64::INFINITY);
        assert!(matches!(err, Err(Error::InvalidInput(InvalidInputKind::InfiniteNumber))));
    }

    #[test]
    fn should_error_on_from_f64_negative() {
        let err = DecimalU64::<U2>::from_f64(-1.0);
        assert!(matches!(err, Err(Error::InvalidInput(InvalidInputKind::NegativeNumber))));
    }
}