Skip to main content

dashu_float/
convert.rs

1use core::{
2    convert::{TryFrom, TryInto},
3    num::FpCategory,
4};
5
6use dashu_base::{
7    AbsOrd, Approximation::*, BitTest, ConversionError, DivRemEuclid, EstimatedLog2, FloatEncoding,
8    Sign, Signed,
9};
10use dashu_int::{IBig, UBig, Word};
11
12use crate::{
13    error::{assert_finite, panic_unlimited_precision, FpError, FpResult},
14    fbig::FBig,
15    math::cache::{reborrow_cache, ConstCache},
16    repr::{Context, Repr},
17    round::{
18        mode::{HalfAway, HalfEven, Zero},
19        Round, Rounded, Rounding,
20        Rounding::*,
21    },
22    utils::{factor_base, ilog_exact, shl_digits, shl_digits_in_place, shr_digits},
23};
24
25impl<R: Round> Context<R> {
26    /// Convert an [IBig] instance to a [FBig] instance with precision
27    /// and rounding given by the context.
28    ///
29    /// # Examples
30    ///
31    /// ```
32    /// # use core::str::FromStr;
33    /// # use dashu_base::ParseError;
34    /// # use dashu_float::DBig;
35    /// use dashu_base::Approximation::*;
36    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
37    ///
38    /// let context = Context::<HalfAway>::new(2);
39    /// assert_eq!(context.convert_int::<10>((-12).into()), Exact(DBig::from_str("-12")?));
40    /// assert_eq!(
41    ///     context.convert_int::<10>(5678.into()),
42    ///     Inexact(DBig::from_str("5.7e3")?, AddOne)
43    /// );
44    /// # Ok::<(), ParseError>(())
45    /// ```
46    pub fn convert_int<const B: Word>(&self, n: IBig) -> Rounded<FBig<R, B>> {
47        let repr = Repr::<B>::new(n, 0);
48        self.repr_round(repr).map(|v| FBig::new(v, *self))
49    }
50}
51
52macro_rules! impl_from_float_for_fbig {
53    ($t:ty) => {
54        impl TryFrom<$t> for Repr<2> {
55            type Error = ConversionError;
56
57            fn try_from(f: $t) -> Result<Self, Self::Error> {
58                match f.decode() {
59                    Ok((man, exp)) => Ok(if man == 0 && f.is_sign_negative() {
60                        Self::neg_zero()
61                    } else {
62                        Repr::new(man.into(), exp as _)
63                    }),
64                    Err(FpCategory::Infinite) => match f.sign() {
65                        Sign::Positive => Ok(Self::infinity()),
66                        Sign::Negative => Ok(Self::neg_infinity()),
67                    },
68                    _ => Err(ConversionError::OutOfBounds), // NaN
69                }
70            }
71        }
72
73        impl<R: Round> TryFrom<$t> for FBig<R, 2> {
74            type Error = ConversionError;
75
76            fn try_from(f: $t) -> Result<Self, Self::Error> {
77                match f.decode() {
78                    Ok((man, exp)) => {
79                        // preserve the sign of a signed zero (-0.0 -> Repr::neg_zero())
80                        let repr = if man == 0 && f.is_sign_negative() {
81                            Repr::neg_zero()
82                        } else {
83                            Repr::new(man.into(), exp as _)
84                        };
85
86                        // The precision is inferenced from the mantissa, because the mantissa of
87                        // normal float is always normalized. This will produce correct precision
88                        // for subnormal floats
89                        let bits = man.unsigned_abs().bit_len();
90                        let context = Context::new(bits);
91                        Ok(Self::new(repr, context))
92                    }
93                    Err(FpCategory::Infinite) => match f.sign() {
94                        Sign::Positive => Ok(Self::INFINITY),
95                        Sign::Negative => Ok(Self::NEG_INFINITY),
96                    },
97                    _ => Err(ConversionError::OutOfBounds), // NaN
98                }
99            }
100        }
101    };
102}
103
104impl_from_float_for_fbig!(f32);
105impl_from_float_for_fbig!(f64);
106
107impl<R: Round, const B: Word> FBig<R, B> {
108    /// Convert the float number to base 10 (with decimal exponents) rounding to even
109    /// and tying away from zero.
110    ///
111    /// It's equivalent to `self.with_rounding::<HalfAway>().with_base::<10>()`.
112    /// The output is directly of type [DBig][crate::DBig].
113    ///
114    /// See [with_base()][Self::with_base] for the precision behavior.
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// # use core::str::FromStr;
120    /// # use dashu_base::ParseError;
121    /// # use dashu_float::{FBig, DBig};
122    /// use dashu_base::Approximation::*;
123    /// use dashu_float::round::Rounding::*;
124    ///
125    /// type Real = FBig;
126    ///
127    /// assert_eq!(
128    ///     Real::from_str("0x1234")?.to_decimal(),
129    ///     Exact(DBig::from_str("4660")?)
130    /// );
131    /// assert_eq!(
132    ///     Real::from_str("0x12.34")?.to_decimal(),
133    ///     Inexact(DBig::from_str("18.20")?, NoOp)
134    /// );
135    /// assert_eq!(
136    ///     Real::from_str("0x1.234p-4")?.to_decimal(),
137    ///     Inexact(DBig::from_str("0.07111")?, AddOne)
138    /// );
139    /// # Ok::<(), ParseError>(())
140    /// ```
141    ///
142    /// # Panics
143    ///
144    /// Panics if the associated context has unlimited precision and the conversion
145    /// cannot be performed losslessly.
146    #[inline]
147    pub fn to_decimal(&self) -> Rounded<FBig<HalfAway, 10>> {
148        self.clone().with_rounding().with_base::<10>()
149    }
150
151    /// Convert the float number to base 2 (with binary exponents) rounding towards zero.
152    ///
153    /// It's equivalent to `self.with_rounding::<Zero>().with_base::<2>()`.
154    ///
155    /// See [with_base()][Self::with_base] for the precision and rounding behavior.
156    ///
157    /// # Examples
158    ///
159    /// ```
160    /// # use core::str::FromStr;
161    /// # use dashu_base::ParseError;
162    /// # use dashu_float::{FBig, DBig};
163    /// use dashu_base::Approximation::*;
164    /// use dashu_float::round::{mode::HalfAway, Rounding::*};
165    ///
166    /// type Real = FBig;
167    ///
168    /// assert_eq!(
169    ///     DBig::from_str("1234")?.to_binary(),
170    ///     Exact(Real::from_str("0x4d2")?)
171    /// );
172    /// assert_eq!(
173    ///     DBig::from_str("12.34")?.to_binary(),
174    ///     Inexact(Real::from_str("0xc.57")?, NoOp)
175    /// );
176    /// assert_eq!(
177    ///     DBig::from_str("1.234e-1")?.to_binary(),
178    ///     Inexact(Real::from_str("0x1.f97p-4")?, NoOp)
179    /// );
180    /// # Ok::<(), ParseError>(())
181    /// ```
182    ///
183    /// # Panics
184    ///
185    /// Panics if the associated context has unlimited precision and the conversion
186    /// cannot be performed losslessly.
187    #[inline]
188    pub fn to_binary(&self) -> Rounded<FBig<Zero, 2>> {
189        self.clone().with_rounding().with_base::<2>()
190    }
191
192    /// Explicitly change the precision of the float number.
193    ///
194    /// If the given precision is less than the current value in the context,
195    /// it will be rounded with the rounding mode specified by the generic parameter.
196    ///
197    /// # Examples
198    ///
199    /// ```rust
200    /// # use core::str::FromStr;
201    /// # use dashu_base::ParseError;
202    /// # use dashu_float::{FBig, DBig};
203    /// use dashu_base::Approximation::*;
204    /// use dashu_float::round::{mode::HalfAway, Rounding::*};
205    ///
206    /// let a = DBig::from_str("2.345")?;
207    /// assert_eq!(a.precision(), 4);
208    /// assert_eq!(
209    ///     a.clone().with_precision(3),
210    ///     Inexact(DBig::from_str("2.35")?, AddOne)
211    /// );
212    /// assert_eq!(
213    ///     a.clone().with_precision(5),
214    ///     Exact(DBig::from_str("2.345")?)
215    /// );
216    /// # Ok::<(), ParseError>(())
217    /// ```
218    #[inline]
219    pub fn with_precision(self, precision: usize) -> Rounded<Self> {
220        let new_context = Context::new(precision);
221
222        // shrink if necessary
223        let repr = if self.context.precision > precision {
224            // it also handles unlimited precision
225            new_context.repr_round(self.repr)
226        } else {
227            Exact(self.repr)
228        };
229
230        repr.map(|v| Self::new(v, new_context))
231    }
232
233    /// Explicitly change the rounding mode of the number.
234    ///
235    /// This operation doesn't modify the underlying representation, it only changes
236    /// the rounding mode in the context.
237    ///
238    /// # Examples
239    ///
240    /// ```rust
241    /// # use core::str::FromStr;
242    /// # use dashu_base::ParseError;
243    /// # use dashu_float::{FBig, DBig};
244    /// use dashu_base::Approximation::*;
245    /// use dashu_float::round::{mode::{HalfAway, Zero}, Rounding::*};
246    ///
247    /// type DBigHalfAway = DBig;
248    /// type DBigZero = FBig::<Zero, 10>;
249    ///
250    /// let a = DBigHalfAway::from_str("2.345")?;
251    /// let b = DBigZero::from_str("2.345")?;
252    /// assert_eq!(a.with_rounding::<Zero>(), b);
253    /// # Ok::<(), ParseError>(())
254    /// ```
255    #[inline]
256    pub fn with_rounding<NewR: Round>(self) -> FBig<NewR, B> {
257        FBig {
258            repr: self.repr,
259            context: Context::new(self.context.precision),
260        }
261    }
262
263    /// Explicitly change the base of the float number.
264    ///
265    /// This function internally calls [with_base_and_precision][Self::with_base_and_precision].
266    /// The precision of the result number will be calculated in such a way that the new
267    /// limit of the significand is less than or equal to before. That is, the new precision
268    /// will be the max integer such that
269    ///
270    /// `NewB ^ new_precision <= B ^ old_precision`
271    ///
272    /// If any rounding happens during the conversion, it follows the rounding mode specified
273    /// by the generic parameter.
274    ///
275    /// # Examples
276    ///
277    /// ```rust
278    /// # use core::str::FromStr;
279    /// # use dashu_base::ParseError;
280    /// # use dashu_float::{FBig, DBig};
281    /// use dashu_base::Approximation::*;
282    /// use dashu_float::round::{mode::Zero, Rounding::*};
283    ///
284    /// type FBin = FBig;
285    /// type FDec = FBig<Zero, 10>;
286    /// type FHex = FBig<Zero, 16>;
287    ///
288    /// let a = FBin::from_str("0x1.234")?; // 0x1234 * 2^-12
289    /// assert_eq!(
290    ///     a.clone().with_base::<10>(),
291    ///     // 1.1376953125 rounded towards zero
292    ///     Inexact(FDec::from_str("1.137")?, NoOp)
293    /// );
294    /// assert_eq!(
295    ///     a.clone().with_base::<16>(),
296    ///     // conversion is exact when the new base is a power of the old base
297    ///     Exact(FHex::from_str("1.234")?)
298    /// );
299    /// # Ok::<(), ParseError>(())
300    /// ```
301    ///
302    /// # Panics
303    ///
304    /// Panics if the associated context has unlimited precision and the conversion
305    /// cannot be performed losslessly.
306    #[inline]
307    #[allow(non_upper_case_globals)]
308    pub fn with_base<const NewB: Word>(self) -> Rounded<FBig<R, NewB>> {
309        // if self.context.precision is zero, then precision is also zero
310        let precision =
311            Repr::<B>::BASE.pow(self.context.precision).log2_bounds().0 / NewB.log2_bounds().1;
312        self.with_base_and_precision(precision as usize)
313    }
314
315    /// Explicitly change the base of the float number with given precision (under the new base).
316    ///
317    /// Infinities are mapped to infinities inexactly, the error will be [NoOp][Rounding::NoOp].
318    ///
319    /// Conversion for float numbers with unlimited precision is only allowed in following cases:
320    /// - The number is infinite
321    /// - The new base NewB is a power of B
322    /// - B is a power of the new base NewB
323    ///
324    /// # Examples
325    ///
326    /// ```rust
327    /// # use core::str::FromStr;
328    /// # use dashu_base::ParseError;
329    /// # use dashu_float::{FBig, DBig};
330    /// use dashu_base::Approximation::*;
331    /// use dashu_float::round::{mode::Zero, Rounding::*};
332    ///
333    /// type FBin = FBig;
334    /// type FDec = FBig<Zero, 10>;
335    /// type FHex = FBig<Zero, 16>;
336    ///
337    /// let a = FBin::from_str("0x1.234")?; // 0x1234 * 2^-12
338    /// assert_eq!(
339    ///     a.clone().with_base_and_precision::<10>(8),
340    ///     // 1.1376953125 rounded towards zero
341    ///     Inexact(FDec::from_str("1.1376953")?, NoOp)
342    /// );
343    /// assert_eq!(
344    ///     a.clone().with_base_and_precision::<16>(8),
345    ///     // conversion can be exact when the new base is a power of the old base
346    ///     Exact(FHex::from_str("1.234")?)
347    /// );
348    /// assert_eq!(
349    ///     a.clone().with_base_and_precision::<16>(2),
350    ///     // but the conversion is still inexact if the target precision is smaller
351    ///     Inexact(FHex::from_str("1.2")?, NoOp)
352    /// );
353    /// # Ok::<(), ParseError>(())
354    /// ```
355    ///
356    /// # Panics
357    ///
358    /// Panics if the associated context has unlimited precision and the conversion
359    /// cannot be performed losslessly.
360    #[allow(non_upper_case_globals)]
361    #[inline]
362    pub fn with_base_and_precision<const NewB: Word>(
363        self,
364        precision: usize,
365    ) -> Rounded<FBig<R, NewB>> {
366        let context = Context::<R>::new(precision);
367        context
368            .convert_base(self.repr, None)
369            .map(|repr| FBig::new(repr, context))
370    }
371
372    /// Convert the float number to integer with the given rounding mode.
373    ///
374    /// # Warning
375    ///
376    /// If the float number has a very large exponent, it will be evaluated and result
377    /// in allocating an huge integer and it might eat up all your memory.
378    ///
379    /// To get a rough idea of how big the number is, it's recommended to use [EstimatedLog2].
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// # use core::str::FromStr;
385    /// # use dashu_base::ParseError;
386    /// # use dashu_float::{FBig, DBig};
387    /// use dashu_base::Approximation::*;
388    /// use dashu_float::round::Rounding::*;
389    ///
390    /// assert_eq!(
391    ///     DBig::from_str("1234")?.to_int(),
392    ///     Exact(1234.into())
393    /// );
394    /// assert_eq!(
395    ///     DBig::from_str("1.234e6")?.to_int(),
396    ///     Exact(1234000.into())
397    /// );
398    /// assert_eq!(
399    ///     DBig::from_str("1.234")?.to_int(),
400    ///     Inexact(1.into(), NoOp)
401    /// );
402    /// # Ok::<(), ParseError>(())
403    /// ```
404    ///
405    /// # Panics
406    ///
407    /// Panics if the number is infinte
408    pub fn to_int(&self) -> Rounded<IBig> {
409        assert_finite(&self.repr);
410
411        // shortcut when the number is already an integer
412        if self.repr.exponent >= 0 {
413            return Exact(shl_digits::<B>(&self.repr.significand, self.repr.exponent as usize));
414        }
415
416        let (hi, lo, precision) = self.split_at_point_internal();
417        let adjust = R::round_fract::<B>(&hi, lo, precision);
418        Inexact(hi + adjust, adjust)
419    }
420
421    /// Convert the float number to [f32] with the rounding mode associated with the type.
422    ///
423    /// Note that the conversion is inexact even if the number is infinite.
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// # use core::str::FromStr;
429    /// # use dashu_base::ParseError;
430    /// # use dashu_float::DBig;
431    /// assert_eq!(DBig::from_str("1.234")?.to_f32().value(), 1.234);
432    /// assert_eq!(DBig::INFINITY.to_f32().value(), f32::INFINITY);
433    /// # Ok::<(), ParseError>(())
434    /// ```
435    #[inline]
436    pub fn to_f32(&self) -> Rounded<f32> {
437        match Context::<R>::convert_to_f32(self.repr.clone()) {
438            Ok(rounded) => rounded,
439            Err(err) => f32_directed_endpoint::<R>(err),
440        }
441    }
442
443    /// Convert the float number to [f64] with the rounding mode associated with the type.
444    ///
445    /// Note that the conversion is inexact even if the number is infinite.
446    ///
447    /// # Examples
448    ///
449    /// ```
450    /// # use core::str::FromStr;
451    /// # use dashu_base::ParseError;
452    /// # use dashu_float::DBig;
453    /// assert_eq!(DBig::from_str("1.234")?.to_f64().value(), 1.234);
454    /// assert_eq!(DBig::INFINITY.to_f64().value(), f64::INFINITY);
455    /// # Ok::<(), ParseError>(())
456    /// ```
457    #[inline]
458    pub fn to_f64(&self) -> Rounded<f64> {
459        match Context::<R>::convert_to_f64(self.repr.clone()) {
460            Ok(rounded) => rounded,
461            Err(err) => f64_directed_endpoint::<R>(err),
462        }
463    }
464}
465
466/// `isize` exponent arithmetic overflowed during base conversion: the value's magnitude
467/// falls outside the representable exponent range, so the result is ±infinity (`large`) or
468/// ±0 (`!large`). Mirrors the convention `convert_base` already uses in its division path,
469/// keeping the conversion overflow-safe (no panic) at the value level.
470#[allow(non_upper_case_globals)]
471fn converted_overflow_repr<const NewB: Word>(large: bool, sign: Sign) -> Rounded<Repr<NewB>> {
472    Inexact(
473        if large {
474            Repr::<NewB>::infinity_with_sign(sign)
475        } else {
476            Repr::<NewB>::zero_with_sign(sign)
477        },
478        Rounding::NoOp,
479    )
480}
481
482/// Number of significant bits a binary float format keeps for a value whose most-significant bit
483/// sits at position `msb`: `max_bits` across the normal range, but fewer for subnormals, whose
484/// spacing is fixed at `2^subnormal_exp` (e.g. `2^-1074` for f64, `2^-149` for f32). Rounding the
485/// source straight to this width lets the bit-encoding step avoid a second rounding, which would
486/// otherwise double-round subnormals.
487fn significand_bits(v: &Repr<2>, max_bits: usize, subnormal_exp: isize) -> usize {
488    if v.significand.is_zero() {
489        return max_bits;
490    }
491    let msb = v.exponent + v.digits() as isize - 1;
492    (msb - subnormal_exp + 1).clamp(1, max_bits as isize) as usize
493}
494
495/// Convert `repr` to base 2 and reduce to a `width`-bit round-to-odd value: the top `width` bits
496/// with the lowest kept bit forced to 1 whenever the conversion was inexact. Rounding this to any
497/// width up to `width - 2` reproduces the correctly-rounded value for every rounding mode, so the
498/// two-step "convert, then round to the final width" cannot double-round.
499///
500/// The conversion is first evaluated at `width + GUARD` bits (work precision `2·(width + GUARD)`)
501/// and only then round-to-odd'd down to `width`. The extra guard is required for wide source
502/// significands (e.g. a decimal `FBig` with hundreds of bits): the base-conversion logarithm is
503/// *near-correct* — its ln/exp series carry a few-ulp error at the work precision — so converting
504/// straight at `width` can land a value whose true result sits within ~`2^{-2·width}` of a
505/// `width`-bit midpoint on the wrong side of that midpoint, and the subsequent round picks the
506/// wrong neighbor (a decimal→f32 subnormal off by 1 ULP). The guard pushes that residual error
507/// well below one `width`-bit ulp.
508#[allow(non_upper_case_globals)]
509fn convert_base_odd<const B: Word>(repr: Repr<B>, width: usize) -> Repr<2> {
510    const GUARD: usize = 24;
511    match Context::<Zero>::new(width + GUARD).convert_base::<B, 2>(repr, None) {
512        Exact(v) => v,
513        Inexact(v, _) if v.significand.is_zero() => v,
514        Inexact(v, _) => {
515            let digits = v.digits();
516            let (sign, mut mag) = v.significand.into_parts();
517            // collapse onto exactly `width` significant bits (drop or pad), then force the lowest
518            // kept bit to 1 to mark the inexact conversion (round-to-odd).
519            let exp = if digits >= width {
520                let shift = digits - width;
521                if shift > 0 {
522                    mag >>= shift;
523                }
524                v.exponent + shift as isize
525            } else {
526                let shift = width - digits;
527                mag <<= shift;
528                v.exponent - shift as isize
529            };
530            mag.set_bit(0);
531            Repr::new(IBig::from_parts(sign, mag), exp)
532        }
533    }
534}
535
536impl<R: Round> Context<R> {
537    // Convert `repr` (base B) to the nearest f64 under this context's rounding mode. A generous
538    // round-to-odd base conversion is rounded once to the target's precision at its own magnitude
539    // (fewer than 53 bits for subnormals), so `into_f64_internal` re-rounds nothing — which would
540    // otherwise double-round subnormals. Handles a source significand of any size.
541    //
542    // Returns `Err(FpError::Overflow/Underflow)` when the value is outside the finite f64 range;
543    // the caller decides whether to saturate that to the directed endpoint (`to_f64`) or report it
544    // as a conversion error (`TryFrom`). This makes `into_f64_internal` the single source of truth
545    // for "is this value in range", shared by both APIs.
546    fn convert_to_f64<const B: Word>(repr: Repr<B>) -> FpResult<f64> {
547        if repr.is_infinite() {
548            return Ok(Inexact(repr.sign() * f64::INFINITY, Rounding::NoOp));
549        }
550        // Underflow short-circuit on the *source* value (before base conversion). For a value far
551        // below half the smallest subnormal (`|x| < 2^-1075`), the result is `±0` under nearest and
552        // the smallest subnormal under outward modes — independent of base conversion. Checking the
553        // source matters because converting a catastrophically tiny value (e.g. a wide-significand
554        // decimal at a hugely negative exponent) drives the conversion's internal `exp` to underflow,
555        // yielding an `odd` with a wildly wrong (too large) magnitude that `encode` then fails to
556        // flag. `log2_bounds` on the source is exact (derived from the significand bit length), so
557        // it sees the true magnitude; `ub < -1075` certifies `|x| < 2^-1075 = ½·MIN_SUBNORMAL`.
558        // (Zero is excluded — it is exactly `0`, not an underflow.)
559        if !repr.significand().is_zero() && repr.log2_bounds().1 < -1075.0 {
560            return Err(FpError::Underflow(repr.sign()));
561        }
562        let odd = convert_base_odd::<B>(repr, 60);
563        // Unified range check (shared by `to_f64` and `TryFrom`): a value beyond f64::MAX is out
564        // of range regardless of rounding mode (the mode only picks the saturation endpoint).
565        // Checked on the base-2 `odd`, BEFORE the significand rounding that could collapse a
566        // beyond-MAX value onto MAX (which `encode` would then miss, breaking mode-independence).
567        // `log2_bounds` fast-rejects the common case; the exact `abs_cmp` runs only near MAX.
568        let (lb, ub) = odd.log2_bounds();
569        if lb > 1024.0
570            || (ub >= 1024.0
571                && odd
572                    .abs_cmp(&(UBig::from(0x1FFFFFFFFFFFFFu64) << 971))
573                    .is_gt())
574        {
575            return Err(FpError::Overflow(odd.sign()));
576        }
577        let bits = significand_bits(&odd, 53, -1074);
578        // The base conversion's rounding flag must propagate: `1e20 → f64` is inexact at the
579        // round-to-odd step even though the already-rounded significand then `encode`s exactly.
580        // This mirrors `Approximation::and_then` — an inexact input lifts an exact `encode` to
581        // inexact with the input's flag, while an inexact `encode` keeps its own flag.
582        let rounded = Context::<R>::new(bits).repr_round(odd);
583        match rounded {
584            Exact(v) => v.into_f64_internal(),
585            Inexact(v, e) => match v.into_f64_internal()? {
586                Exact(f) => Ok(Inexact(f, e)),
587                Inexact(f, e2) => Ok(Inexact(f, e2)),
588            },
589        }
590    }
591
592    // [convert_to_f64] for f32.
593    fn convert_to_f32<const B: Word>(repr: Repr<B>) -> FpResult<f32> {
594        if repr.is_infinite() {
595            return Ok(Inexact(repr.sign() * f32::INFINITY, Rounding::NoOp));
596        }
597        // See `convert_to_f64`: underflow short-circuit on the source value. f32's smallest
598        // subnormal is `2^-149`, so `|x| < 2^-150 = ½·MIN_SUBNORMAL` rounds to `±0` (nearest) or
599        // the smallest subnormal (outward). The source `log2_bounds` avoids the base-conversion
600        // magnitude corruption that would otherwise hide a catastrophic underflow from `encode`.
601        // (Zero is excluded — it is exactly `0`, not an underflow.)
602        if !repr.significand().is_zero() && repr.log2_bounds().1 < -150.0 {
603            return Err(FpError::Underflow(repr.sign()));
604        }
605        let odd = convert_base_odd::<B>(repr, 32);
606        // See `convert_to_f64`: unified range check on the base-2 `odd`, before the significand
607        // rounding. f32::MAX = (2^24 − 1) × 2^104 ≈ 2^128.
608        let (lb, ub) = odd.log2_bounds();
609        if lb > 128.0 || (ub >= 128.0 && odd.abs_cmp(&(UBig::from(0xFFFFFFu64) << 104)).is_gt()) {
610            return Err(FpError::Overflow(odd.sign()));
611        }
612        let bits = significand_bits(&odd, 24, -149);
613        let rounded = Context::<R>::new(bits).repr_round(odd);
614        match rounded {
615            Exact(v) => v.into_f32_internal(),
616            Inexact(v, e) => match v.into_f32_internal()? {
617                Exact(f) => Ok(Inexact(f, e)),
618                Inexact(f, e2) => Ok(Inexact(f, e2)),
619            },
620        }
621    }
622
623    // Convert the [Repr] from base B to base NewB, with the precision under the target base from this context.
624    #[allow(non_upper_case_globals)]
625    fn convert_base<const B: Word, const NewB: Word>(
626        &self,
627        repr: Repr<B>,
628        mut cache: Option<&mut ConstCache>,
629    ) -> Rounded<Repr<NewB>> {
630        // shortcut if NewB is the same as B
631        if NewB == B {
632            return Exact(Repr {
633                significand: repr.significand,
634                exponent: repr.exponent,
635            });
636        }
637
638        // shortcut for infinities, no rounding happens but the result is inexact
639        if repr.is_infinite() {
640            return Inexact(
641                Repr {
642                    significand: repr.significand,
643                    exponent: repr.exponent,
644                },
645                Rounding::NoOp,
646            );
647        }
648
649        if NewB > B {
650            // shortcut if NewB is a power of B
651            let n = ilog_exact(NewB, B);
652            if n > 1 {
653                let (exp, rem) = repr.exponent.div_rem_euclid(n as isize);
654                let signif = repr.significand * B.pow(rem as u32);
655                let repr = Repr::new(signif, exp);
656                return self.repr_round(repr);
657            }
658        } else {
659            // shortcut if B is a power of NewB
660            let n = ilog_exact(B, NewB);
661            if n > 1 {
662                let exp = match repr.exponent.checked_mul(n as isize) {
663                    Some(e) => e,
664                    None => return converted_overflow_repr::<NewB>(repr.exponent > 0, repr.sign()),
665                };
666                return Exact(Repr::new(repr.significand, exp));
667            }
668        }
669
670        // Shortcut: when B and NewB share common factors, factor out the common part.
671        // B = NewB^a * r where gcd(r, NewB) = 1, so B^exp = NewB^(a*exp) * r^exp.
672        // For positive exponents the result is always exact (integer multiplication).
673        // For negative exponents, exact only when r^|exp| divides the significand.
674        let (a, r) = factor_base(B, NewB);
675        if a > 0 && r > 1 {
676            if repr.exponent >= 0 {
677                let sign = repr.sign();
678                let r_exp = UBig::from_word(r).pow(repr.exponent as usize);
679                let significand = repr.significand * r_exp;
680                let exp = match (a as isize).checked_mul(repr.exponent) {
681                    Some(e) => e,
682                    None => return converted_overflow_repr::<NewB>(true, sign),
683                };
684                let new_repr = Repr::<NewB>::new(significand, exp);
685                return self.repr_round(new_repr);
686            } else {
687                let r_exp: IBig = UBig::from_word(r).pow((-repr.exponent) as usize).into();
688                if repr.significand.is_multiple_of(&r_exp) {
689                    let exp = match (a as isize).checked_mul(repr.exponent) {
690                        Some(e) => e,
691                        None => return converted_overflow_repr::<NewB>(false, repr.sign()),
692                    };
693                    let new_repr = Repr::<NewB>::new(repr.significand / r_exp, exp);
694                    return self.repr_round(new_repr);
695                }
696            }
697        }
698
699        // When NewB is a multiple of B: compute significand * B^exp directly
700        // as an integer, then express in base NewB.
701        if NewB % B == 0 && repr.exponent >= 0 {
702            let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
703            let new_repr = Repr::<NewB>::new(signif, 0);
704            return self.repr_round(new_repr);
705        }
706
707        // if the base cannot be converted losslessly, the precision must be set
708        if self.precision == 0 {
709            panic_unlimited_precision();
710        }
711
712        // choose a exponent threshold such that number with exponent smaller than this value
713        // will be converted by directly evaluating the power. The threshold here is chosen such
714        // that the power under base 10 will fit in a double word.
715        const THRESHOLD_SMALL_EXP: isize = (Word::BITS as f32 * 0.60206) as isize; // word bits * 2 / log2(10)
716        if repr.exponent.abs() <= THRESHOLD_SMALL_EXP {
717            // if the exponent is small enough, directly evaluate the exponent
718            if repr.exponent >= 0 {
719                let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
720                Exact(Repr::new(signif, 0))
721            } else {
722                let den: Repr<NewB> =
723                    Repr::new(Repr::<B>::BASE.pow(-repr.exponent as usize).into(), 0);
724                // repr_div requires the dividend to be no wider than `precision + divisor`, so
725                // pre-shrink the significand the same way Context::div does — the caller, not
726                // the kernel, is responsible for bounding the dividend. Rounding it to
727                // `den.digits() + precision` preserves enough information for the division to
728                // be correctly rounded at `precision`.
729                let num: Repr<NewB> = Repr::new(repr.significand, 0);
730                let num =
731                    if !num.is_pos_zero() && num.digits_ub() > den.digits_lb() + self.precision {
732                        Self::new(den.digits() + self.precision)
733                            .repr_round_ref(&num)
734                            .value()
735                    } else {
736                        num
737                    };
738                match self.repr_div(num, den) {
739                    Ok(v) => v.map(|r: Repr<NewB>| Repr {
740                        significand: r.significand,
741                        exponent: r.exponent,
742                    }),
743                    Err(FpError::Overflow(sign)) => {
744                        Inexact(Repr::<NewB>::infinity_with_sign(sign), Rounding::NoOp)
745                    }
746                    Err(FpError::Underflow(sign)) => {
747                        Inexact(Repr::<NewB>::zero_with_sign(sign), Rounding::NoOp)
748                    }
749                    Err(_) => unreachable!(),
750                }
751            }
752        } else {
753            // if the exponent is large, then we first estimate the result exponent as floor(exponent * log(B) / log(NewB)),
754            // then the fractional part is multiplied with the original significand
755            let work_context = Context::<R>::new(2 * self.precision); // double the precision to get the precise logarithm
756                                                                      // ln(old base) and ln(new base) — near-correct is sufficient for the exponent estimate,
757                                                                      // and using the near-correct `ln_compute`/`ln_base` (R: Round) keeps base conversion
758                                                                      // off the `ErrorBounds` bound. Both are computed in base NewB so the euclidean division
759                                                                      // has matching bases.
760            let new_exp = repr.exponent
761                * work_context
762                    .ln_compute::<NewB>(
763                        &Repr::new(Repr::<B>::BASE.into(), 0),
764                        work_context.precision,
765                        false,
766                        reborrow_cache(&mut cache),
767                    )
768                    .0;
769            let (exponent, rem) =
770                new_exp.div_rem_euclid(work_context.ln_base::<NewB>(reborrow_cache(&mut cache)));
771            let exponent_sign = exponent.sign();
772            let exponent: isize = match exponent.try_into() {
773                Ok(v) => v,
774                Err(_) => {
775                    return converted_overflow_repr::<NewB>(
776                        exponent_sign == Sign::Positive,
777                        repr.sign(),
778                    );
779                }
780            };
781            // exp(fractional exponent) — near-correct is sufficient (it scales the significand),
782            // so use `exp_compute` (R: Round) and stay off the `ErrorBounds` bound.
783            let n = 1usize << (work_context.precision.bit_len() / 2);
784            let exp_rem = work_context
785                .exp_compute::<NewB>(
786                    &rem.repr,
787                    work_context.precision,
788                    false,
789                    n,
790                    reborrow_cache(&mut cache),
791                )
792                .expect("exp(reduced rem) cannot overflow (|rem| < B^-n)")
793                .0;
794            let significand = repr.significand * exp_rem.repr.significand;
795            let repr = Repr::new(significand, exponent + exp_rem.repr.exponent);
796            self.repr_round(repr)
797        }
798    }
799}
800
801impl<const B: Word> Repr<B> {
802    // this method requires that the representation is already rounded to 24 binary bits
803    fn into_f32_internal(self) -> FpResult<f32> {
804        assert!(B == 2);
805        debug_assert!(self.is_finite());
806        debug_assert!(self.significand.bit_len() <= 24);
807
808        let sign = self.sign();
809        if self.is_neg_zero() {
810            // encode() would drop the sign of -0; preserve it exactly
811            return Ok(Exact(sign * 0f32));
812        }
813        let man24: i32 = self.significand.try_into().unwrap();
814        match f32::encode(man24, self.exponent as i16) {
815            Exact(v) => Ok(Exact(v)),
816            Inexact(v, _) if v.is_infinite() => Err(FpError::Overflow(sign)),
817            Inexact(0.0, _) => Err(FpError::Underflow(sign)),
818            Inexact(v, _) => Ok(Inexact(v, Rounding::NoOp)),
819        }
820    }
821
822    /// Convert the float number representation to a [f32] with the default IEEE 754 rounding mode.
823    ///
824    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
825    /// the float number with a specific rounding mode, please use [FBig::to_f32].
826    ///
827    /// # Examples
828    ///
829    /// ```
830    /// # use dashu_base::Approximation::*;
831    /// # use dashu_float::{Repr, round::Rounding::*};
832    /// assert_eq!(Repr::<2>::one().to_f32(), Exact(1.0));
833    /// assert_eq!(Repr::<10>::infinity().to_f32(), Inexact(f32::INFINITY, NoOp));
834    /// ```
835    #[inline]
836    pub fn to_f32(&self) -> Rounded<f32> {
837        match Context::<HalfEven>::convert_to_f32(self.clone()) {
838            Ok(rounded) => rounded,
839            Err(err) => f32_directed_endpoint::<HalfEven>(err),
840        }
841    }
842
843    // this method requires that the representation is already rounded to 53 binary bits
844    fn into_f64_internal(self) -> FpResult<f64> {
845        assert!(B == 2);
846        debug_assert!(self.is_finite());
847        debug_assert!(self.significand.bit_len() <= 53);
848
849        let sign = self.sign();
850        if self.is_neg_zero() {
851            // encode() would drop the sign of -0; preserve it exactly
852            return Ok(Exact(sign * 0f64));
853        }
854        let man53: i64 = self.significand.try_into().unwrap();
855        match f64::encode(man53, self.exponent as i16) {
856            Exact(v) => Ok(Exact(v)),
857            Inexact(v, _) if v.is_infinite() => Err(FpError::Overflow(sign)),
858            Inexact(0.0, _) => Err(FpError::Underflow(sign)),
859            Inexact(v, _) => Ok(Inexact(v, Rounding::NoOp)),
860        }
861    }
862
863    /// Convert the float number representation to a [f64] with the default IEEE 754 rounding mode.
864    ///
865    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
866    /// the float number with a specific rounding mode, please use [FBig::to_f64].
867    ///
868    /// # Examples
869    ///
870    /// ```
871    /// # use dashu_base::Approximation::*;
872    /// # use dashu_float::{Repr, round::Rounding::*};
873    /// assert_eq!(Repr::<2>::one().to_f64(), Exact(1.0));
874    /// assert_eq!(Repr::<10>::infinity().to_f64(), Inexact(f64::INFINITY, NoOp));
875    /// ```
876    #[inline]
877    pub fn to_f64(&self) -> Rounded<f64> {
878        match Context::<HalfEven>::convert_to_f64(self.clone()) {
879            Ok(rounded) => rounded,
880            Err(err) => f64_directed_endpoint::<HalfEven>(err),
881        }
882    }
883
884    /// Convert the float number representation to a [IBig].
885    ///
886    /// The fractional part is always rounded to zero. To convert with other rounding modes,
887    /// please use [FBig::to_int()].
888    ///
889    /// # Warning
890    ///
891    /// If the float number has a very large exponent, it will be evaluated and result
892    /// in allocating an huge integer and it might eat up all your memory.
893    ///
894    /// To get a rough idea of how big the number is, it's recommended to use [EstimatedLog2].
895    ///
896    /// # Examples
897    ///
898    /// ```
899    /// # use dashu_base::Approximation::*;
900    /// # use dashu_int::IBig;
901    /// # use dashu_float::{Repr, round::Rounding::*};
902    /// assert_eq!(Repr::<2>::neg_one().to_int(), Exact(IBig::NEG_ONE));
903    /// ```
904    ///
905    /// # Panics
906    ///
907    /// Panics if the number is infinte.
908    pub fn to_int(&self) -> Rounded<IBig> {
909        assert_finite(self);
910
911        if self.exponent >= 0 {
912            // the number is already an integer
913            Exact(shl_digits::<B>(&self.significand, self.exponent as usize))
914        } else if self.smaller_than_one() {
915            // the number is definitely smaller than
916            Inexact(IBig::ZERO, Rounding::NoOp)
917        } else {
918            let int = shr_digits::<B>(&self.significand, (-self.exponent) as usize);
919            Inexact(int, Rounding::NoOp)
920        }
921    }
922}
923
924impl<const B: Word> From<UBig> for Repr<B> {
925    #[inline]
926    fn from(n: UBig) -> Self {
927        Self::new(n.into(), 0)
928    }
929}
930impl<R: Round, const B: Word> From<UBig> for FBig<R, B> {
931    #[inline]
932    fn from(n: UBig) -> Self {
933        Self::from_parts(n.into(), 0)
934    }
935}
936
937impl<const B: Word> From<IBig> for Repr<B> {
938    #[inline]
939    fn from(n: IBig) -> Self {
940        Self::new(n, 0)
941    }
942}
943impl<R: Round, const B: Word> From<IBig> for FBig<R, B> {
944    #[inline]
945    fn from(n: IBig) -> Self {
946        Self::from_parts(n, 0)
947    }
948}
949
950impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for IBig {
951    type Error = ConversionError;
952
953    #[inline]
954    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
955        if value.repr.is_infinite() {
956            Err(ConversionError::OutOfBounds)
957        } else if value.repr.significand.is_zero() {
958            // A zero significand is integer zero regardless of exponent. This also
959            // accepts IEEE-754 signed zero, whose sign is carried by a -1 exponent
960            // sentinel (not the significand); it is treated as plain 0. The zero
961            // must be handled here rather than in the `else` branch below, which
962            // shifts by `exponent as usize` and would underflow on the -1 sentinel.
963            Ok(value.repr.significand)
964        } else if value.repr.exponent < 0 {
965            Err(ConversionError::LossOfPrecision)
966        } else {
967            let mut int = value.repr.significand;
968            shl_digits_in_place::<B>(&mut int, value.repr.exponent as usize);
969            Ok(int)
970        }
971    }
972}
973
974impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for UBig {
975    type Error = ConversionError;
976
977    #[inline]
978    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
979        let int: IBig = value.try_into()?;
980        int.try_into()
981    }
982}
983
984macro_rules! fbig_unsigned_conversions {
985    ($($t:ty)*) => {$(
986        impl<const B: Word> From<$t> for Repr<B> {
987            #[inline]
988            fn from(value: $t) -> Repr<B> {
989                UBig::from(value).into()
990            }
991        }
992        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
993            #[inline]
994            fn from(value: $t) -> FBig<R, B> {
995                UBig::from(value).into()
996            }
997        }
998
999        impl<const B: Word> TryFrom<Repr<B>> for $t {
1000            type Error = ConversionError;
1001
1002            fn try_from(value: Repr<B>) -> Result<Self, Self::Error> {
1003                if value.sign() == Sign::Negative || value.is_infinite() {
1004                    Err(ConversionError::OutOfBounds)
1005                } else {
1006                    let (log2_lb, _) = value.log2_bounds();
1007                    if log2_lb >= <$t>::BITS as f32 {
1008                        Err(ConversionError::OutOfBounds)
1009                    } else if value.exponent < 0 {
1010                        Err(ConversionError::LossOfPrecision)
1011                    } else {
1012                        shl_digits::<B>(&value.significand, value.exponent as usize).try_into()
1013                    }
1014                }
1015            }
1016        }
1017        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
1018            type Error = ConversionError;
1019
1020            #[inline]
1021            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
1022                value.repr.try_into()
1023            }
1024        }
1025    )*};
1026}
1027fbig_unsigned_conversions!(u8 u16 u32 u64 u128 usize);
1028
1029macro_rules! fbig_signed_conversions {
1030    ($($t:ty)*) => {$(
1031        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
1032            #[inline]
1033            fn from(value: $t) -> FBig<R, B> {
1034                IBig::from(value).into()
1035            }
1036        }
1037
1038        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
1039            type Error = ConversionError;
1040
1041            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
1042                if value.repr.is_infinite() {
1043                    Err(ConversionError::OutOfBounds)
1044                } else {
1045                    let (log2_lb, _) = value.repr.log2_bounds();
1046                    if log2_lb >= <$t>::BITS as f32 {
1047                        Err(ConversionError::OutOfBounds)
1048                    } else if value.repr.exponent < 0 {
1049                        Err(ConversionError::LossOfPrecision)
1050                    } else {
1051                        shl_digits::<B>(&value.repr.significand, value.repr.exponent as usize).try_into()
1052                    }
1053                }
1054            }
1055        }
1056    )*};
1057}
1058fbig_signed_conversions!(i8 i16 i32 i64 i128 isize);
1059
1060// The directed saturation endpoint for an out-of-range f32/f64 result, chosen from the `FpError`
1061// returned by `into_f*_internal`. Overflow saturates to ±MAX or ±∞ per the mode (outward modes
1062// reach ±∞; toward-zero/opposite/nearest saturate to the largest finite); underflow saturates to
1063// ±0 or the smallest subnormal of that sign. `round_low_part`'s AddOne/SubOne verdict on a
1064// same-sign residual is exactly the outward-vs-inward decision; only its directional verdict is
1065// used. This is the single place that picks the endpoint, shared by `to_f32`/`to_f64` (Repr uses
1066// HalfEven, FBig uses its own mode).
1067macro_rules! impl_float_directed_endpoint {
1068    (
1069        $fn:ident, $t:ty, $max:expr, $min:expr, $inf:expr, $neg_inf:expr,
1070        $smallest_sub:expr, $neg_smallest_sub:expr
1071    ) => {
1072        fn $fn<R: Round>(err: FpError) -> Rounded<$t> {
1073            match err {
1074                FpError::Overflow(sign) => {
1075                    let adj = if sign == Sign::Positive {
1076                        R::round_low_part(&IBig::ONE, Sign::Positive, || {
1077                            core::cmp::Ordering::Greater
1078                        })
1079                    } else {
1080                        R::round_low_part(&IBig::NEG_ONE, Sign::Negative, || {
1081                            core::cmp::Ordering::Greater
1082                        })
1083                    };
1084                    Inexact(
1085                        match (sign, adj) {
1086                            (Sign::Positive, AddOne) => $inf,
1087                            (Sign::Positive, _) => $max,
1088                            (Sign::Negative, SubOne) => $neg_inf,
1089                            (Sign::Negative, _) => $min,
1090                        },
1091                        adj,
1092                    )
1093                }
1094                FpError::Underflow(sign) => {
1095                    let adj = if sign == Sign::Positive {
1096                        R::round_low_part(&IBig::ZERO, Sign::Positive, || core::cmp::Ordering::Less)
1097                    } else {
1098                        R::round_low_part(&IBig::ZERO, Sign::Negative, || core::cmp::Ordering::Less)
1099                    };
1100                    Inexact(
1101                        match (sign, adj) {
1102                            (Sign::Positive, AddOne) => $smallest_sub, // smallest positive subnormal
1103                            (Sign::Positive, _) => 0.0,
1104                            (Sign::Negative, SubOne) => $neg_smallest_sub,
1105                            (Sign::Negative, _) => -0.0,
1106                        },
1107                        adj,
1108                    )
1109                }
1110                // `into_f*_internal` only returns Overflow/Underflow; the infinite-input case is
1111                // handled by `convert_to_f*` (returning `Ok`) before this is reached.
1112                _ => unreachable!("convert_to_f* only returns Overflow/Underflow here"),
1113            }
1114        }
1115    };
1116}
1117impl_float_directed_endpoint!(
1118    f32_directed_endpoint,
1119    f32,
1120    f32::MAX,
1121    f32::MIN,
1122    f32::INFINITY,
1123    f32::NEG_INFINITY,
1124    f32::from_bits(1),
1125    f32::from_bits(0x8000_0001)
1126);
1127impl_float_directed_endpoint!(
1128    f64_directed_endpoint,
1129    f64,
1130    f64::MAX,
1131    f64::MIN,
1132    f64::INFINITY,
1133    f64::NEG_INFINITY,
1134    f64::from_bits(1),
1135    f64::from_bits(0x8000_0000_0000_0001)
1136);
1137
1138macro_rules! impl_from_fbig_for_float {
1139    ($t:ty, $convert:ident) => {
1140        impl TryFrom<Repr<2>> for $t {
1141            type Error = ConversionError;
1142
1143            #[inline]
1144            fn try_from(value: Repr<2>) -> Result<Self, Self::Error> {
1145                if value.is_infinite() {
1146                    return Err(ConversionError::LossOfPrecision);
1147                }
1148                // Range detection is shared with `to_f32`/`to_f64` via `convert_to_f*`: it returns
1149                // `Err(Overflow)` for a value beyond the largest finite `$t`, so `OutOfBounds` is
1150                // reported the same way under every rounding mode (Repr uses HalfEven here).
1151                match Context::<HalfEven>::$convert(value) {
1152                    Ok(Exact(v)) => Ok(v),
1153                    Ok(Inexact(_, _)) => Err(ConversionError::LossOfPrecision),
1154                    Err(FpError::Overflow(_)) => Err(ConversionError::OutOfBounds),
1155                    Err(FpError::Underflow(_)) => Err(ConversionError::LossOfPrecision),
1156                    Err(_) => unreachable!(),
1157                }
1158            }
1159        }
1160
1161        impl<R: Round> TryFrom<FBig<R, 2>> for $t {
1162            type Error = ConversionError;
1163
1164            #[inline]
1165            fn try_from(value: FBig<R, 2>) -> Result<Self, Self::Error> {
1166                if value.repr.is_infinite() {
1167                    return Err(ConversionError::LossOfPrecision);
1168                }
1169                // A value beyond the largest finite `$t` is out of range whatever the rounding mode:
1170                // the mode only selects the saturation endpoint (±MAX vs ±∞), and `convert_to_f*`
1171                // reports that range condition as `Err(Overflow)` regardless of mode — so
1172                // `Err(OutOfBounds)` reliably means "beyond the finite range", unlike the old
1173                // result-infiniteness check (which flipped LossOfPrecision/OutOfBounds with the mode).
1174                match Context::<R>::$convert(value.repr) {
1175                    Ok(Exact(v)) => Ok(v),
1176                    Ok(Inexact(_, _)) => Err(ConversionError::LossOfPrecision),
1177                    Err(FpError::Overflow(_)) => Err(ConversionError::OutOfBounds),
1178                    Err(FpError::Underflow(_)) => Err(ConversionError::LossOfPrecision),
1179                    Err(_) => unreachable!(),
1180                }
1181            }
1182        }
1183    };
1184}
1185impl_from_fbig_for_float!(f32, convert_to_f32);
1186impl_from_fbig_for_float!(f64, convert_to_f64);
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191    use crate::repr::Repr;
1192
1193    // Directed overflow must reach the endpoint for a value whose *most*-significant bit straddles
1194    // f32::MAX (not only for values whose lsb exponent is ≥ 128). `3·2¹²⁷` ≈ 1.5·2¹²⁸ overflows
1195    // f32::MAX = (2 − 2⁻²³)·2¹²⁷, yet its lsb exponent is 127 — the old exponent-gated branch fell
1196    // through to `encode`, which saturates to ±∞ mode-blindly.
1197    #[test]
1198    fn f32_directed_overflow_at_msb_boundary() {
1199        use crate::round::mode::{Down, Up};
1200        // f32: 3·2^127 under Zero/Down -> f32::MAX, under Up/Away -> +∞.
1201        let zero = FBig::<Zero, 2>::from_parts(3.into(), 127);
1202        let down = FBig::<Down, 2>::from_parts(3.into(), 127);
1203        let up = FBig::<Up, 2>::from_parts(3.into(), 127);
1204        assert_eq!(zero.to_f32().value().to_bits(), 0x7f7fffff); // f32::MAX
1205        assert_eq!(down.to_f32().value().to_bits(), 0x7f7fffff);
1206        assert!(up.to_f32().value().is_infinite() && up.to_f32().value().is_sign_positive());
1207        // negative mirror
1208        let nzero = FBig::<Zero, 2>::from_parts((-3).into(), 127);
1209        assert_eq!(nzero.to_f32().value().to_bits(), 0xff7fffff); // f32::MIN
1210
1211        // f64: 3·2^1023 overflows f64::MAX; lsb exponent 1023 < 1024.
1212        let z64 = FBig::<Zero, 2>::from_parts(3.into(), 1023);
1213        assert_eq!(z64.to_f64().value().to_bits(), 0x7fefffffffffffff); // f64::MAX
1214        let u64 = FBig::<Up, 2>::from_parts(3.into(), 1023);
1215        assert!(u64.to_f64().value().is_infinite() && u64.to_f64().value().is_sign_positive());
1216    }
1217
1218    // Directed underflow must reach the endpoint through the `encode` path too (not only for the
1219    // extreme exponents caught by the old explicit branch). `2⁻¹⁶⁰` is below the smallest subnormal;
1220    // under Up a positive value must round up to `2⁻¹⁴⁹`, but `encode` returns ±0 mode-blindly.
1221    #[test]
1222    fn f32_directed_underflow_through_encode() {
1223        use crate::round::mode::{Away, Down, Up};
1224        // f32: 2^-160 under Up/Away -> smallest +subnormal, under Zero/Down -> +0.
1225        let up = FBig::<Up, 2>::from_parts(IBig::ONE, -160);
1226        let away = FBig::<Away, 2>::from_parts(IBig::ONE, -160);
1227        let zero = FBig::<Zero, 2>::from_parts(IBig::ONE, -160);
1228        let down = FBig::<Down, 2>::from_parts(IBig::ONE, -160);
1229        assert_eq!(up.to_f32().value().to_bits(), 0x00000001); // smallest +subnormal
1230        assert_eq!(away.to_f32().value().to_bits(), 0x00000001);
1231        assert_eq!(zero.to_f32().value().to_bits(), 0x0);
1232        assert_eq!(down.to_f32().value().to_bits(), 0x0);
1233        // negative: Down/Away -> smallest -subnormal, Zero/Up -> -0.
1234        let ndown = FBig::<Down, 2>::from_parts(-IBig::ONE, -160);
1235        assert_eq!(ndown.to_f32().value().to_bits(), 0x80000001);
1236
1237        // f64: 2^-1100 under Up -> smallest +subnormal.
1238        let u64 = FBig::<Up, 2>::from_parts(IBig::ONE, -1100);
1239        assert_eq!(u64.to_f64().value().to_bits(), 0x0000_0000_0000_0001);
1240    }
1241
1242    // A decimal FBig whose value exceeds f32::MAX must saturate to the largest *finite* f32 under
1243    // toward-zero (Zero), not +∞ — directed overflow picks the endpoint per mode.
1244    #[test]
1245    fn f32_overflow_saturates_to_max_under_toward_zero() {
1246        use crate::round::mode::Up;
1247        // value ≈ 1.8e67 ≫ f32::MAX
1248        let sig: IBig = "18113714167384154970503568309331051197800435559900844351020490293248000000000000000000000000000000000000000000000000000000000000000000000040081793412673420422647135518538018600544982168035325793404432580816367361955984101780462905766719198411690240".parse().unwrap();
1249        let down = FBig::<Zero, 10>::from_parts(sig.clone(), -180);
1250        assert_eq!(down.to_f32().value().to_bits(), 0x7f7fffff); // f32::MAX, not +∞
1251                                                                 // The same value toward +∞ does reach +∞.
1252        let up = FBig::<Up, 10>::from_parts(sig, -180);
1253        assert!(up.to_f32().value().is_infinite());
1254    }
1255
1256    // A wide decimal significand near an f32 subnormal midpoint must round to the correct
1257    // neighbor. The near-correct base-conversion logarithm previously landed on the wrong side of a
1258    // 32-bit midpoint, producing a result 1 ULP off (0x00040008 instead of 0x00040007).
1259    #[test]
1260    fn f32_decimal_subnormal_rounds_correctly() {
1261        let v = FBig::<HalfEven, 10>::from_parts(
1262            "367352494370447282365772889742681992006459962834329374643515088008836389924495676300982092025765783512749250624297822169761305238359955010699895018824154119671"
1263                .parse()
1264                .unwrap(),
1265            -198,
1266        );
1267        assert_eq!(v.to_f32().value().to_bits(), 0x00040007);
1268    }
1269
1270    // A positive value below the smallest subnormal must round *up* to that smallest subnormal
1271    // under Up/Away (and to ±0 under toward-zero/opposite/nearest) — the underflow path used to
1272    // return a mode-blind signed zero, which is not an upper bound for a positive value under Up.
1273    #[test]
1274    fn f64_directed_underflow_below_smallest_subnormal() {
1275        use crate::round::mode::Down;
1276        // tiny positive binary value, far below 2^-1074
1277        let up = FBig::<crate::round::mode::Up, 2>::from_parts(IBig::ONE, -20000);
1278        let away = FBig::<crate::round::mode::Away, 2>::from_parts(IBig::ONE, -20000);
1279        let zero = FBig::<Zero, 2>::from_parts(IBig::ONE, -20000);
1280        let down = FBig::<Down, 2>::from_parts(IBig::ONE, -20000);
1281        assert_eq!(up.to_f64().value().to_bits(), 0x0000_0000_0000_0001); // smallest +subnormal
1282        assert_eq!(away.to_f64().value().to_bits(), 0x0000_0000_0000_0001);
1283        assert_eq!(zero.to_f64().value().to_bits(), 0x0); // +0
1284        assert_eq!(down.to_f64().value().to_bits(), 0x0);
1285
1286        // tiny negative: Down/Away -> smallest -subnormal, Zero/Up -> -0
1287        let ndown = FBig::<Down, 2>::from_parts(-IBig::ONE, -20000);
1288        let nup = FBig::<crate::round::mode::Up, 2>::from_parts(-IBig::ONE, -20000);
1289        assert_eq!(ndown.to_f64().value().to_bits(), 0x8000_0000_0000_0001); // smallest -subnormal
1290        assert_eq!(nup.to_f64().value().to_bits(), 0x8000_0000_0000_0000); // -0
1291    }
1292
1293    // A wide-significand *decimal* value far below ½·MIN_SUBNORMAL (exponent −20000). The base
1294    // conversion's internal `exp` underflows for such a catastrophically tiny value, so without the
1295    // source-`log2_bounds` short-circuit the converted magnitude is wrong and `to_f64` returned a
1296    // spurious finite subnormal (≈2^-593) instead of the directed underflow endpoint. The binary
1297    // test above doesn't hit this — it skips base conversion entirely.
1298    #[test]
1299    fn f64_decimal_wide_significand_underflow() {
1300        use crate::round::mode::{Down, Up};
1301        let wide = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
1302            .parse::<IBig>()
1303            .unwrap();
1304        for prec in [20usize, 50, 100, 500] {
1305            let he = FBig::<HalfEven, 10>::from_parts(wide.clone(), -20000)
1306                .with_precision(prec)
1307                .value();
1308            let up = FBig::<Up, 10>::from_parts(wide.clone(), -20000)
1309                .with_precision(prec)
1310                .value();
1311            let dn = FBig::<Down, 10>::from_parts(wide.clone(), -20000)
1312                .with_precision(prec)
1313                .value();
1314            // positive value: nearest/Down -> +0, Up -> smallest positive subnormal
1315            assert_eq!(he.to_f64().value().to_bits(), 0x0, "HalfEven @ prec {prec}");
1316            assert_eq!(dn.to_f64().value().to_bits(), 0x0, "Down @ prec {prec}");
1317            assert_eq!(up.to_f64().value().to_bits(), 0x0000_0000_0000_0001, "Up @ prec {prec}");
1318            // f32 mirror: |x| < 2^-150 = ½·MIN_SUBNORMAL -> +0 / smallest +subnormal
1319            assert_eq!(he.to_f32().value().to_bits(), 0x0u32, "f32 HalfEven @ prec {prec}");
1320            assert_eq!(up.to_f32().value().to_bits(), 0x0000_0001u32, "f32 Up @ prec {prec}");
1321
1322            // negative value: nearest/Up -> -0, Down -> smallest negative subnormal
1323            let neg = FBig::<HalfEven, 10>::from_parts(-wide.clone(), -20000)
1324                .with_precision(prec)
1325                .value();
1326            let ndn = FBig::<Down, 10>::from_parts(-wide.clone(), -20000)
1327                .with_precision(prec)
1328                .value();
1329            assert_eq!(
1330                neg.to_f64().value().to_bits(),
1331                0x8000_0000_0000_0000,
1332                "neg HalfEven @ prec {prec}"
1333            );
1334            assert_eq!(
1335                ndn.to_f64().value().to_bits(),
1336                0x8000_0000_0000_0001,
1337                "neg Down @ prec {prec}"
1338            );
1339        }
1340    }
1341
1342    #[test]
1343    fn ibig_try_from_accepts_signed_zero() {
1344        // IEEE-754 signed zero (sign encoded in a -1 exponent sentinel) is plain 0.
1345        let neg_zero = FBig::<HalfAway, 10>::new(Repr::neg_zero(), Context::new(8));
1346        assert_eq!(IBig::try_from(neg_zero), Ok(IBig::from(0)));
1347
1348        // positive zero already worked, and still does
1349        let pos_zero = FBig::<HalfAway, 10>::new(Repr::zero(), Context::new(8));
1350        assert_eq!(IBig::try_from(pos_zero), Ok(IBig::from(0)));
1351
1352        // UBig delegates to the IBig impl, so it accepts signed zero too
1353        let neg_zero = FBig::<HalfAway, 2>::new(Repr::neg_zero(), Context::new(8));
1354        assert_eq!(UBig::try_from(neg_zero), Ok(UBig::from(0u8)));
1355
1356        // a genuine fractional value must still be rejected
1357        let frac = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(1), -1), Context::new(8));
1358        assert_eq!(IBig::try_from(frac), Err(ConversionError::LossOfPrecision));
1359
1360        // a normal integer round-trips exactly
1361        let int_val = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(42), 0), Context::new(8));
1362        assert_eq!(IBig::try_from(int_val), Ok(IBig::from(42)));
1363    }
1364
1365    #[test]
1366    fn with_base_high_precision_no_overflow() {
1367        // Regression for issue #95: converting a high-precision base-2 float to base
1368        // 10 panicked on 32-bit targets ("arithmetic operations with the infinity are
1369        // not allowed!"). The base conversion evaluates exp(r) as `sum^(B^n)` through
1370        // `powi` with a huge exponent (B^n) on a base (sum) very close to 1; `powi`'s
1371        // overflow guard estimated log2(base) with the catastrophically-canceling
1372        // `log2_est`, and the ~1e-4 of f32 noise scaled by the exponent crossed the
1373        // (much smaller on 32-bit) isize threshold, yielding a spurious ±inf that then
1374        // panicked when shifted. See `powi` in exp.rs for the fix.
1375        use crate::round::mode::Zero;
1376        use core::str::FromStr;
1377
1378        // The reporter's input: -1.1111…0011 in binary (578 significant bits), written
1379        // in the hex form dashu accepts for base-2 floats (`0x1.<hex>…`). The value is
1380        // identical to the raw binary literal.
1381        let num = FBig::<Zero, 2>::from_str(
1382            "-0x1.fffdc8d645194a5a95df4be063472d4406dd096339dd7dc2a8527d208b3da7b9e5c36b4f49a7982cb2ad20a4e7e4c016f858fe8cddea011a6d01fe3823189c4ed4f57a7babc331498",
1383        )
1384        .unwrap();
1385
1386        // at the original 578-bit precision the conversion succeeds …
1387        let a = num
1388            .clone()
1389            .with_precision(578)
1390            .value()
1391            .with_base::<10>()
1392            .value();
1393        assert!(a.repr().is_finite());
1394        // … and so does a slightly higher precision (586), which panicked on 32-bit
1395        // (wasm32 / i686). The result matches the value computed on 64-bit. Compared
1396        // by value (FBig equality ignores context) rather than via string formatting,
1397        // so this works under no_std too.
1398        let b = num.with_precision(586).value().with_base::<10>().value();
1399        assert!(b.repr().is_finite());
1400        let expected = FBig::<Zero, 10>::from_str(
1401            "-1.9999661944503703041843468850635057967553124154072485151176192294480158424234268438137612977886891381228704640656094986435381057574477216648567249609280392009533217665484389886",
1402        )
1403        .unwrap();
1404        assert_eq!(b, expected);
1405    }
1406}