dashu-float 0.5.0

A big float library supporting arbitrary precision, arbitrary base and arbitrary rounding mode
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
//! A cached floating-point number — [`FBig`] with a shared constant cache attached.

use alloc::rc::Rc;
use core::cell::RefCell;
use core::cmp::Ordering;
use core::str::FromStr;

use dashu_base::{AbsOrd, ConversionError, EstimatedLog2, ParseError, Sign, Signed};
use dashu_int::{IBig, UBig};

use crate::error::panic_unlimited_precision;
use crate::fbig::FBig;
use crate::math::cache::ConstCache;
use crate::repr::{Context, Repr, Word};
use crate::round::{mode, Round, Rounded};
use crate::utils::digit_len;

/// A floating-point number that carries a shared handle to a [`ConstCache`].
///
/// It is functionally an [`FBig`]: same in-memory representation (`fbig`),
/// plus an [`Rc<RefCell<ConstCache>>`] handle. The difference is that the
/// transcendental operations (`ln`, `exp`, `sin`, `cos`, …, `pi`, base conversion)
/// thread that handle into the underlying [`Context`] methods, so they reuse and
/// progressively extend the cached exact binary-splitting state instead of
/// recomputing constants from scratch on every call.
///
/// `Context`/`FBig` themselves stay `Copy` + `Send` + `Sync` + `no_std` (so
/// `static_fbig!` keeps working); only this cached
/// wrapper is `!Send + !Sync`, because it shares state through an `Rc<RefCell<..>>`.
/// To share one cache across threads, build an analogous type over
/// `Arc<Mutex<ConstCache>>` instead (the [`Context`] methods accept
/// `Option<&mut ConstCache>`, independent of the container).
///
/// Every value-producing operation returns a `CachedFBig` that preserves the
/// handle, so `(a + b).ln().exp()` stays cached throughout — no silent cache loss.
/// When two `CachedFBig` values with different cache handles interact in a binary
/// operation, the LHS (left-hand-side) cache is preserved in the result. For
/// `FBig op CachedFBig`, the `CachedFBig` operand's cache is preserved.
///
/// # Examples
///
/// ```
/// use core::cell::RefCell;
/// use core::str::FromStr;
/// use dashu_float::{CachedFBig, ConstCache, Context};
/// use dashu_float::round::mode::HalfAway;
/// use std::rc::Rc;
///
/// let cache = Rc::new(RefCell::new(ConstCache::new()));
/// // build a cached decimal number 1.234
/// let x = CachedFBig::<HalfAway, 10>::with_cache(
///     dashu_float::Repr::new(1234.into(), -3),
///     Context::new(50),
/// );
///
/// // ln / exp reuse the same shared cache handle
/// let _ = x.clone().ln().exp();
/// ```
pub struct CachedFBig<R: Round = mode::Zero, const B: Word = 2> {
    pub(crate) fbig: FBig<R, B>,
    pub(crate) cache: Rc<RefCell<ConstCache>>,
}

impl<R: Round, const B: Word> CachedFBig<R, B> {
    /// Wrap an [`FBig`], sharing the given cache handle.
    #[inline]
    pub fn new(value: FBig<R, B>, cache: Rc<RefCell<ConstCache>>) -> Self {
        Self { fbig: value, cache }
    }

    /// Build from raw parts, sharing the given cache handle.
    #[inline]
    pub fn from_repr(repr: Repr<B>, context: Context<R>, cache: Rc<RefCell<ConstCache>>) -> Self {
        Self {
            fbig: FBig::new(repr, context),
            cache,
        }
    }

    /// Build from raw parts with a fresh, exclusive cache.
    #[inline]
    pub fn with_cache(repr: Repr<B>, context: Context<R>) -> Self {
        Self::from_repr(repr, context, Rc::new(RefCell::new(ConstCache::new())))
    }

    /// Build a `CachedFBig` from an [`FBig`] result, re-attaching this value's
    /// shared cache handle (cloned cheaply via `Rc`).
    #[inline]
    pub(crate) fn from_fbig(fbig: FBig<R, B>, cache: &Rc<RefCell<ConstCache>>) -> Self {
        Self {
            fbig,
            cache: Rc::clone(cache),
        }
    }

    /// Borrow the inner [`FBig`].
    #[inline]
    pub fn as_fbig(&self) -> &FBig<R, B> {
        &self.fbig
    }

    /// Drop the cache handle and return the underlying [`FBig`].
    #[inline]
    pub fn into_fbig(self) -> FBig<R, B> {
        self.fbig
    }

    /// Borrow the shared constant cache immutably.
    ///
    /// Use this to inspect cache state, e.g. `cached.cache().total_terms()`.
    #[inline]
    pub fn cache(&self) -> impl core::ops::Deref<Target = ConstCache> + '_ {
        self.cache.borrow()
    }

    /// Clear all cached constant state, freeing the underlying memory.
    ///
    /// The next transcendental operation will recompute constants from scratch.
    #[inline]
    pub fn clear_cache(&self) {
        self.cache.borrow_mut().clear();
    }

    /// π at `precision` base-`B` digits, reusing/extending `cache`.
    pub fn pi(precision: usize, cache: &Rc<RefCell<ConstCache>>) -> Self {
        let fbig = {
            let mut c = cache.borrow_mut();
            Context::<R>::new(precision).pi::<B>(Some(&mut *c)).value()
        };
        Self::from_fbig(fbig, cache)
    }

    // ----- accessors -----

    /// Maximum precision set for the number (see [`FBig::precision`]).
    #[inline]
    pub const fn precision(&self) -> usize {
        self.fbig.context.precision
    }

    /// Number of significant digits (see [`FBig::digits`]).
    #[inline]
    pub fn digits(&self) -> usize {
        self.fbig.repr.digits()
    }

    /// The associated context.
    #[inline]
    pub const fn context(&self) -> Context<R> {
        self.fbig.context
    }

    /// The underlying representation.
    #[inline]
    pub const fn repr(&self) -> &Repr<B> {
        &self.fbig.repr
    }

    /// Consume and return the underlying representation.
    #[inline]
    pub fn into_repr(self) -> Repr<B> {
        self.fbig.repr
    }

    /// Sign of the number (see [`FBig::sign`]).
    #[inline]
    pub const fn sign(&self) -> Sign {
        self.fbig.repr.sign()
    }

    /// Change precision, preserving the handle (see [`FBig::with_precision`]).
    pub fn with_precision(&self, precision: usize) -> Rounded<Self> {
        self.fbig
            .clone()
            .with_precision(precision)
            .map(|f| Self::from_fbig(f, &self.cache))
    }

    /// Change rounding mode, preserving the handle (see [`FBig::with_rounding`]).
    pub fn with_rounding<NewR: Round>(&self) -> CachedFBig<NewR, B> {
        CachedFBig::from_fbig(self.fbig.clone().with_rounding::<NewR>(), &self.cache)
    }
}

impl<R: Round, const B: Word> CachedFBig<R, B> {
    /// ULP of the number (see [`FBig::ulp`]).
    pub fn ulp(&self) -> Self {
        if self.fbig.context.precision == 0 {
            panic_unlimited_precision();
        }
        let repr = Repr {
            significand: dashu_int::IBig::ONE,
            exponent: self.fbig.repr.exponent + self.fbig.repr.digits() as isize
                - self.fbig.context.precision as isize,
        };
        Self::from_repr(repr, self.fbig.context, Rc::clone(&self.cache))
    }

    /// Convert to an integer (see [`FBig::to_int`]).
    pub fn to_int(&self) -> Rounded<dashu_int::IBig> {
        self.fbig.clone().to_int()
    }

    /// Convert to `f32` (see [`FBig::to_f32`]).
    pub fn to_f32(&self) -> Rounded<f32> {
        self.fbig.clone().to_f32()
    }

    /// Convert to `f64` (see [`FBig::to_f64`]).
    pub fn to_f64(&self) -> Rounded<f64> {
        self.fbig.clone().to_f64()
    }

    /// Construct from significand + exponent, with a fresh cache (see [`FBig::from_parts`]).
    pub fn from_parts(significand: dashu_int::IBig, exponent: isize) -> Self {
        let precision = digit_len::<B>(&significand).max(1);
        let repr = Repr::new(significand, exponent);
        Self::with_cache(repr, Context::new(precision))
    }
}

// ---------------------------------------------------------------------------
// From / Into
// ---------------------------------------------------------------------------

impl<R: Round, const B: Word> From<FBig<R, B>> for CachedFBig<R, B> {
    #[inline]
    fn from(fbig: FBig<R, B>) -> Self {
        Self::new(fbig, Rc::new(RefCell::new(ConstCache::new())))
    }
}

impl<R: Round, const B: Word> From<CachedFBig<R, B>> for FBig<R, B> {
    #[inline]
    fn from(cached: CachedFBig<R, B>) -> Self {
        cached.into_fbig()
    }
}

impl<R: Round, const B: Word> FBig<R, B> {
    /// Attach a shared cache handle, turning this [`FBig`] into a [`CachedFBig`].
    #[inline]
    pub fn into_cached(self, cache: Rc<RefCell<ConstCache>>) -> CachedFBig<R, B> {
        CachedFBig::new(self, cache)
    }
}

// ---------------------------------------------------------------------------
// FromStr / From / TryFrom
//
// Construction from an external value (string, integer, primitive float) attaches
// a *fresh* cache, exactly like `From<FBig>` above — there is no existing handle
// to share, and `FromStr`/`TryFrom` have no parameter for one.
// ---------------------------------------------------------------------------

impl<R: Round, const B: Word> FromStr for CachedFBig<R, B> {
    type Err = ParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, ParseError> {
        Ok(FBig::from_str(s)?.into())
    }
}

impl<R: Round, const B: Word> From<UBig> for CachedFBig<R, B> {
    #[inline]
    fn from(n: UBig) -> Self {
        FBig::from(n).into()
    }
}

impl<R: Round, const B: Word> From<IBig> for CachedFBig<R, B> {
    #[inline]
    fn from(n: IBig) -> Self {
        FBig::from(n).into()
    }
}

macro_rules! impl_from_int_for_cached_fbig {
    ($($t:ty)*) => {$(
        impl<R: Round, const B: Word> From<$t> for CachedFBig<R, B> {
            #[inline]
            fn from(value: $t) -> Self {
                FBig::from(value).into()
            }
        }
    )*};
}
impl_from_int_for_cached_fbig!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);

impl<R: Round> TryFrom<f32> for CachedFBig<R, 2> {
    type Error = ConversionError;

    #[inline]
    fn try_from(value: f32) -> Result<Self, Self::Error> {
        FBig::try_from(value).map(Self::from)
    }
}

impl<R: Round> TryFrom<f64> for CachedFBig<R, 2> {
    type Error = ConversionError;

    #[inline]
    fn try_from(value: f64) -> Result<Self, Self::Error> {
        FBig::try_from(value).map(Self::from)
    }
}

macro_rules! impl_try_from_cached_fbig_for_int {
    ($($t:ty)*) => {$(
        impl<R: Round, const B: Word> TryFrom<CachedFBig<R, B>> for $t {
            type Error = ConversionError;

            #[inline]
            fn try_from(value: CachedFBig<R, B>) -> Result<Self, Self::Error> {
                value.fbig.try_into()
            }
        }
    )*};
}
impl_try_from_cached_fbig_for_int!(
    u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize UBig IBig
);

impl<R: Round> TryFrom<CachedFBig<R, 2>> for f32 {
    type Error = ConversionError;

    #[inline]
    fn try_from(value: CachedFBig<R, 2>) -> Result<Self, Self::Error> {
        value.fbig.try_into()
    }
}

impl<R: Round> TryFrom<CachedFBig<R, 2>> for f64 {
    type Error = ConversionError;

    #[inline]
    fn try_from(value: CachedFBig<R, 2>) -> Result<Self, Self::Error> {
        value.fbig.try_into()
    }
}

// ---------------------------------------------------------------------------
// Clone / Default / Debug / comparisons
// ---------------------------------------------------------------------------

impl<R: Round, const B: Word> Clone for CachedFBig<R, B> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            fbig: self.fbig.clone(),
            cache: Rc::clone(&self.cache),
        }
    }
}

impl<R: Round, const B: Word> Default for CachedFBig<R, B> {
    /// Default value: 0 with a fresh cache.
    #[inline]
    fn default() -> Self {
        Self::with_cache(Repr::zero(), Context::new(0))
    }
}

impl<R: Round, const B: Word> core::fmt::Debug for CachedFBig<R, B> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CachedFBig")
            .field("repr", &self.fbig.repr)
            .field("precision", &self.fbig.context.precision)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Display / LowerExp / UpperExp / base-specific formatting
//
// Each delegates to the inner FBig so the rendered string is identical to FBig.
// (`Debug` above intentionally keeps the cached-specific struct form.)
// ---------------------------------------------------------------------------

impl<R: Round, const B: Word> core::fmt::Display for CachedFBig<R, B> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.fbig, f)
    }
}

impl<R: Round, const B: Word> core::fmt::LowerExp for CachedFBig<R, B> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::LowerExp::fmt(&self.fbig, f)
    }
}

impl<R: Round, const B: Word> core::fmt::UpperExp for CachedFBig<R, B> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::UpperExp::fmt(&self.fbig, f)
    }
}

/// Mirror the base-specific format traits ([`core::fmt::Binary`], [`Octal`](core::fmt::Octal),
/// [`LowerHex`]/[`UpperHex`](core::fmt::UpperHex)) onto [`CachedFBig`] for the bases where they
/// apply, delegating each to the inner [`FBig`]'s impl so the output matches.
macro_rules! impl_cached_fmt_with_base {
    ($base:literal, $trait:ident) => {
        impl<R: Round> core::fmt::$trait for CachedFBig<R, $base> {
            #[inline]
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                core::fmt::$trait::fmt(&self.fbig, f)
            }
        }
    };
}
impl_cached_fmt_with_base!(2, Binary);
impl_cached_fmt_with_base!(2, LowerHex);
impl_cached_fmt_with_base!(2, UpperHex);
impl_cached_fmt_with_base!(8, Octal);
impl_cached_fmt_with_base!(16, LowerHex);
impl_cached_fmt_with_base!(16, UpperHex);

impl<R1: Round, R2: Round, const B: Word> PartialEq<CachedFBig<R2, B>> for CachedFBig<R1, B> {
    #[inline]
    fn eq(&self, other: &CachedFBig<R2, B>) -> bool {
        // value equality, mirroring FBig (compares the representation only).
        self.fbig.repr == other.fbig.repr
    }
}

impl<R: Round, const B: Word> Eq for CachedFBig<R, B> {}

// ---------------------------------------------------------------------------
// Ordering and the dashu-base ordering/log/sign traits
// (delegate to the inner FBig — value ordering, context ignored)
// ---------------------------------------------------------------------------

impl<R1: Round, R2: Round, const B: Word> PartialOrd<CachedFBig<R2, B>> for CachedFBig<R1, B> {
    #[inline]
    fn partial_cmp(&self, other: &CachedFBig<R2, B>) -> Option<Ordering> {
        self.fbig.partial_cmp(&other.fbig)
    }
}

impl<R: Round, const B: Word> Ord for CachedFBig<R, B> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.fbig.cmp(&other.fbig)
    }
}

impl<R: Round, const B: Word> AbsOrd for CachedFBig<R, B> {
    #[inline]
    fn abs_cmp(&self, other: &Self) -> Ordering {
        AbsOrd::abs_cmp(&self.fbig, &other.fbig)
    }
}

impl<R: Round, const B: Word> AbsOrd<UBig> for CachedFBig<R, B> {
    #[inline]
    fn abs_cmp(&self, other: &UBig) -> Ordering {
        AbsOrd::abs_cmp(&self.fbig, other)
    }
}
impl<R: Round, const B: Word> AbsOrd<CachedFBig<R, B>> for UBig {
    #[inline]
    fn abs_cmp(&self, other: &CachedFBig<R, B>) -> Ordering {
        AbsOrd::abs_cmp(self, &other.fbig)
    }
}
impl<R: Round, const B: Word> AbsOrd<IBig> for CachedFBig<R, B> {
    #[inline]
    fn abs_cmp(&self, other: &IBig) -> Ordering {
        AbsOrd::abs_cmp(&self.fbig, other)
    }
}
impl<R: Round, const B: Word> AbsOrd<CachedFBig<R, B>> for IBig {
    #[inline]
    fn abs_cmp(&self, other: &CachedFBig<R, B>) -> Ordering {
        AbsOrd::abs_cmp(self, &other.fbig)
    }
}

impl<R: Round, const B: Word> Signed for CachedFBig<R, B> {
    #[inline]
    fn sign(&self) -> Sign {
        self.fbig.sign()
    }
}

impl<R: Round, const B: Word> EstimatedLog2 for CachedFBig<R, B> {
    #[inline]
    fn log2_bounds(&self) -> (f32, f32) {
        EstimatedLog2::log2_bounds(&self.fbig)
    }

    #[inline]
    fn log2_est(&self) -> f32 {
        EstimatedLog2::log2_est(&self.fbig)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::round::mode;
    use alloc::format;

    fn handle() -> Rc<RefCell<ConstCache>> {
        Rc::new(RefCell::new(ConstCache::new()))
    }

    /// An `FBig` with value `n` at the given precision (so inexact results match the
    /// `CachedFBig` operands built at the same precision).
    fn fbig(n: i32, prec: usize) -> FBig<mode::HalfAway, 10> {
        FBig::from_repr(Repr::new(n.into(), 0), Context::new(prec))
    }

    #[test]
    fn test_pi_matches_fbig() {
        for &precision in &[10usize, 50, 100] {
            let h = handle();
            let cached = CachedFBig::<mode::HalfAway, 10>::pi(precision, &h).into_fbig();
            let direct = FBig::<mode::HalfAway, 10>::pi(precision);
            assert_eq!(cached, direct, "pi mismatch at precision {precision}");
        }
    }

    #[test]
    fn test_transcendentals_match_fbig() {
        let x = CachedFBig::<mode::HalfAway, 10>::with_cache(
            Repr::new(1234.into(), -3), // 1.234
            Context::new(50),
        );
        let y = FBig::<mode::HalfAway, 10>::from_repr(Repr::new(1234.into(), -3), Context::new(50));

        assert_eq!(x.clone().ln().into_fbig(), y.clone().ln());
        assert_eq!(x.clone().exp().into_fbig(), y.clone().exp());
        assert_eq!(x.clone().sin().into_fbig(), y.clone().sin());
        assert_eq!(x.clone().cos().into_fbig(), y.clone().cos());
        assert_eq!(x.clone().exp_m1().into_fbig(), y.clone().exp_m1());
        assert_eq!(x.clone().ln_1p().into_fbig(), y.clone().ln_1p());
        assert_eq!(x.powf(&x.clone()).into_fbig(), y.clone().powf(&y));
    }

    #[test]
    fn test_cache_extension_matches_scratch() {
        // Extending π 100 -> 1000 through one shared handle must equal a from-scratch compute.
        let h = handle();
        let _pi_100 = CachedFBig::<mode::HalfAway, 10>::pi(100, &h);
        let pi_1000 = CachedFBig::<mode::HalfAway, 10>::pi(1000, &h).into_fbig();
        let direct = Context::<mode::HalfAway>::new(1000).pi::<10>(None).value();
        assert_eq!(pi_1000, direct);
    }

    #[test]
    fn test_cache_survives_arithmetic() {
        // a and b share one cache handle; the sum must keep it so the subsequent
        // ln() reuses the same shared cache.
        let h = handle();
        let a = CachedFBig::<mode::HalfAway, 10>::from_repr(
            Repr::new(2.into(), 0),
            Context::new(30),
            h.clone(),
        );
        let b = CachedFBig::<mode::HalfAway, 10>::from_repr(
            Repr::new(3.into(), 0),
            Context::new(30),
            h.clone(),
        );
        let sum_ln = (a.clone() + b.clone()).ln().into_fbig();
        let expected = (fbig(2, 30) + fbig(3, 30)).ln();
        assert_eq!(sum_ln, expected);
    }

    #[test]
    fn test_arithmetic_matches_fbig() {
        let a =
            CachedFBig::<mode::HalfAway, 10>::with_cache(Repr::new(2.into(), 0), Context::new(20));
        let b =
            CachedFBig::<mode::HalfAway, 10>::with_cache(Repr::new(3.into(), 0), Context::new(20));

        assert_eq!((a.clone() + b.clone()).into_fbig(), fbig(2, 20) + fbig(3, 20));
        assert_eq!((a.clone() - b.clone()).into_fbig(), fbig(2, 20) - fbig(3, 20));
        assert_eq!((a.clone() * b.clone()).into_fbig(), fbig(2, 20) * fbig(3, 20));
        assert_eq!((a.clone() / b.clone()).into_fbig(), fbig(2, 20) / fbig(3, 20));
    }

    #[test]
    fn test_debug_compiles() {
        let x = CachedFBig::<mode::HalfAway, 10>::with_cache(
            Repr::new(1234.into(), -3),
            Context::new(50),
        );
        let s = format!("{:?}", x);
        assert!(s.contains("CachedFBig"));
    }

    #[test]
    fn test_arithmetic_with_fbig() {
        let a =
            CachedFBig::<mode::HalfAway, 10>::with_cache(Repr::new(2.into(), 0), Context::new(20));
        let b = fbig(3, 20);

        // CachedFBig op FBig — cache preserved (LHS)
        let c = a.clone() + b.clone();
        assert_eq!(c.into_fbig(), fbig(2, 20) + fbig(3, 20));

        // FBig op CachedFBig — cache preserved (RHS)
        let d = b.clone() + a.clone();
        assert_eq!(d.into_fbig(), fbig(3, 20) + fbig(2, 20));

        // Sub, Mul, Div
        assert_eq!((a.clone() - b.clone()).into_fbig(), fbig(2, 20) - fbig(3, 20));
        assert_eq!((a.clone() * b.clone()).into_fbig(), fbig(2, 20) * fbig(3, 20));
        assert_eq!((a.clone() / b.clone()).into_fbig(), fbig(2, 20) / fbig(3, 20));
    }

    #[test]
    fn test_arithmetic_with_primitives() {
        let a =
            CachedFBig::<mode::HalfAway, 10>::with_cache(Repr::new(2.into(), 0), Context::new(20));

        // CachedFBig op primitive
        assert_eq!((a.clone() + 3u8).into_fbig(), fbig(2, 20) + 3u8);
        assert_eq!((a.clone() - 3i32).into_fbig(), fbig(2, 20) - 3i32);
        assert_eq!((a.clone() * 4u64).into_fbig(), fbig(2, 20) * 4u64);

        // Primitive op CachedFBig
        assert_eq!((3u8 + a.clone()).into_fbig(), 3u8 + fbig(2, 20));
        assert_eq!((10i32 - a.clone()).into_fbig(), 10i32 - fbig(2, 20));
    }

    #[test]
    fn test_cache_size() {
        let x = CachedFBig::<mode::HalfAway, 10>::with_cache(
            Repr::new(1234.into(), -3),
            Context::new(50),
        );
        let _ = x.ln();
        // After computing ln(1.234), the cache should have some state
        assert!(x.cache().total_terms() > 0);
        assert!(x.cache().total_words() > 0);
    }

    #[test]
    fn test_cache_clear() {
        let x = CachedFBig::<mode::HalfAway, 10>::with_cache(
            Repr::new(1234.into(), -3),
            Context::new(50),
        );
        let before_clear = x.ln().into_fbig();
        assert!(x.cache().total_terms() > 0);

        x.clear_cache();
        assert_eq!(x.cache().total_terms(), 0);
        assert_eq!(x.cache().total_words(), 0);

        // After clearing, recomputation still produces the same result
        let after_clear = x.ln().into_fbig();
        assert_eq!(after_clear, before_clear);
    }
}