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