1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use core::cmp::Ordering;

use dashu_base::{
    Approximation::{self, *},
    BitTest, ConversionError, DivRem, FloatEncoding, PowerOfTwo, Sign, UnsignedAbs,
};
use dashu_int::{IBig, UBig};

use crate::{
    rbig::{RBig, Relaxed},
    repr::Repr,
};

impl From<UBig> for Repr {
    #[inline]
    fn from(v: UBig) -> Self {
        Repr {
            numerator: v.into(),
            denominator: UBig::ONE,
        }
    }
}

impl From<IBig> for Repr {
    #[inline]
    fn from(v: IBig) -> Self {
        Repr {
            numerator: v,
            denominator: UBig::ONE,
        }
    }
}

impl TryFrom<Repr> for UBig {
    type Error = ConversionError;
    #[inline]
    fn try_from(value: Repr) -> Result<Self, Self::Error> {
        let (sign, mag) = value.numerator.into_parts();
        if sign == Sign::Negative {
            Err(ConversionError::OutOfBounds)
        } else if mag.is_one() {
            Ok(mag)
        } else {
            Err(ConversionError::LossOfPrecision)
        }
    }
}

impl TryFrom<Repr> for IBig {
    type Error = ConversionError;
    #[inline]
    fn try_from(value: Repr) -> Result<Self, Self::Error> {
        if value.denominator.is_one() {
            Ok(value.numerator)
        } else {
            Err(ConversionError::LossOfPrecision)
        }
    }
}

macro_rules! forward_conversion_to_repr {
    ($from:ty => $t:ident) => {
        impl From<$from> for $t {
            #[inline]
            fn from(v: $from) -> Self {
                $t(Repr::from(v))
            }
        }
        impl TryFrom<$t> for $from {
            type Error = ConversionError;
            #[inline]
            fn try_from(value: $t) -> Result<Self, Self::Error> {
                Self::try_from(value.0)
            }
        }
    };
}
forward_conversion_to_repr!(UBig => RBig);
forward_conversion_to_repr!(IBig => RBig);
forward_conversion_to_repr!(UBig => Relaxed);
forward_conversion_to_repr!(IBig => Relaxed);

macro_rules! impl_conversion_for_prim_ints {
    ($($t:ty)*) => {$(
        impl From<$t> for Repr {
            #[inline]
            fn from(v: $t) -> Repr {
                Repr {
                    numerator: v.into(),
                    denominator: UBig::ONE
                }
            }
        }

        impl TryFrom<Repr> for $t {
            type Error = ConversionError;
            #[inline]
            fn try_from(value: Repr) -> Result<Self, Self::Error> {
                let int: IBig = value.try_into()?;
                int.try_into()
            }
        }

        forward_conversion_to_repr!($t => RBig);
        forward_conversion_to_repr!($t => Relaxed);
    )*};
}
impl_conversion_for_prim_ints!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);

macro_rules! impl_conversion_from_float {
    ($t:ty) => {
        impl TryFrom<$t> for Repr {
            type Error = ConversionError;

            fn try_from(value: $t) -> Result<Self, Self::Error> {
                // shortcut to prevent issues in counting leading zeros
                if value == 0. {
                    return Ok(Repr::zero());
                }

                match value.decode() {
                    Ok((man, exp)) => {
                        // here we don't remove the common factor 2, because we need exact
                        // exponent value in some cases (like approx_f32 and approx_f64)
                        let repr = if exp >= 0 {
                            Repr {
                                numerator: IBig::from(man) << exp as usize,
                                denominator: UBig::ONE,
                            }
                        } else {
                            let mut denominator = UBig::ZERO;
                            denominator.set_bit((-exp) as _);
                            Repr {
                                numerator: IBig::from(man),
                                denominator,
                            }
                        };
                        Ok(repr)
                    }
                    Err(_) => Err(ConversionError::OutOfBounds),
                }
            }
        }

        impl TryFrom<$t> for RBig {
            type Error = ConversionError;
            #[inline]
            fn try_from(value: $t) -> Result<Self, Self::Error> {
                Repr::try_from(value).map(|repr| RBig(repr.reduce2()))
            }
        }
        impl TryFrom<$t> for Relaxed {
            type Error = ConversionError;
            #[inline]
            fn try_from(value: $t) -> Result<Self, Self::Error> {
                Repr::try_from(value).map(|repr| Relaxed(repr.reduce2()))
            }
        }
    };
}
impl_conversion_from_float!(f32);
impl_conversion_from_float!(f64);

macro_rules! impl_conversion_to_float {
    ($t:ty [$lb:literal, $ub:literal]) => {
        impl TryFrom<RBig> for $t {
            type Error = ConversionError;

            /// Convert RBig to primitive floats. It returns [Ok] only if
            /// the conversion can be done losslessly
            fn try_from(value: RBig) -> Result<Self, Self::Error> {
                if value.0.numerator.is_zero() {
                    Ok(0.)
                } else if value.0.denominator.is_power_of_two() {
                    // conversion is exact only if the denominator is a power of two
                    let num_bits = value.0.numerator.bit_len();
                    let den_bits = value.0.denominator.trailing_zeros().unwrap();
                    let top_bit = num_bits as isize - den_bits as isize;
                    if top_bit > $ub {
                        // see to_f32::encode for explanation of the bounds
                        Err(ConversionError::OutOfBounds)
                    } else if top_bit < $lb {
                        Err(ConversionError::LossOfPrecision)
                    } else {
                        match <$t>::encode(
                            value.0.numerator.try_into().unwrap(),
                            -(den_bits as i16),
                        ) {
                            Exact(v) => Ok(v),
                            Inexact(v, _) => {
                                if v.is_infinite() {
                                    Err(ConversionError::OutOfBounds)
                                } else {
                                    Err(ConversionError::LossOfPrecision)
                                }
                            }
                        }
                    }
                } else {
                    Err(ConversionError::LossOfPrecision)
                }
            }
        }

        impl TryFrom<Relaxed> for $t {
            type Error = ConversionError;

            #[inline]
            fn try_from(value: Relaxed) -> Result<Self, Self::Error> {
                // convert to RBig to eliminate cofactors
                <$t>::try_from(value.canonicalize())
            }
        }
    };
}
impl_conversion_to_float!(f32 [-149, 128]); // see f32::encode for explanation of the bounds
impl_conversion_to_float!(f64 [-1074, 1024]); // see f32::encode for explanation of the bounds

impl Repr {
    /// Convert the rational number to [f32] without guaranteed correct rounding.
    fn to_f32_fast(&self) -> f32 {
        // shortcut
        if self.numerator.is_zero() {
            return 0.;
        }

        // to get enough precision (24 bits), we need to do a 48 by 24 bit division
        let sign = self.numerator.sign();
        let num_bits = self.numerator.bit_len();
        let den_bits = self.denominator.bit_len();

        let num_shift = num_bits as isize - 48;
        let num48: i64 = if num_shift >= 0 {
            (&self.numerator) >> num_shift as usize
        } else {
            (&self.numerator) << (-num_shift) as usize
        }
        .try_into()
        .unwrap();

        let den_shift = den_bits as isize - 24;
        let den24: u32 = if den_shift >= 0 {
            (&self.denominator) >> den_shift as usize
        } else {
            (&self.denominator) << (-den_shift) as usize
        }
        .try_into()
        .unwrap();

        // determine the exponent
        let exponent = num_shift - den_shift;
        if exponent >= 128 {
            // max f32 = 2^128 * (1 - 2^-24)
            sign * f32::INFINITY
        } else if exponent < -149 - 25 {
            // min f32 = 2^-149, quotient has at most 25 bits
            sign * 0f32
        } else {
            let (mut man, r) = num48.unsigned_abs().div_rem(den24 as u64);

            // round to nearest, ties to even
            let half = (r as u32 * 2).cmp(&den24);
            if half == Ordering::Greater || (half == Ordering::Equal && man & 1 > 0) {
                man += 1;
            }
            f32::encode(sign * man as i32, exponent as i16).value()
        }
    }

    fn to_f64_fast(&self) -> f64 {
        // shortcut
        if self.numerator.is_zero() {
            return 0.;
        }

        // to get enough precision (53 bits), we need to do a 106 by 53 bit division
        let sign = self.numerator.sign();
        let num_bits = self.numerator.bit_len();
        let den_bits = self.denominator.bit_len();

        let num_shift = num_bits as isize - 106;
        let num106: i128 = if num_shift >= 0 {
            (&self.numerator) >> num_shift as usize
        } else {
            (&self.numerator) << (-num_shift) as usize
        }
        .try_into()
        .unwrap();

        let den_shift = den_bits as isize - 53;
        let den53: u64 = if den_shift >= 0 {
            (&self.denominator) >> den_shift as usize
        } else {
            (&self.denominator) << (-den_shift) as usize
        }
        .try_into()
        .unwrap();

        // determine the exponent
        let exponent = num_shift - den_shift;
        if exponent >= 1024 {
            // max f64 = 2^1024 × (1 − 2^−53)
            sign * f64::INFINITY
        } else if exponent < -1074 - 54 {
            // min f64 = 2^-1074, quotient has at most 54 bits
            sign * 0f64
        } else {
            let (mut man, r) = num106.unsigned_abs().div_rem(den53 as u128);

            // round to nearest, ties to even
            let half = (r as u64 * 2).cmp(&den53);
            if half == Ordering::Greater || (half == Ordering::Equal && man & 1 > 0) {
                man += 1;
            }
            f64::encode(sign * man as i64, exponent as i16).value()
        }
    }

    /// Convert the rational number to [f32] with guaranteed correct rounding.
    fn to_f32(&self) -> Approximation<f32, Sign> {
        // shortcut
        if self.numerator.is_zero() {
            return Exact(0.);
        }

        // to get enough precision, shift such that numerator has
        // 24 bits more than the denominator
        let sign = self.numerator.sign();
        let num_bits = self.numerator.bit_len();
        let den_bits = self.denominator.bit_len();

        let shift = num_bits as isize - den_bits as isize - 24; // i.e. exponent
        let (num, den) = if shift >= 0 {
            (self.numerator.clone(), (&self.denominator) << shift as usize)
        } else {
            ((&self.numerator) << (-shift) as usize, self.denominator.clone())
        };

        // then construct the
        if shift >= 128 {
            // max f32 = 2^128 * (1 - 2^-24)
            Inexact(sign * f32::INFINITY, sign)
        } else if shift < -149 - 25 {
            // min f32 = 2^-149, quotient has at most 25 bits
            Inexact(sign * 0f32, -sign)
        } else {
            let (man, r) = num.unsigned_abs().div_rem(&den);
            let man: u32 = man.try_into().unwrap();

            // round to nearest, ties to even
            if r.is_zero() {
                Exact(man)
            } else {
                let half = (r << 1).cmp(&den);
                if half == Ordering::Greater || (half == Ordering::Equal && man & 1 > 0) {
                    Inexact(man + 1, sign)
                } else {
                    Inexact(man, -sign)
                }
            }
            .and_then(|man| f32::encode(sign * man as i32, shift as i16))
        }
    }

    fn to_f64(&self) -> Approximation<f64, Sign> {
        // shortcut
        if self.numerator.is_zero() {
            return Exact(0.);
        }

        // to get enough precision, shift such that numerator has
        // 53 bits more than the denominator
        let sign = self.numerator.sign();
        let num_bits = self.numerator.bit_len();
        let den_bits = self.denominator.bit_len();

        let shift = num_bits as isize - den_bits as isize - 53; // i.e. exponent
        let (num, den) = if shift >= 0 {
            (self.numerator.clone(), (&self.denominator) << shift as usize)
        } else {
            ((&self.numerator) << (-shift) as usize, self.denominator.clone())
        };

        // then construct the
        if shift >= 1024 {
            // max f64 = 2^1024 × (1 − 2^−53)
            Inexact(sign * f64::INFINITY, sign)
        } else if shift < -1074 - 53 {
            // min f64 = 2^-1074, quotient has at most 53 bits
            Inexact(sign * 0f64, -sign)
        } else {
            let (man, r) = num.unsigned_abs().div_rem(&den);
            let man: u64 = man.try_into().unwrap();

            // round to nearest, ties to even
            if r.is_zero() {
                Exact(man)
            } else {
                let half = (r << 1).cmp(&den);
                if half == Ordering::Greater || (half == Ordering::Equal && man & 1 > 0) {
                    Inexact(man + 1, sign)
                } else {
                    Inexact(man, -sign)
                }
            }
            .and_then(|man| f64::encode(sign * man as i64, shift as i16))
        }
    }
}

impl RBig {
    /// Convert the rational number to a [f32].
    ///
    /// The rounding follows the default IEEE 754 behavior (rounds to nearest,
    /// ties to even).
    ///
    /// The rounding will be correct at most of the time, but in rare cases the
    /// mantissa can be off by one bit. Use [RBig::to_f32_fast] for ensured correct
    /// rounding.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ONE.to_f32_fast(), 1f32);
    ///
    /// let r = RBig::from_parts(22.into(), 7u8.into());
    /// assert_eq!(r.to_f32_fast(), 22./7.)
    /// ```
    #[inline]
    pub fn to_f32_fast(&self) -> f32 {
        self.0.to_f32_fast()
    }

    /// Convert the rational number to a [f64].
    ///
    /// The rounding follows the default IEEE 754 behavior (rounds to nearest,
    /// ties to even).
    ///
    /// The rounding will be correct at most of the time, but in rare cases the
    /// mantissa can be off by one bit. Use [RBig::to_f32_fast] for ensured correct
    /// rounding.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ONE.to_f64_fast(), 1f64);
    ///
    /// let r = RBig::from_parts(22.into(), 7u8.into());
    /// assert_eq!(r.to_f64_fast(), 22./7.)
    /// ```
    #[inline]
    pub fn to_f64_fast(&self) -> f64 {
        self.0.to_f64_fast()
    }

    /// Convert the rational number to a [f32] with guaranteed correct rounding.
    ///
    /// The rounding follows the default IEEE 754 behavior (rounds to nearest,
    /// ties to even).
    ///
    /// Because of the guaranteed rounding, it might take a long time to convert
    /// when the numerator and denominator are large. In this case [RBig::to_f32_fast]
    /// can be used if the correct rounding is not required.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_base::{Approximation::*, Sign::*};
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ONE.to_f32(), Exact(1f32));
    ///
    /// let r = RBig::from_parts(22.into(), 7u8.into());
    /// // f32 representation of 22/7 is smaller than the actual 22/7
    /// assert_eq!(r.to_f32(), Inexact(22./7., Negative));
    /// ```
    #[inline]
    pub fn to_f32(&self) -> Approximation<f32, Sign> {
        self.0.to_f32()
    }

    /// Convert the rational number to a [f64] with guaranteed correct rounding.
    ///
    /// The rounding follows the default IEEE 754 behavior (rounds to nearest,
    /// ties to even).
    ///
    /// Because of the guaranteed rounding, it might take a long time to convert
    /// when the numerator and denominator are large. In this case [RBig::to_f32_fast]
    /// can be used if the correct rounding is not required.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_base::{Approximation::*, Sign::*};
    /// # use dashu_ratio::RBig;
    /// assert_eq!(RBig::ONE.to_f64(), Exact(1f64));
    ///
    /// let r = RBig::from_parts(22.into(), 7u8.into());
    /// // f64 representation of 22/7 is smaller than the actual 22/7
    /// assert_eq!(r.to_f64(), Inexact(22./7., Negative));
    /// ```
    #[inline]
    pub fn to_f64(&self) -> Approximation<f64, Sign> {
        self.0.to_f64()
    }

    /// Convert the rational number to an [IBig].
    ///
    /// The conversion rounds toward zero. It's equivalent to [RBig::trunc],
    /// but it returns the fractional part if the rational number is not an integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dashu_base::Approximation::*;
    /// # use dashu_int::{IBig, UBig};
    /// # use dashu_ratio::RBig;
    /// let a = RBig::from_parts(22.into(), UBig::ONE);
    /// assert_eq!(a.to_int(), Exact(IBig::from(22)));
    ///
    /// let b = RBig::from_parts(22.into(), 7u8.into());
    /// assert_eq!(b.to_int(), Inexact(
    ///     IBig::from(3), RBig::from_parts(1.into(), 7u8.into())
    /// ));
    /// ```
    #[inline]
    pub fn to_int(&self) -> Approximation<IBig, Self> {
        let (trunc, fract) = self.clone().split_at_point();
        if fract.is_zero() {
            Approximation::Exact(trunc)
        } else {
            Approximation::Inexact(trunc, fract)
        }
    }
}

impl Relaxed {
    /// Convert the rational number to a [f32].
    ///
    /// See [RBig::to_f32_fast] for details.
    #[inline]
    pub fn to_f32_fast(&self) -> f32 {
        self.0.to_f32_fast()
    }
    /// Convert the rational number to a [f64].
    ///
    /// See [RBig::to_f64_fast] for details.
    #[inline]
    pub fn to_f64_fast(&self) -> f64 {
        self.0.to_f64_fast()
    }

    /// Convert the rational number to a [f32] with guaranteed correct rounding.
    ///
    /// See [RBig::to_f32] for details.
    #[inline]
    pub fn to_f32(&self) -> Approximation<f32, Sign> {
        self.0.to_f32()
    }
    /// Convert the rational number to a [f64] with guaranteed correct rounding.
    ///
    /// See [RBig::to_f64] for details.
    #[inline]
    pub fn to_f64(&self) -> Approximation<f64, Sign> {
        self.0.to_f64()
    }
    /// Convert the rational number to am [IBig].
    ///
    /// See [RBig::to_int] for details.
    #[inline]
    pub fn to_int(&self) -> Approximation<IBig, Self> {
        let (trunc, fract) = self.clone().split_at_point();
        if fract.is_zero() {
            Approximation::Exact(trunc)
        } else {
            Approximation::Inexact(trunc, fract)
        }
    }
}