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, DivExact, DivRemEuclid, EstimatedLog2,
8    FloatEncoding, 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 [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 let Some(quot) = (&repr.significand).div_exact(r_exp, &()) {
689                    // the quotient's sign is the dividend's (r_exp > 0)
690                    let exp = match (a as isize).checked_mul(repr.exponent) {
691                        Some(e) => e,
692                        None => return converted_overflow_repr::<NewB>(false, quot.sign()),
693                    };
694                    let new_repr = Repr::<NewB>::new(quot, exp);
695                    return self.repr_round(new_repr);
696                }
697            }
698        }
699
700        // When NewB is a multiple of B: compute significand * B^exp directly
701        // as an integer, then express in base NewB.
702        if NewB % B == 0 && repr.exponent >= 0 {
703            let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
704            let new_repr = Repr::<NewB>::new(signif, 0);
705            return self.repr_round(new_repr);
706        }
707
708        // if the base cannot be converted losslessly, the precision must be set
709        if self.precision == 0 {
710            panic_unlimited_precision();
711        }
712
713        // choose a exponent threshold such that number with exponent smaller than this value
714        // will be converted by directly evaluating the power. The threshold here is chosen such
715        // that the power under base 10 will fit in a double word.
716        const THRESHOLD_SMALL_EXP: isize = (Word::BITS as f32 * 0.60206) as isize; // word bits * 2 / log2(10)
717        if repr.exponent.abs() <= THRESHOLD_SMALL_EXP {
718            // if the exponent is small enough, directly evaluate the exponent
719            if repr.exponent >= 0 {
720                let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
721                Exact(Repr::new(signif, 0))
722            } else {
723                let den: Repr<NewB> =
724                    Repr::new(Repr::<B>::BASE.pow(-repr.exponent as usize).into(), 0);
725                // repr_div requires the dividend to be no wider than `precision + divisor`, so
726                // pre-shrink the significand the same way Context::div does — the caller, not
727                // the kernel, is responsible for bounding the dividend. Rounding it to
728                // `den.digits() + precision` preserves enough information for the division to
729                // be correctly rounded at `precision`.
730                let num: Repr<NewB> = Repr::new(repr.significand, 0);
731                let num =
732                    if !num.is_pos_zero() && num.digits_ub() > den.digits_lb() + self.precision {
733                        Self::new(den.digits() + self.precision)
734                            .repr_round_ref(&num)
735                            .value()
736                    } else {
737                        num
738                    };
739                match self.repr_div(num, den) {
740                    Ok(v) => v.map(|r: Repr<NewB>| Repr {
741                        significand: r.significand,
742                        exponent: r.exponent,
743                    }),
744                    Err(FpError::Overflow(sign)) => {
745                        Inexact(Repr::<NewB>::infinity_with_sign(sign), Rounding::NoOp)
746                    }
747                    Err(FpError::Underflow(sign)) => {
748                        Inexact(Repr::<NewB>::zero_with_sign(sign), Rounding::NoOp)
749                    }
750                    Err(_) => unreachable!(),
751                }
752            }
753        } else {
754            // if the exponent is large, then we first estimate the result exponent as floor(exponent * log(B) / log(NewB)),
755            // then the fractional part is multiplied with the original significand
756            let work_context = Context::<R>::new(2 * self.precision); // double the precision to get the precise logarithm
757                                                                      // ln(old base) and ln(new base) — near-correct is sufficient for the exponent estimate,
758                                                                      // and using the near-correct `ln_compute`/`ln_base` (R: Round) keeps base conversion
759                                                                      // off the `ErrorBounds` bound. Both are computed in base NewB so the euclidean division
760                                                                      // has matching bases.
761            let new_exp = repr.exponent
762                * work_context
763                    .ln_compute::<NewB>(
764                        &Repr::new(Repr::<B>::BASE.into(), 0),
765                        work_context.precision,
766                        false,
767                        reborrow_cache(&mut cache),
768                    )
769                    .to_value_radius::<R>()
770                    .0;
771            let (exponent, rem) =
772                new_exp.div_rem_euclid(work_context.ln_base::<NewB>(reborrow_cache(&mut cache)));
773            let exponent_sign = exponent.sign();
774            let exponent: isize = match exponent.try_into() {
775                Ok(v) => v,
776                Err(_) => {
777                    return converted_overflow_repr::<NewB>(
778                        exponent_sign == Sign::Positive,
779                        repr.sign(),
780                    );
781                }
782            };
783            // exp(fractional exponent) — near-correct is sufficient (it scales the significand),
784            // so use `exp_compute` (R: Round) and stay off the `ErrorBounds` bound.
785            let n = 1usize << (work_context.precision.bit_len() / 2);
786            let exp_rem = work_context
787                .exp_compute::<NewB>(
788                    &rem.repr,
789                    work_context.precision,
790                    false,
791                    n,
792                    reborrow_cache(&mut cache),
793                )
794                .expect("exp(reduced rem) cannot overflow (|rem| < B^-n)")
795                .mid;
796            let significand = repr.significand * exp_rem.repr.significand;
797            let repr = Repr::new(significand, exponent + exp_rem.repr.exponent);
798            self.repr_round(repr)
799        }
800    }
801}
802
803impl<const B: Word> Repr<B> {
804    // this method requires that the representation is already rounded to 24 binary bits
805    fn into_f32_internal(self) -> FpResult<f32> {
806        assert!(B == 2);
807        debug_assert!(self.is_finite());
808        debug_assert!(self.significand.bit_len() <= 24);
809
810        let sign = self.sign();
811        if self.is_neg_zero() {
812            // encode() would drop the sign of -0; preserve it exactly
813            return Ok(Exact(sign * 0f32));
814        }
815        let man24: i32 = self.significand.try_into().unwrap();
816        match f32::encode(man24, self.exponent as i16) {
817            Exact(v) => Ok(Exact(v)),
818            Inexact(v, _) if v.is_infinite() => Err(FpError::Overflow(sign)),
819            Inexact(0.0, _) => Err(FpError::Underflow(sign)),
820            Inexact(v, _) => Ok(Inexact(v, Rounding::NoOp)),
821        }
822    }
823
824    /// Convert the float number representation to a [f32] with the default IEEE 754 rounding mode.
825    ///
826    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
827    /// the float number with a specific rounding mode, please use [FBig::to_f32].
828    ///
829    /// # Examples
830    ///
831    /// ```
832    /// # use dashu_base::Approximation::*;
833    /// # use dashu_float::{Repr, round::Rounding::*};
834    /// assert_eq!(Repr::<2>::one().to_f32(), Exact(1.0));
835    /// assert_eq!(Repr::<10>::infinity().to_f32(), Inexact(f32::INFINITY, NoOp));
836    /// ```
837    #[inline]
838    pub fn to_f32(&self) -> Rounded<f32> {
839        match Context::<HalfEven>::convert_to_f32(self.clone()) {
840            Ok(rounded) => rounded,
841            Err(err) => f32_directed_endpoint::<HalfEven>(err),
842        }
843    }
844
845    // this method requires that the representation is already rounded to 53 binary bits
846    fn into_f64_internal(self) -> FpResult<f64> {
847        assert!(B == 2);
848        debug_assert!(self.is_finite());
849        debug_assert!(self.significand.bit_len() <= 53);
850
851        let sign = self.sign();
852        if self.is_neg_zero() {
853            // encode() would drop the sign of -0; preserve it exactly
854            return Ok(Exact(sign * 0f64));
855        }
856        let man53: i64 = self.significand.try_into().unwrap();
857        match f64::encode(man53, self.exponent as i16) {
858            Exact(v) => Ok(Exact(v)),
859            Inexact(v, _) if v.is_infinite() => Err(FpError::Overflow(sign)),
860            Inexact(0.0, _) => Err(FpError::Underflow(sign)),
861            Inexact(v, _) => Ok(Inexact(v, Rounding::NoOp)),
862        }
863    }
864
865    /// Convert the float number representation to a [f64] with the default IEEE 754 rounding mode.
866    ///
867    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
868    /// the float number with a specific rounding mode, please use [FBig::to_f64].
869    ///
870    /// # Examples
871    ///
872    /// ```
873    /// # use dashu_base::Approximation::*;
874    /// # use dashu_float::{Repr, round::Rounding::*};
875    /// assert_eq!(Repr::<2>::one().to_f64(), Exact(1.0));
876    /// assert_eq!(Repr::<10>::infinity().to_f64(), Inexact(f64::INFINITY, NoOp));
877    /// ```
878    #[inline]
879    pub fn to_f64(&self) -> Rounded<f64> {
880        match Context::<HalfEven>::convert_to_f64(self.clone()) {
881            Ok(rounded) => rounded,
882            Err(err) => f64_directed_endpoint::<HalfEven>(err),
883        }
884    }
885
886    /// Convert the float number representation to a [IBig].
887    ///
888    /// The fractional part is always rounded to zero. To convert with other rounding modes,
889    /// please use [FBig::to_int()].
890    ///
891    /// # Warning
892    ///
893    /// If the float number has a very large exponent, it will be evaluated and result
894    /// in allocating an huge integer and it might eat up all your memory.
895    ///
896    /// To get a rough idea of how big the number is, it's recommended to use [EstimatedLog2].
897    ///
898    /// # Examples
899    ///
900    /// ```
901    /// # use dashu_base::Approximation::*;
902    /// # use dashu_int::IBig;
903    /// # use dashu_float::{Repr, round::Rounding::*};
904    /// assert_eq!(Repr::<2>::neg_one().to_int(), Exact(IBig::NEG_ONE));
905    /// ```
906    ///
907    /// # Panics
908    ///
909    /// Panics if the number is infinte.
910    pub fn to_int(&self) -> Rounded<IBig> {
911        assert_finite(self);
912
913        if self.exponent >= 0 {
914            // the number is already an integer
915            Exact(shl_digits::<B>(&self.significand, self.exponent as usize))
916        } else if self.smaller_than_one() {
917            // the number is definitely smaller than
918            Inexact(IBig::ZERO, Rounding::NoOp)
919        } else {
920            let int = shr_digits::<B>(&self.significand, (-self.exponent) as usize);
921            Inexact(int, Rounding::NoOp)
922        }
923    }
924}
925
926impl<const B: Word> From<UBig> for Repr<B> {
927    #[inline]
928    fn from(n: UBig) -> Self {
929        Self::new(n.into(), 0)
930    }
931}
932impl<R: Round, const B: Word> From<UBig> for FBig<R, B> {
933    #[inline]
934    fn from(n: UBig) -> Self {
935        Self::from_parts(n.into(), 0)
936    }
937}
938
939impl<const B: Word> From<IBig> for Repr<B> {
940    #[inline]
941    fn from(n: IBig) -> Self {
942        Self::new(n, 0)
943    }
944}
945impl<R: Round, const B: Word> From<IBig> for FBig<R, B> {
946    #[inline]
947    fn from(n: IBig) -> Self {
948        Self::from_parts(n, 0)
949    }
950}
951
952impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for IBig {
953    type Error = ConversionError;
954
955    #[inline]
956    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
957        if value.repr.is_infinite() {
958            Err(ConversionError::OutOfBounds)
959        } else if value.repr.significand.is_zero() {
960            // A zero significand is integer zero regardless of exponent. This also
961            // accepts IEEE-754 signed zero, whose sign is carried by a -1 exponent
962            // sentinel (not the significand); it is treated as plain 0. The zero
963            // must be handled here rather than in the `else` branch below, which
964            // shifts by `exponent as usize` and would underflow on the -1 sentinel.
965            Ok(value.repr.significand)
966        } else if value.repr.exponent < 0 {
967            Err(ConversionError::LossOfPrecision)
968        } else {
969            let mut int = value.repr.significand;
970            shl_digits_in_place::<B>(&mut int, value.repr.exponent as usize);
971            Ok(int)
972        }
973    }
974}
975
976impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for UBig {
977    type Error = ConversionError;
978
979    #[inline]
980    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
981        let int: IBig = value.try_into()?;
982        int.try_into()
983    }
984}
985
986macro_rules! fbig_unsigned_conversions {
987    ($($t:ty)*) => {$(
988        impl<const B: Word> From<$t> for Repr<B> {
989            #[inline]
990            fn from(value: $t) -> Repr<B> {
991                UBig::from(value).into()
992            }
993        }
994        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
995            #[inline]
996            fn from(value: $t) -> FBig<R, B> {
997                UBig::from(value).into()
998            }
999        }
1000
1001        impl<const B: Word> TryFrom<Repr<B>> for $t {
1002            type Error = ConversionError;
1003
1004            fn try_from(value: Repr<B>) -> Result<Self, Self::Error> {
1005                if value.sign() == Sign::Negative || value.is_infinite() {
1006                    Err(ConversionError::OutOfBounds)
1007                } else {
1008                    let (log2_lb, _) = value.log2_bounds();
1009                    if log2_lb >= <$t>::BITS as f32 {
1010                        Err(ConversionError::OutOfBounds)
1011                    } else if value.exponent < 0 {
1012                        Err(ConversionError::LossOfPrecision)
1013                    } else {
1014                        shl_digits::<B>(&value.significand, value.exponent as usize).try_into()
1015                    }
1016                }
1017            }
1018        }
1019        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
1020            type Error = ConversionError;
1021
1022            #[inline]
1023            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
1024                value.repr.try_into()
1025            }
1026        }
1027    )*};
1028}
1029fbig_unsigned_conversions!(u8 u16 u32 u64 u128 usize);
1030
1031macro_rules! fbig_signed_conversions {
1032    ($($t:ty)*) => {$(
1033        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
1034            #[inline]
1035            fn from(value: $t) -> FBig<R, B> {
1036                IBig::from(value).into()
1037            }
1038        }
1039
1040        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
1041            type Error = ConversionError;
1042
1043            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
1044                if value.repr.is_infinite() {
1045                    Err(ConversionError::OutOfBounds)
1046                } else {
1047                    let (log2_lb, _) = value.repr.log2_bounds();
1048                    if log2_lb >= <$t>::BITS as f32 {
1049                        Err(ConversionError::OutOfBounds)
1050                    } else if value.repr.exponent < 0 {
1051                        Err(ConversionError::LossOfPrecision)
1052                    } else {
1053                        shl_digits::<B>(&value.repr.significand, value.repr.exponent as usize).try_into()
1054                    }
1055                }
1056            }
1057        }
1058    )*};
1059}
1060fbig_signed_conversions!(i8 i16 i32 i64 i128 isize);
1061
1062// The directed saturation endpoint for an out-of-range f32/f64 result, chosen from the `FpError`
1063// returned by `into_f*_internal`. Overflow saturates to ±MAX or ±∞ per the mode (outward modes
1064// reach ±∞; toward-zero/opposite/nearest saturate to the largest finite); underflow saturates to
1065// ±0 or the smallest subnormal of that sign. `round_low_part`'s AddOne/SubOne verdict on a
1066// same-sign residual is exactly the outward-vs-inward decision; only its directional verdict is
1067// used. This is the single place that picks the endpoint, shared by `to_f32`/`to_f64` (Repr uses
1068// HalfEven, FBig uses its own mode).
1069macro_rules! impl_float_directed_endpoint {
1070    (
1071        $fn:ident, $t:ty, $max:expr, $min:expr, $inf:expr, $neg_inf:expr,
1072        $smallest_sub:expr, $neg_smallest_sub:expr
1073    ) => {
1074        fn $fn<R: Round>(err: FpError) -> Rounded<$t> {
1075            match err {
1076                FpError::Overflow(sign) => {
1077                    let adj = if sign == Sign::Positive {
1078                        R::round_low_part(&IBig::ONE, Sign::Positive, || {
1079                            core::cmp::Ordering::Greater
1080                        })
1081                    } else {
1082                        R::round_low_part(&IBig::NEG_ONE, Sign::Negative, || {
1083                            core::cmp::Ordering::Greater
1084                        })
1085                    };
1086                    Inexact(
1087                        match (sign, adj) {
1088                            (Sign::Positive, AddOne) => $inf,
1089                            (Sign::Positive, _) => $max,
1090                            (Sign::Negative, SubOne) => $neg_inf,
1091                            (Sign::Negative, _) => $min,
1092                        },
1093                        adj,
1094                    )
1095                }
1096                FpError::Underflow(sign) => {
1097                    let adj = if sign == Sign::Positive {
1098                        R::round_low_part(&IBig::ZERO, Sign::Positive, || core::cmp::Ordering::Less)
1099                    } else {
1100                        R::round_low_part(&IBig::ZERO, Sign::Negative, || core::cmp::Ordering::Less)
1101                    };
1102                    Inexact(
1103                        match (sign, adj) {
1104                            (Sign::Positive, AddOne) => $smallest_sub, // smallest positive subnormal
1105                            (Sign::Positive, _) => 0.0,
1106                            (Sign::Negative, SubOne) => $neg_smallest_sub,
1107                            (Sign::Negative, _) => -0.0,
1108                        },
1109                        adj,
1110                    )
1111                }
1112                // `into_f*_internal` only returns Overflow/Underflow; the infinite-input case is
1113                // handled by `convert_to_f*` (returning `Ok`) before this is reached.
1114                _ => unreachable!("convert_to_f* only returns Overflow/Underflow here"),
1115            }
1116        }
1117    };
1118}
1119impl_float_directed_endpoint!(
1120    f32_directed_endpoint,
1121    f32,
1122    f32::MAX,
1123    f32::MIN,
1124    f32::INFINITY,
1125    f32::NEG_INFINITY,
1126    f32::from_bits(1),
1127    f32::from_bits(0x8000_0001)
1128);
1129impl_float_directed_endpoint!(
1130    f64_directed_endpoint,
1131    f64,
1132    f64::MAX,
1133    f64::MIN,
1134    f64::INFINITY,
1135    f64::NEG_INFINITY,
1136    f64::from_bits(1),
1137    f64::from_bits(0x8000_0000_0000_0001)
1138);
1139
1140macro_rules! impl_from_fbig_for_float {
1141    ($t:ty, $convert:ident) => {
1142        impl TryFrom<Repr<2>> for $t {
1143            type Error = ConversionError;
1144
1145            #[inline]
1146            fn try_from(value: Repr<2>) -> Result<Self, Self::Error> {
1147                if value.is_infinite() {
1148                    return Err(ConversionError::LossOfPrecision);
1149                }
1150                // Range detection is shared with `to_f32`/`to_f64` via `convert_to_f*`: it returns
1151                // `Err(Overflow)` for a value beyond the largest finite `$t`, so `OutOfBounds` is
1152                // reported the same way under every rounding mode (Repr uses HalfEven here).
1153                match Context::<HalfEven>::$convert(value) {
1154                    Ok(Exact(v)) => Ok(v),
1155                    Ok(Inexact(_, _)) => Err(ConversionError::LossOfPrecision),
1156                    Err(FpError::Overflow(_)) => Err(ConversionError::OutOfBounds),
1157                    Err(FpError::Underflow(_)) => Err(ConversionError::LossOfPrecision),
1158                    Err(_) => unreachable!(),
1159                }
1160            }
1161        }
1162
1163        impl<R: Round> TryFrom<FBig<R, 2>> for $t {
1164            type Error = ConversionError;
1165
1166            #[inline]
1167            fn try_from(value: FBig<R, 2>) -> Result<Self, Self::Error> {
1168                if value.repr.is_infinite() {
1169                    return Err(ConversionError::LossOfPrecision);
1170                }
1171                // A value beyond the largest finite `$t` is out of range whatever the rounding mode:
1172                // the mode only selects the saturation endpoint (±MAX vs ±∞), and `convert_to_f*`
1173                // reports that range condition as `Err(Overflow)` regardless of mode — so
1174                // `Err(OutOfBounds)` reliably means "beyond the finite range", unlike the old
1175                // result-infiniteness check (which flipped LossOfPrecision/OutOfBounds with the mode).
1176                match Context::<R>::$convert(value.repr) {
1177                    Ok(Exact(v)) => Ok(v),
1178                    Ok(Inexact(_, _)) => Err(ConversionError::LossOfPrecision),
1179                    Err(FpError::Overflow(_)) => Err(ConversionError::OutOfBounds),
1180                    Err(FpError::Underflow(_)) => Err(ConversionError::LossOfPrecision),
1181                    Err(_) => unreachable!(),
1182                }
1183            }
1184        }
1185    };
1186}
1187impl_from_fbig_for_float!(f32, convert_to_f32);
1188impl_from_fbig_for_float!(f64, convert_to_f64);
1189
1190#[cfg(test)]
1191mod tests {
1192    use super::*;
1193    use crate::repr::Repr;
1194
1195    // Directed overflow must reach the endpoint for a value whose *most*-significant bit straddles
1196    // f32::MAX (not only for values whose lsb exponent is ≥ 128). `3·2¹²⁷` ≈ 1.5·2¹²⁸ overflows
1197    // f32::MAX = (2 − 2⁻²³)·2¹²⁷, yet its lsb exponent is 127 — the old exponent-gated branch fell
1198    // through to `encode`, which saturates to ±∞ mode-blindly.
1199    #[test]
1200    fn f32_directed_overflow_at_msb_boundary() {
1201        use crate::round::mode::{Down, Up};
1202        // f32: 3·2^127 under Zero/Down -> f32::MAX, under Up/Away -> +∞.
1203        let zero = FBig::<Zero, 2>::from_parts(3.into(), 127);
1204        let down = FBig::<Down, 2>::from_parts(3.into(), 127);
1205        let up = FBig::<Up, 2>::from_parts(3.into(), 127);
1206        assert_eq!(zero.to_f32().value().to_bits(), 0x7f7fffff); // f32::MAX
1207        assert_eq!(down.to_f32().value().to_bits(), 0x7f7fffff);
1208        assert!(up.to_f32().value().is_infinite() && up.to_f32().value().is_sign_positive());
1209        // negative mirror
1210        let nzero = FBig::<Zero, 2>::from_parts((-3).into(), 127);
1211        assert_eq!(nzero.to_f32().value().to_bits(), 0xff7fffff); // f32::MIN
1212
1213        // f64: 3·2^1023 overflows f64::MAX; lsb exponent 1023 < 1024.
1214        let z64 = FBig::<Zero, 2>::from_parts(3.into(), 1023);
1215        assert_eq!(z64.to_f64().value().to_bits(), 0x7fefffffffffffff); // f64::MAX
1216        let u64 = FBig::<Up, 2>::from_parts(3.into(), 1023);
1217        assert!(u64.to_f64().value().is_infinite() && u64.to_f64().value().is_sign_positive());
1218    }
1219
1220    // Directed underflow must reach the endpoint through the `encode` path too (not only for the
1221    // extreme exponents caught by the old explicit branch). `2⁻¹⁶⁰` is below the smallest subnormal;
1222    // under Up a positive value must round up to `2⁻¹⁴⁹`, but `encode` returns ±0 mode-blindly.
1223    #[test]
1224    fn f32_directed_underflow_through_encode() {
1225        use crate::round::mode::{Away, Down, Up};
1226        // f32: 2^-160 under Up/Away -> smallest +subnormal, under Zero/Down -> +0.
1227        let up = FBig::<Up, 2>::from_parts(IBig::ONE, -160);
1228        let away = FBig::<Away, 2>::from_parts(IBig::ONE, -160);
1229        let zero = FBig::<Zero, 2>::from_parts(IBig::ONE, -160);
1230        let down = FBig::<Down, 2>::from_parts(IBig::ONE, -160);
1231        assert_eq!(up.to_f32().value().to_bits(), 0x00000001); // smallest +subnormal
1232        assert_eq!(away.to_f32().value().to_bits(), 0x00000001);
1233        assert_eq!(zero.to_f32().value().to_bits(), 0x0);
1234        assert_eq!(down.to_f32().value().to_bits(), 0x0);
1235        // negative: Down/Away -> smallest -subnormal, Zero/Up -> -0.
1236        let ndown = FBig::<Down, 2>::from_parts(-IBig::ONE, -160);
1237        assert_eq!(ndown.to_f32().value().to_bits(), 0x80000001);
1238
1239        // f64: 2^-1100 under Up -> smallest +subnormal.
1240        let u64 = FBig::<Up, 2>::from_parts(IBig::ONE, -1100);
1241        assert_eq!(u64.to_f64().value().to_bits(), 0x0000_0000_0000_0001);
1242    }
1243
1244    // A decimal FBig whose value exceeds f32::MAX must saturate to the largest *finite* f32 under
1245    // toward-zero (Zero), not +∞ — directed overflow picks the endpoint per mode.
1246    #[test]
1247    fn f32_overflow_saturates_to_max_under_toward_zero() {
1248        use crate::round::mode::Up;
1249        // value ≈ 1.8e67 ≫ f32::MAX
1250        let sig: IBig = "18113714167384154970503568309331051197800435559900844351020490293248000000000000000000000000000000000000000000000000000000000000000000000040081793412673420422647135518538018600544982168035325793404432580816367361955984101780462905766719198411690240".parse().unwrap();
1251        let down = FBig::<Zero, 10>::from_parts(sig.clone(), -180);
1252        assert_eq!(down.to_f32().value().to_bits(), 0x7f7fffff); // f32::MAX, not +∞
1253                                                                 // The same value toward +∞ does reach +∞.
1254        let up = FBig::<Up, 10>::from_parts(sig, -180);
1255        assert!(up.to_f32().value().is_infinite());
1256    }
1257
1258    // A wide decimal significand near an f32 subnormal midpoint must round to the correct
1259    // neighbor. The near-correct base-conversion logarithm previously landed on the wrong side of a
1260    // 32-bit midpoint, producing a result 1 ULP off (0x00040008 instead of 0x00040007).
1261    #[test]
1262    fn f32_decimal_subnormal_rounds_correctly() {
1263        let v = FBig::<HalfEven, 10>::from_parts(
1264            "367352494370447282365772889742681992006459962834329374643515088008836389924495676300982092025765783512749250624297822169761305238359955010699895018824154119671"
1265                .parse()
1266                .unwrap(),
1267            -198,
1268        );
1269        assert_eq!(v.to_f32().value().to_bits(), 0x00040007);
1270    }
1271
1272    // A positive value below the smallest subnormal must round *up* to that smallest subnormal
1273    // under Up/Away (and to ±0 under toward-zero/opposite/nearest) — the underflow path used to
1274    // return a mode-blind signed zero, which is not an upper bound for a positive value under Up.
1275    #[test]
1276    fn f64_directed_underflow_below_smallest_subnormal() {
1277        use crate::round::mode::Down;
1278        // tiny positive binary value, far below 2^-1074
1279        let up = FBig::<crate::round::mode::Up, 2>::from_parts(IBig::ONE, -20000);
1280        let away = FBig::<crate::round::mode::Away, 2>::from_parts(IBig::ONE, -20000);
1281        let zero = FBig::<Zero, 2>::from_parts(IBig::ONE, -20000);
1282        let down = FBig::<Down, 2>::from_parts(IBig::ONE, -20000);
1283        assert_eq!(up.to_f64().value().to_bits(), 0x0000_0000_0000_0001); // smallest +subnormal
1284        assert_eq!(away.to_f64().value().to_bits(), 0x0000_0000_0000_0001);
1285        assert_eq!(zero.to_f64().value().to_bits(), 0x0); // +0
1286        assert_eq!(down.to_f64().value().to_bits(), 0x0);
1287
1288        // tiny negative: Down/Away -> smallest -subnormal, Zero/Up -> -0
1289        let ndown = FBig::<Down, 2>::from_parts(-IBig::ONE, -20000);
1290        let nup = FBig::<crate::round::mode::Up, 2>::from_parts(-IBig::ONE, -20000);
1291        assert_eq!(ndown.to_f64().value().to_bits(), 0x8000_0000_0000_0001); // smallest -subnormal
1292        assert_eq!(nup.to_f64().value().to_bits(), 0x8000_0000_0000_0000); // -0
1293    }
1294
1295    // A wide-significand *decimal* value far below ½·MIN_SUBNORMAL (exponent −20000). The base
1296    // conversion's internal `exp` underflows for such a catastrophically tiny value, so without the
1297    // source-`log2_bounds` short-circuit the converted magnitude is wrong and `to_f64` returned a
1298    // spurious finite subnormal (≈2^-593) instead of the directed underflow endpoint. The binary
1299    // test above doesn't hit this — it skips base conversion entirely.
1300    #[test]
1301    fn f64_decimal_wide_significand_underflow() {
1302        use crate::round::mode::{Down, Up};
1303        let wide = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
1304            .parse::<IBig>()
1305            .unwrap();
1306        for prec in [20usize, 50, 100, 500] {
1307            let he = FBig::<HalfEven, 10>::from_parts(wide.clone(), -20000)
1308                .with_precision(prec)
1309                .value();
1310            let up = FBig::<Up, 10>::from_parts(wide.clone(), -20000)
1311                .with_precision(prec)
1312                .value();
1313            let dn = FBig::<Down, 10>::from_parts(wide.clone(), -20000)
1314                .with_precision(prec)
1315                .value();
1316            // positive value: nearest/Down -> +0, Up -> smallest positive subnormal
1317            assert_eq!(he.to_f64().value().to_bits(), 0x0, "HalfEven @ prec {prec}");
1318            assert_eq!(dn.to_f64().value().to_bits(), 0x0, "Down @ prec {prec}");
1319            assert_eq!(up.to_f64().value().to_bits(), 0x0000_0000_0000_0001, "Up @ prec {prec}");
1320            // f32 mirror: |x| < 2^-150 = ½·MIN_SUBNORMAL -> +0 / smallest +subnormal
1321            assert_eq!(he.to_f32().value().to_bits(), 0x0u32, "f32 HalfEven @ prec {prec}");
1322            assert_eq!(up.to_f32().value().to_bits(), 0x0000_0001u32, "f32 Up @ prec {prec}");
1323
1324            // negative value: nearest/Up -> -0, Down -> smallest negative subnormal
1325            let neg = FBig::<HalfEven, 10>::from_parts(-wide.clone(), -20000)
1326                .with_precision(prec)
1327                .value();
1328            let ndn = FBig::<Down, 10>::from_parts(-wide.clone(), -20000)
1329                .with_precision(prec)
1330                .value();
1331            assert_eq!(
1332                neg.to_f64().value().to_bits(),
1333                0x8000_0000_0000_0000,
1334                "neg HalfEven @ prec {prec}"
1335            );
1336            assert_eq!(
1337                ndn.to_f64().value().to_bits(),
1338                0x8000_0000_0000_0001,
1339                "neg Down @ prec {prec}"
1340            );
1341        }
1342    }
1343
1344    #[test]
1345    fn ibig_try_from_accepts_signed_zero() {
1346        // IEEE-754 signed zero (sign encoded in a -1 exponent sentinel) is plain 0.
1347        let neg_zero = FBig::<HalfAway, 10>::new(Repr::neg_zero(), Context::new(8));
1348        assert_eq!(IBig::try_from(neg_zero), Ok(IBig::from(0)));
1349
1350        // positive zero already worked, and still does
1351        let pos_zero = FBig::<HalfAway, 10>::new(Repr::zero(), Context::new(8));
1352        assert_eq!(IBig::try_from(pos_zero), Ok(IBig::from(0)));
1353
1354        // UBig delegates to the IBig impl, so it accepts signed zero too
1355        let neg_zero = FBig::<HalfAway, 2>::new(Repr::neg_zero(), Context::new(8));
1356        assert_eq!(UBig::try_from(neg_zero), Ok(UBig::from(0u8)));
1357
1358        // a genuine fractional value must still be rejected
1359        let frac = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(1), -1), Context::new(8));
1360        assert_eq!(IBig::try_from(frac), Err(ConversionError::LossOfPrecision));
1361
1362        // a normal integer round-trips exactly
1363        let int_val = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(42), 0), Context::new(8));
1364        assert_eq!(IBig::try_from(int_val), Ok(IBig::from(42)));
1365    }
1366
1367    #[test]
1368    fn with_base_high_precision_no_overflow() {
1369        // Regression for issue #95: converting a high-precision base-2 float to base
1370        // 10 panicked on 32-bit targets ("arithmetic operations with the infinity are
1371        // not allowed!"). The base conversion evaluates exp(r) as `sum^(B^n)` through
1372        // `powi` with a huge exponent (B^n) on a base (sum) very close to 1; `powi`'s
1373        // overflow guard estimated log2(base) with the catastrophically-canceling
1374        // `log2_est`, and the ~1e-4 of f32 noise scaled by the exponent crossed the
1375        // (much smaller on 32-bit) isize threshold, yielding a spurious ±inf that then
1376        // panicked when shifted. See `powi` in exp.rs for the fix.
1377        use crate::round::mode::Zero;
1378        use core::str::FromStr;
1379
1380        // The reporter's input: -1.1111…0011 in binary (578 significant bits), written
1381        // in the hex form dashu accepts for base-2 floats (`0x1.<hex>…`). The value is
1382        // identical to the raw binary literal.
1383        let num = FBig::<Zero, 2>::from_str(
1384            "-0x1.fffdc8d645194a5a95df4be063472d4406dd096339dd7dc2a8527d208b3da7b9e5c36b4f49a7982cb2ad20a4e7e4c016f858fe8cddea011a6d01fe3823189c4ed4f57a7babc331498",
1385        )
1386        .unwrap();
1387
1388        // at the original 578-bit precision the conversion succeeds …
1389        let a = num
1390            .clone()
1391            .with_precision(578)
1392            .value()
1393            .with_base::<10>()
1394            .value();
1395        assert!(a.repr().is_finite());
1396        // … and so does a slightly higher precision (586), which panicked on 32-bit
1397        // (wasm32 / i686). The result matches the value computed on 64-bit. Compared
1398        // by value (FBig equality ignores context) rather than via string formatting,
1399        // so this works under no_std too.
1400        let b = num.with_precision(586).value().with_base::<10>().value();
1401        assert!(b.repr().is_finite());
1402        let expected = FBig::<Zero, 10>::from_str(
1403            "-1.9999661944503703041843468850635057967553124154072485151176192294480158424234268438137612977886891381228704640656094986435381057574477216648567249609280392009533217665484389886",
1404        )
1405        .unwrap();
1406        assert_eq!(b, expected);
1407    }
1408}