brine-fp 0.3.0

192-bit fixed-point math library with logarithmic and exponential functions. Designed for blockchain, scientific, and financial applications.
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
use super::consts::*;
use super::signed::SignedNumeric;
use super::InnerUint;
use core::convert::*;
use core::ops::{Add, Sub, Mul, Div};

#[cfg(not(feature = "std"))]
use alloc::{format, string::String};

// Based on the following implementations:
// https://github.com/solana-labs/solana-program-library/blob/v2.0/libraries/math/src/precise_number.rs
// https://github.com/StrataFoundation/strata/blob/master/programs/spl-token-bonding/src/precise_number.rs

/// A `UnsignedNumeric` is an unsigned 192-bit fixed-point number with 18 decimal places of
/// precision.
///
/// ### Internal Representation
/// Internally, the value is stored as a [`InnerUint`], which wraps a little-endian array `[u64; 3]`.
/// This means the layout is:
///
/// ```text
/// InnerUint([lo, mid, hi])
/// // equivalent to:
/// // value = lo + (mid << 64) + (hi << 128)
/// ```
///
/// Each component contributes to the full 192-bit value:
///
/// ```text
/// value = (hi × 2^128) + (mid × 2^64) + lo
/// ```
///
/// ### Fixed-Point Scaling
/// All values are scaled by [`ONE`] (10^18). That is, the internal number is interpreted
/// as `raw / ONE` to recover its real-world value.
///
/// Examples:
/// - `InnerUint([1_000_000_000_000_000_000, 0, 0])` → 1.0
/// - `InnerUint([500_000_000_000_000_000, 0, 0])` → 0.5
/// - `InnerUint([2_000_000_000_000_000_000, 0, 0])` → 2.0
///
/// ### Example: High-Bit Usage
///
/// When you write:
/// ```text
/// let a = UnsignedNumeric::from([0, 0, 1]);
/// ```
/// This initializes the internal 192-bit value with the array `[0, 0, 1]`.
/// In this representation:
///
/// - `0` is the least significant 64 bits (`lo`)
/// - `0` is the middle 64 bits (`mid`)
/// - `1` is the most significant 64 bits (`hi`)
///
/// The actual 192-bit value is computed as:
///
/// ```text
/// value = (1 × 2^128) + (0 × 2^64) + 0 = 2^128
///       = 340282366920938463463374607431768211456
/// ```
///
/// Since this is a fixed-point number, the real-world value is:
///
/// ```text
/// real_value = value / 10^18 = 340282366920938463463.374607431768211456
/// ```
///
/// This system allows for both extremely high precision and a vast dynamic range,
/// making [`UnsignedNumeric`] ideal for financial, scientific, or blockchain applications
/// where `f64` or even `u128` would lose accuracy or overflow.
#[derive(Clone, Debug, PartialEq)]
pub struct UnsignedNumeric {
    /// Internal value stored as a 192-bit integer, scaled by ONE (10^18).
    pub value: InnerUint,
}

impl UnsignedNumeric {
    /// Returns a `UnsignedNumeric` representing 0.0.
    pub fn zero() -> Self {
        Self { value: zero() }
    }

    /// Returns a `UnsignedNumeric` representing 1.0.
    pub fn one() -> Self {
        Self { value: one() }
    }

    /// Constructs a `UnsignedNumeric` from an integer value by scaling it by ONE (10^18).
    /// For example, `new(7)` produces `7.0`.
    pub fn new(value: u128) -> Self {
        // `one()` is 10^18 and 10^18 * u128::MAX will always fit within 196 bits
        let value = InnerUint::from(value).checked_mul(one()).unwrap();
        Self { value }
    }

    /// Constructs a `UnsignedNumeric` from a `u128` that is already scaled by ONE (i.e. in fixed-point space).
    /// This bypasses internal multiplication and is useful for constants or pre-scaled data.
    pub fn from_scaled_u128(value: u128) -> Self {
        Self {
            value: InnerUint::from(value),
        }
    }

    /// Constructs a `UnsignedNumeric` directly from a raw `[u64; 3]` value.
    /// The input is interpreted as already scaled (fixed-point).
    /// Layout is little-endian: `[lo, mid, hi]` = `lo + (mid << 64) + (hi << 128)`.
    pub fn from_values(lo: u64, mid: u64, hi: u64) -> Self {
        Self {
            value: InnerUint([lo, mid, hi]),
        }
    }

    /// Converts this `UnsignedNumeric` into a raw `[u8; 24]` representation.
    pub fn to_bytes(&self) -> [u8; 24] {
        let InnerUint([lo, mid, hi]) = self.value;

        let mut bytes = [0u8; 24];
        bytes[0..8].copy_from_slice(&lo.to_le_bytes());
        bytes[8..16].copy_from_slice(&mid.to_le_bytes());
        bytes[16..24].copy_from_slice(&hi.to_le_bytes());

        bytes
    }

    /// Converts a raw `[u8; 24]` representation into a `UnsignedNumeric`.
    pub fn from_bytes(bytes: &[u8; 24]) -> Self {
        let lo = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
        let mid = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
        let hi = u64::from_le_bytes(bytes[16..24].try_into().unwrap());

        Self {
            value: InnerUint([lo, mid, hi]),
        }
    }

    /// Converts this `UnsignedNumeric` into a regular `u128` by dividing by ONE.
    /// Applies rounding correction to avoid always flooring the result.
    /// Returns `None` if the division would overflow or the result exceeds `u128::MAX`.
    pub fn to_imprecise(&self) -> Option<u128> {
        self.value
            .checked_add(Self::rounding_correction())?
            .checked_div(one())
            .map(|v| v.as_u128())
    }

    /// Converts this `UnsignedNumeric` into a signed version,
    /// wrapping it in a `SignedNumeric` with `is_negative = false`.
    /// Useful when beginning arithmetic that may result in negative values.
    pub fn signed(&self) -> SignedNumeric {
        SignedNumeric {
            value: self.clone(),
            is_negative: false,
        }
    }

    /// Returns a rounding correction (0.5) used in division/multiplication
    /// to mitigate truncation from integer floor behavior.
    /// This simulates "round-to-nearest" by adding half the divisor.
    fn rounding_correction() -> InnerUint {
        InnerUint::from(ONE / 2)
    }

    /// Compares two `UnsignedNumeric`s for approximate equality,
    /// allowing for a configurable `precision` window.
    pub fn almost_eq(&self, rhs: &Self, precision: InnerUint) -> bool {
        let (difference, _) = self.unsigned_sub(rhs);
        difference.value < precision
    }

    /// Returns `true` if `self < rhs` in fixed-point terms.
    pub fn less_than(&self, rhs: &Self) -> bool {
        self.value < rhs.value
    }

    /// Returns `true` if `self > rhs`.
    pub fn greater_than(&self, rhs: &Self) -> bool {
        self.value > rhs.value
    }

    /// Returns `true` if `self <= rhs`.
    pub fn less_than_or_equal(&self, rhs: &Self) -> bool {
        self.value <= rhs.value
    }

    /// Returns `true` if `self >= rhs`.
    pub fn greater_than_or_equal(&self, rhs: &Self) -> bool {
        self.value >= rhs.value
    }

    /// Rounds down to the nearest whole number by truncating fractional digits.
    pub fn floor(&self) -> Option<Self> {
        let value = self.value.checked_div(one())?.checked_mul(one())?;
        Some(Self { value })
    }

    /// Rounds up to the nearest whole number.
    pub fn ceiling(&self) -> Option<Self> {
        let value = self
            .value
            .checked_add(one().checked_sub(InnerUint::from(1))?)?
            .checked_div(one())?
            .checked_mul(one())?;
        Some(Self { value })
    }

    /// Divides `self / rhs` in fixed-point space, maintaining precision.
    /// Applies rounding correction to minimize truncation error.
    /// Returns `None` on divide-by-zero or overflow.
    pub fn checked_div(&self, rhs: &Self) -> Option<Self> {
        if *rhs == Self::zero() {
            return None;
        }
        match self.value.checked_mul(one()) {
            Some(v) => {
                let value = v
                    .checked_add(Self::rounding_correction())?
                    .checked_div(rhs.value)?;
                Some(Self { value })
            }
            None => {
                let value = self
                    .value
                    .checked_add(Self::rounding_correction())?
                    .checked_div(rhs.value)?
                    .checked_mul(one())?;
                Some(Self { value })
            }
        }
    }

    /// Multiplies two `UnsignedNumeric`s and returns the result in fixed-point space.
    /// Automatically divides by ONE to maintain correct scaling, and applies rounding correction.
    /// Falls back to a reduced-precision path if full multiplication would overflow.
    pub fn checked_mul(&self, rhs: &Self) -> Option<Self> {
        match self.value.checked_mul(rhs.value) {
            Some(v) => {
                let value = v
                    .checked_add(Self::rounding_correction())?
                    .checked_div(one())?;
                Some(Self { value })
            }
            None => {
                let value = if self.value >= rhs.value {
                    self.value.checked_div(one())?.checked_mul(rhs.value)?
                } else {
                    rhs.value.checked_div(one())?.checked_mul(self.value)?
                };
                Some(Self { value })
            }
        }
    }

    /// Adds two precise numbers. Returns `None` on overflow.
    pub fn checked_add(&self, rhs: &Self) -> Option<Self> {
        let value = self.value.checked_add(rhs.value)?;
        Some(Self { value })
    }

    /// Subtracts `rhs` from `self`. Returns `None` if the result would be negative.
    pub fn checked_sub(&self, rhs: &Self) -> Option<Self> {
        let value = self.value.checked_sub(rhs.value)?;
        Some(Self { value })
    }

    /// Computes the absolute difference between two numbers.
    /// Returns the result and a boolean indicating whether the result was originally negative.
    pub fn unsigned_sub(&self, rhs: &Self) -> (Self, bool) {
        match self.value.checked_sub(rhs.value) {
            None => {
                let value = rhs.value.checked_sub(self.value).unwrap();
                (Self { value }, true)
            }
            Some(value) => (Self { value }, false),
        }
    }

    /// Converts the precise number into a human-readable decimal string with full 18-digit precision.
    ///
    /// For example, a number representing 3.1415 will be displayed as:
    /// `"3.141500000000000000"`
    pub fn to_string(&self) -> String {
        let whole = self.floor().unwrap().to_imprecise().unwrap();
        let decimals = self
            .checked_sub(&UnsignedNumeric::new(whole))
            .unwrap()
            .checked_mul(&UnsignedNumeric::new(ONE))
            .unwrap()
            .to_imprecise()
            .unwrap();
        format!("{}.{:0>width$}", whole, decimals, width = 18)
    }
}

// Standard arithmetic trait implementations
impl Add for UnsignedNumeric {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        self.checked_add(&rhs).unwrap()
    }
}

impl Add<&UnsignedNumeric> for UnsignedNumeric {
    type Output = Self;

    fn add(self, rhs: &Self) -> Self::Output {
        self.checked_add(rhs).unwrap()
    }
}

impl Add<UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn add(self, rhs: UnsignedNumeric) -> Self::Output {
        self.checked_add(&rhs).unwrap()
    }
}

impl Add<&UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn add(self, rhs: &UnsignedNumeric) -> Self::Output {
        self.checked_add(rhs).unwrap()
    }
}

impl Sub for UnsignedNumeric {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        self.checked_sub(&rhs).unwrap()
    }
}

impl Sub<&UnsignedNumeric> for UnsignedNumeric {
    type Output = Self;

    fn sub(self, rhs: &Self) -> Self::Output {
        self.checked_sub(rhs).unwrap()
    }
}

impl Sub<UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn sub(self, rhs: UnsignedNumeric) -> Self::Output {
        self.checked_sub(&rhs).unwrap()
    }
}

impl Sub<&UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn sub(self, rhs: &UnsignedNumeric) -> Self::Output {
        self.checked_sub(rhs).unwrap()
    }
}

impl Mul for UnsignedNumeric {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        self.checked_mul(&rhs).unwrap()
    }
}

impl Mul<&UnsignedNumeric> for UnsignedNumeric {
    type Output = Self;

    fn mul(self, rhs: &Self) -> Self::Output {
        self.checked_mul(rhs).unwrap()
    }
}

impl Mul<UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn mul(self, rhs: UnsignedNumeric) -> Self::Output {
        self.checked_mul(&rhs).unwrap()
    }
}

impl Mul<&UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn mul(self, rhs: &UnsignedNumeric) -> Self::Output {
        self.checked_mul(rhs).unwrap()
    }
}

impl Div for UnsignedNumeric {
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        self.checked_div(&rhs).unwrap()
    }
}

impl Div<&UnsignedNumeric> for UnsignedNumeric {
    type Output = Self;

    fn div(self, rhs: &Self) -> Self::Output {
        self.checked_div(rhs).unwrap()
    }
}

impl Div<UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn div(self, rhs: UnsignedNumeric) -> Self::Output {
        self.checked_div(&rhs).unwrap()
    }
}

impl Div<&UnsignedNumeric> for &UnsignedNumeric {
    type Output = UnsignedNumeric;

    fn div(self, rhs: &UnsignedNumeric) -> Self::Output {
        self.checked_div(rhs).unwrap()
    }
}

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

    fn max_numeric() -> UnsignedNumeric {
        UnsignedNumeric {
            value: InnerUint::MAX,
        }
    }

    #[test]
    fn test_zero_and_one() {
        assert_eq!(UnsignedNumeric::zero().value, InnerUint::from(0));
        assert_eq!(UnsignedNumeric::one().value, InnerUint::from(ONE));
    }

    #[test]
    fn test_from_scaled_u128() {
        let n = UnsignedNumeric::from_scaled_u128(42 * ONE);
        assert_eq!(n.to_imprecise().unwrap(), 42);
    }

    #[test]
    fn test_to_string_exact() {
        let n = UnsignedNumeric::new(3);
        assert_eq!(n.to_string(), "3.000000000000000000");
    }

    #[test]
    fn test_to_string_fractional() {
        let mut n = UnsignedNumeric::new(3);
        n.value += InnerUint::from(250_000_000_000_000_000u128); // +0.25
        assert_eq!(n.to_string(), "3.250000000000000000");
    }

    #[test]
    fn test_checked_add() {
        let a = UnsignedNumeric::new(1);
        let b = UnsignedNumeric::new(2);
        let sum = a.checked_add(&b).unwrap();
        assert_eq!(sum.to_imprecise().unwrap(), 3);
    }

    #[test]
    fn test_checked_sub_underflow() {
        let a = UnsignedNumeric::new(1);
        let b = UnsignedNumeric::new(2);
        assert!(a.checked_sub(&b).is_none());
    }

    #[test]
    fn test_checked_sub_valid() {
        let a = UnsignedNumeric::new(3);
        let b = UnsignedNumeric::new(1);
        let result = a.checked_sub(&b).unwrap();
        assert_eq!(result.to_imprecise().unwrap(), 2);
    }

    #[test]
    fn test_checked_mul_simple() {
        let a = UnsignedNumeric::new(2);
        let b = UnsignedNumeric::new(3);
        let product = a.checked_mul(&b).unwrap();
        assert_eq!(product.to_imprecise().unwrap(), 6);
    }

    #[test]
    fn test_checked_div_exact() {
        let a = UnsignedNumeric::new(6);
        let b = UnsignedNumeric::new(2);
        let result = a.checked_div(&b).unwrap();
        assert_eq!(result.to_imprecise().unwrap(), 3);
    }

    #[test]
    fn test_checked_div_rounded() {
        let a = UnsignedNumeric::new(1);
        let b = UnsignedNumeric::new(3); // 1 / 3

        let result = a.checked_div(&b).unwrap();
        let expected = UnsignedNumeric::from_scaled_u128(333_333_333_333_333_333); // ~0.333...

        assert!(result.almost_eq(&expected, InnerUint::from(1_000_000)));
    }

    #[test]
    fn test_unsigned_sub_positive() {
        let a = UnsignedNumeric::new(7);
        let b = UnsignedNumeric::new(3);
        let (result, is_negative) = a.unsigned_sub(&b);
        assert_eq!(result.to_imprecise().unwrap(), 4);
        assert!(!is_negative);
    }

    #[test]
    fn test_unsigned_sub_negative() {
        let a = UnsignedNumeric::new(3);
        let b = UnsignedNumeric::new(7);
        let (result, is_negative) = a.unsigned_sub(&b);
        assert_eq!(result.to_imprecise().unwrap(), 4);
        assert!(is_negative);
    }

    #[test]
    fn test_almost_eq_within_precision() {
        let a = UnsignedNumeric::new(5);
        let mut b = a.clone();
        b.value += InnerUint::from(10); // Very slight difference

        assert!(a.almost_eq(&b, InnerUint::from(20)));
        assert!(!a.almost_eq(&b, InnerUint::from(5)));
    }

    #[test]
    fn test_comparisons() {
        let a = UnsignedNumeric::new(1);
        let b = UnsignedNumeric::new(2);
        assert!(a.less_than(&b));
        assert!(b.greater_than(&a));
        assert!(a.less_than_or_equal(&b));
        assert!(b.greater_than_or_equal(&a));
        assert!(a.less_than_or_equal(&a));
        assert!(a.greater_than_or_equal(&a));
    }

    #[test]
    fn test_signed_conversion() {
        let u = UnsignedNumeric::new(42);
        let s = u.signed();
        assert_eq!(s.value, u);
        assert!(!s.is_negative);
    }

    #[test]
    fn test_serialization() {
        let original = UnsignedNumeric::from_values(123, 456, 789);
        let bytes = original.to_bytes();
        let recovered = UnsignedNumeric::from_bytes(&bytes);

        assert_eq!(original, recovered);
    }

    #[test]
    fn test_floor() {
        let whole_number = UnsignedNumeric::new(2);
        let mut decimal_number = UnsignedNumeric::new(2);
        decimal_number.value += InnerUint::from(1);
        let floor = decimal_number.floor().unwrap();
        let floor_again = floor.floor().unwrap();
        assert_eq!(whole_number.value, floor.value);
        assert_eq!(whole_number.value, floor_again.value);
    }

    #[test]
    fn test_ceiling() {
        let whole_number = UnsignedNumeric::new(2);
        let mut decimal_number = UnsignedNumeric::new(2);
        decimal_number.value -= InnerUint::from(1);
        let ceiling = decimal_number.ceiling().unwrap();
        let ceiling_again = ceiling.ceiling().unwrap();
        assert_eq!(whole_number.value, ceiling.value);
        assert_eq!(whole_number.value, ceiling_again.value);
    }

    #[test]
    fn test_add_overflow() {
        let a = max_numeric();
        let b = UnsignedNumeric::one();
        assert!(a.checked_add(&b).is_none(), "Expected overflow on add");
    }

    #[test]
    fn test_mul_overflow() {
        let a = max_numeric();
        let b = UnsignedNumeric::new(2); // 2.0 in scaled form

        let result = a.checked_mul(&b);
        assert!(result.is_none(), "Expected overflow on multiply");
    }

    #[test]
    fn test_mul_fallback_path() {
        let a = UnsignedNumeric::new(1_000_000_000_000u128); // large-ish value
        let b = UnsignedNumeric::new(2);

        let result = a.checked_mul(&b).unwrap();
        assert_eq!(result.to_imprecise().unwrap(), 2_000_000_000_000);
    }

    #[test]
    fn test_mul_large_by_large_overflow() {
        let a = UnsignedNumeric {
            value: InnerUint([0, 0, 1]), // 2^128
        };
        let b = a.clone(); // 2^128 * 2^128 = 2^256, definitely too large

        let result = a.checked_mul(&b);
        assert!(result.is_none(), "Expected overflow on large * large");
    }

    #[test]
    fn test_div_by_zero() {
        let a = UnsignedNumeric::new(42);
        let zero = UnsignedNumeric::zero();

        assert!(a.checked_div(&zero).is_none(), "Expected div by zero to fail");
    }

    #[test]
    fn test_floor_overflow_fallback() {
        // floor() performs: value / ONE * ONE
        // If value is MAX, this can overflow
        let a = max_numeric();
        let result = a.floor();
        assert!(result.is_some(), "Should handle overflow in floor safely");
    }

    #[test]
    fn test_ceiling_overflow() {
        // ceiling() performs: (value + ONE - 1) / ONE * ONE
        // Adding ONE - 1 to MAX will overflow
        let a = max_numeric();
        let result = a.ceiling();
        assert!(result.is_none(), "Expected overflow in ceiling()");
    }

    #[test]
    fn test_rounding_correction_addition_overflow() {
        let a = max_numeric();
        // This simulates rounding correction inside `checked_div`
        let corrected = a.value.checked_add(UnsignedNumeric::rounding_correction());
        assert!(corrected.is_none(), "Expected overflow in rounding correction");
    }

    #[test]
    fn test_arithmetic_operators() {
        let a = UnsignedNumeric::new(5);
        let b = UnsignedNumeric::new(3);
        
        // Test addition
        let sum = a.clone() + b.clone();
        assert_eq!(sum.to_imprecise().unwrap(), 8);
        
        // Test subtraction
        let diff = a.clone() - b.clone();
        assert_eq!(diff.to_imprecise().unwrap(), 2);
        
        // Test multiplication
        let product = a.clone() * b.clone();
        assert_eq!(product.to_imprecise().unwrap(), 15);
        
        // Test division
        let quotient = a / b;
        assert!(quotient.almost_eq(&UnsignedNumeric::from_scaled_u128(1_666_666_666_666_666_666), InnerUint::from(1_000_000)));
    }

    #[test]
    fn test_arithmetic_operators_with_references() {
        let a = UnsignedNumeric::new(10);
        let b = UnsignedNumeric::new(4);
        
        // Test with references
        let sum = &a + &b;
        assert_eq!(sum.to_imprecise().unwrap(), 14);
        
        let diff = &a - &b;
        assert_eq!(diff.to_imprecise().unwrap(), 6);
        
        let product = &a * &b;
        assert_eq!(product.to_imprecise().unwrap(), 40);
        
        let quotient = &a / &b;
        assert_eq!(quotient.to_imprecise().unwrap(), 3);
    }

    #[test]
    fn test_arithmetic_operators_mixed_references() {
        let a = UnsignedNumeric::new(6);
        let b = UnsignedNumeric::new(2);
        
        // Test mixed reference patterns
        let sum1 = a.clone() + &b;
        let sum2 = &a + b.clone();
        assert_eq!(sum1.to_imprecise().unwrap(), 8);
        assert_eq!(sum2.to_imprecise().unwrap(), 8);
        
        let product1 = a.clone() * &b;
        let product2 = &a * b.clone();
        assert_eq!(product1.to_imprecise().unwrap(), 12);
        assert_eq!(product2.to_imprecise().unwrap(), 12);
    }
}