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
// Copyright © 2024 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.

use crate::Rational;
use core::cmp::Ordering;
use malachite_base::num::arithmetic::traits::{
    DivRound, DivisibleByPowerOf2, IsPowerOf2, NegAssign,
};
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::conversion::traits::{
    ConvertibleFrom, ExactFrom, RawMantissaAndExponent, RoundingFrom, SciMantissaAndExponent,
    WrappingFrom,
};
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_base::rounding_modes::RoundingMode;

fn abs_is_neg_power_of_2(x: &Rational) -> bool {
    x.numerator == 1u32 && x.denominator.is_power_of_2()
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FloatFromRationalError;

macro_rules! float_impls {
    ($f: ident) => {
        impl RoundingFrom<Rational> for $f {
            /// Converts a [`Rational`] to a value of a primitive float according to a specified
            /// [`RoundingMode`], taking the [`Rational`] by value.
            ///
            /// - If the rounding mode is `Floor`, the largest float less than or equal to the
            ///   [`Rational`] is returned. If the [`Rational`] is greater than the maximum finite
            ///   float, then the maximum finite float is returned. If it is smaller than the
            ///   minimum finite float, then negative infinity is returned. If it is between zero
            ///   and the minimum positive float, then positive zero is returned.
            /// - If the rounding mode is `Ceiling`, the smallest float greater than or equal to the
            ///   [`Rational`] is returned. If the [`Rational`] is greater than the maximum finite
            ///   float, then positive infinity is returned. If it is smaller than the minimum
            ///   finite float, then the minimum finite float is returned. If it is between zero and
            ///   the maximum negative float, then negative zero is returned.
            /// - If the rounding mode is `Down`, then the rounding proceeds as with `Floor` if the
            ///   [`Rational`] is non-negative and as with `Ceiling` if the [`Rational`] is
            ///   negative. If the [`Rational`] is between the maximum negative float and the
            ///   minimum positive float, then positive zero is returned when the [`Rational`] is
            ///   non-negative and negative zero otherwise.
            /// - If the rounding mode is `Up`, then the rounding proceeds as with `Ceiling` if the
            ///   [`Rational`] is non-negative and as with `Floor` if the [`Rational`] is negative.
            ///   Positive zero is only returned when the [`Rational`] is zero, and negative zero is
            ///   never returned.
            /// - If the rounding mode is `Nearest`, then the nearest float is returned. If the
            ///   [`Rational`] is exactly between two floats, the float with the zero
            ///   least-significant bit in its representation is selected. If the [`Rational`] is
            ///   greater than the maximum finite float, then the maximum finite float is returned.
            ///   If the [`Rational`] is closer to zero than to any float (or if there is a tie
            ///   between zero and another float), then positive or negative zero is returned,
            ///   depending on the [`Rational`]'s sign.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n \log n \log\log n)$
            ///
            /// $M(n) = O(n \log n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Panics
            /// Panics if the rounding mode is `Exact` and `value` cannot be represented exactly.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#rounding_from).
            fn rounding_from(mut value: Rational, mut rm: RoundingMode) -> ($f, Ordering) {
                if value == 0u32 {
                    (0.0, Ordering::Equal)
                } else {
                    let sign = value.sign;
                    if !sign {
                        rm.neg_assign();
                    }
                    let mut exponent = value.floor_log_base_2_abs();
                    let (f, o) = if exponent > $f::MAX_EXPONENT {
                        match rm {
                            RoundingMode::Exact => {
                                panic!("Value cannot be represented exactly as a float")
                            }
                            RoundingMode::Floor | RoundingMode::Down | RoundingMode::Nearest => {
                                ($f::MAX_FINITE, Ordering::Less)
                            }
                            _ => ($f::INFINITY, Ordering::Greater),
                        }
                    } else if exponent >= $f::MIN_NORMAL_EXPONENT {
                        value >>= exponent - i64::wrapping_from($f::MANTISSA_WIDTH);
                        let (n, d) = value.into_numerator_and_denominator();
                        let (mut mantissa, o) = n.div_round(d, rm);
                        let mut bits = mantissa.significant_bits();
                        let mut done = false;
                        if bits > $f::MANTISSA_WIDTH + 1 {
                            if exponent == $f::MAX_EXPONENT {
                                done = true;
                            } else {
                                bits -= 1;
                                mantissa >>= 1; // lsb is zero
                                exponent += 1;
                            }
                        }
                        if done {
                            match rm {
                                RoundingMode::Exact => {
                                    panic!("Value cannot be represented exactly as a float")
                                }
                                RoundingMode::Floor
                                | RoundingMode::Down
                                | RoundingMode::Nearest => ($f::MAX_FINITE, Ordering::Less),
                                _ => ($f::INFINITY, Ordering::Greater),
                            }
                        } else {
                            assert_eq!(bits, $f::MANTISSA_WIDTH + 1);
                            mantissa.clear_bit($f::MANTISSA_WIDTH);
                            (
                                $f::from_raw_mantissa_and_exponent(
                                    u64::exact_from(&mantissa),
                                    u64::exact_from(exponent + $f::MAX_EXPONENT),
                                ),
                                o,
                            )
                        }
                    } else if exponent >= $f::MIN_EXPONENT {
                        let target_width = u64::wrapping_from(exponent - $f::MIN_EXPONENT + 1);
                        value >>= $f::MIN_EXPONENT;
                        let (n, d) = value.into_numerator_and_denominator();
                        let (mantissa, o) = n.div_round(d, rm);
                        (
                            if mantissa.significant_bits() > target_width
                                && exponent == $f::MIN_NORMAL_EXPONENT - 1
                            {
                                $f::MIN_POSITIVE_NORMAL
                            } else {
                                $f::from_raw_mantissa_and_exponent(u64::exact_from(&mantissa), 0)
                            },
                            o,
                        )
                    } else {
                        match rm {
                            RoundingMode::Exact => {
                                panic!("Value cannot be represented exactly as a float")
                            }
                            RoundingMode::Floor | RoundingMode::Down => (0.0, Ordering::Less),
                            RoundingMode::Nearest => {
                                if exponent == $f::MIN_EXPONENT - 1
                                    && !abs_is_neg_power_of_2(&value)
                                {
                                    ($f::MIN_POSITIVE_SUBNORMAL, Ordering::Greater)
                                } else {
                                    (0.0, Ordering::Less)
                                }
                            }
                            _ => ($f::MIN_POSITIVE_SUBNORMAL, Ordering::Greater),
                        }
                    };
                    if sign {
                        (f, o)
                    } else {
                        (-f, o.reverse())
                    }
                }
            }
        }

        impl TryFrom<Rational> for $f {
            type Error = FloatFromRationalError;

            /// Converts a [`Rational`] to a primitive float, taking the [`Rational`] by value. If
            /// the input isn't exactly equal to any float, an error is returned.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(1)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#try_from).
            fn try_from(value: Rational) -> Result<$f, Self::Error> {
                if value == 0 {
                    Ok(0.0)
                } else {
                    let sign = value.sign;
                    let (mantissa, exponent, _) = value
                        .sci_mantissa_and_exponent_round(RoundingMode::Exact)
                        .ok_or(FloatFromRationalError)?;
                    let f = $f::from_sci_mantissa_and_exponent(mantissa, i64::exact_from(exponent))
                        .ok_or(FloatFromRationalError);
                    if sign {
                        f
                    } else {
                        f.map(|x| -x)
                    }
                }
            }
        }

        impl ConvertibleFrom<Rational> for $f {
            /// Determines whether a [`Rational`] can be exactly converted to a primitive float,
            /// taking the [`Rational`] by value.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#convertible_from).
            fn convertible_from(value: Rational) -> bool {
                if value == 0 {
                    true
                } else {
                    if let Some((mantissa, exponent, _)) =
                        value.sci_mantissa_and_exponent_round::<$f>(RoundingMode::Exact)
                    {
                        let exponent = i64::exact_from(exponent);
                        if !($f::MIN_EXPONENT..=$f::MAX_EXPONENT).contains(&exponent) {
                            return false;
                        }
                        let (orig_mantissa, orig_exponent) = mantissa.raw_mantissa_and_exponent();
                        orig_exponent == u64::wrapping_from($f::MAX_EXPONENT)
                            && exponent >= $f::MIN_NORMAL_EXPONENT
                            || orig_mantissa.divisible_by_power_of_2(u64::wrapping_from(
                                $f::MIN_NORMAL_EXPONENT - exponent,
                            ))
                    } else {
                        false
                    }
                }
            }
        }

        impl<'a> RoundingFrom<&'a Rational> for $f {
            /// Converts a [`Rational`] to a value of a primitive float according to a specified
            /// [`RoundingMode`], taking the [`Rational`] by reference.
            ///
            /// - If the rounding mode is `Floor`, the largest float less than or equal to the
            ///   [`Rational`] is returned. If the [`Rational`] is greater than the maximum finite
            ///   float, then the maximum finite float is returned. If it is smaller than the
            ///   minimum finite float, then negative infinity is returned. If it is between zero
            ///   and the minimum positive float, then positive zero is returned.
            /// - If the rounding mode is `Ceiling`, the smallest float greater than or equal to the
            ///   [`Rational`] is returned. If the [`Rational`] is greater than the maximum finite
            ///   float, then positive infinity is returned. If it is smaller than the minimum
            ///   finite float, then the minimum finite float is returned. If it is between zero and
            ///   the maximum negative float, then negative zero is returned.
            /// - If the rounding mode is `Down`, then the rounding proceeds as with `Floor` if the
            ///   [`Rational`] is non-negative and as with `Ceiling` if the [`Rational`] is
            ///   negative. If the [`Rational`] is between the maximum negative float and the
            ///   minimum positive float, then positive zero is returned when the [`Rational`] is
            ///   non-negative and negative zero otherwise.
            /// - If the rounding mode is `Up`, then the rounding proceeds as with `Ceiling` if the
            ///   [`Rational`] is non-negative and as with `Floor` if the [`Rational`] is negative.
            ///   Positive zero is only returned when the [`Rational`] is zero, and negative zero is
            ///   never returned.
            /// - If the rounding mode is `Nearest`, then the nearest float is returned. If the
            ///   [`Rational`] is exactly between two floats, the float with the zero
            ///   least-significant bit in its representation is selected. If the [`Rational`] is
            ///   greater than the maximum finite float, then the maximum finite float is returned.
            ///   If the [`Rational`] is closer to zero than to any float (or if there is a tie
            ///   between zero and another float), then positive or negative zero is returned,
            ///   depending on the [`Rational`]'s sign.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n \log n \log\log n)$
            ///
            /// $M(n) = O(n \log n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Panics
            /// Panics if the rounding mode is `Exact` and `value` cannot be represented exactly.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#rounding_from).
            fn rounding_from(value: &'a Rational, mut rm: RoundingMode) -> ($f, Ordering) {
                if *value == 0u32 {
                    (0.0, Ordering::Equal)
                } else {
                    if !value.sign {
                        rm.neg_assign();
                    }
                    let mut exponent = value.floor_log_base_2_abs();
                    let (f, o) = if exponent > $f::MAX_EXPONENT {
                        match rm {
                            RoundingMode::Exact => {
                                panic!("Value cannot be represented exactly as a float")
                            }
                            RoundingMode::Floor | RoundingMode::Down | RoundingMode::Nearest => {
                                ($f::MAX_FINITE, Ordering::Less)
                            }
                            _ => ($f::INFINITY, Ordering::Greater),
                        }
                    } else if exponent >= $f::MIN_NORMAL_EXPONENT {
                        let x = value >> exponent - i64::wrapping_from($f::MANTISSA_WIDTH);
                        let (n, d) = x.into_numerator_and_denominator();
                        let (mut mantissa, o) = n.div_round(d, rm);
                        let mut bits = mantissa.significant_bits();
                        let mut done = false;
                        if bits > $f::MANTISSA_WIDTH + 1 {
                            if exponent == $f::MAX_EXPONENT {
                                done = true;
                            } else {
                                bits -= 1;
                                mantissa >>= 1; // lsb is zero
                                exponent += 1;
                            }
                        }
                        if done {
                            match rm {
                                RoundingMode::Exact => {
                                    panic!("Value cannot be represented exactly as a float")
                                }
                                RoundingMode::Floor
                                | RoundingMode::Down
                                | RoundingMode::Nearest => ($f::MAX_FINITE, Ordering::Less),
                                _ => ($f::INFINITY, Ordering::Greater),
                            }
                        } else {
                            assert_eq!(bits, $f::MANTISSA_WIDTH + 1);
                            mantissa.clear_bit($f::MANTISSA_WIDTH);
                            (
                                $f::from_raw_mantissa_and_exponent(
                                    u64::exact_from(&mantissa),
                                    u64::exact_from(exponent + $f::MAX_EXPONENT),
                                ),
                                o,
                            )
                        }
                    } else if exponent >= $f::MIN_EXPONENT {
                        let target_width = u64::wrapping_from(exponent - $f::MIN_EXPONENT + 1);
                        let x = value >> $f::MIN_EXPONENT;
                        let (n, d) = x.into_numerator_and_denominator();
                        let (mantissa, o) = n.div_round(d, rm);
                        (
                            if mantissa.significant_bits() > target_width
                                && exponent == $f::MIN_NORMAL_EXPONENT - 1
                            {
                                $f::MIN_POSITIVE_NORMAL
                            } else {
                                $f::from_raw_mantissa_and_exponent(u64::exact_from(&mantissa), 0)
                            },
                            o,
                        )
                    } else {
                        match rm {
                            RoundingMode::Exact => {
                                panic!("Value cannot be represented exactly as a float")
                            }
                            RoundingMode::Floor | RoundingMode::Down => (0.0, Ordering::Less),
                            RoundingMode::Nearest => {
                                if exponent == $f::MIN_EXPONENT - 1
                                    && !abs_is_neg_power_of_2(&value)
                                {
                                    ($f::MIN_POSITIVE_SUBNORMAL, Ordering::Greater)
                                } else {
                                    (0.0, Ordering::Less)
                                }
                            }
                            _ => ($f::MIN_POSITIVE_SUBNORMAL, Ordering::Greater),
                        }
                    };
                    if value.sign {
                        (f, o)
                    } else {
                        (-f, o.reverse())
                    }
                }
            }
        }

        impl<'a> TryFrom<&'a Rational> for $f {
            type Error = FloatFromRationalError;

            /// Converts a [`Rational`] to a primitive float, taking the [`Rational`] by reference.
            /// If the input isn't exactly equal to any float, an error is returned.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#try_from).
            fn try_from(value: &'a Rational) -> Result<$f, Self::Error> {
                if *value == 0 {
                    Ok(0.0)
                } else {
                    let (mantissa, exponent, _) = value
                        .sci_mantissa_and_exponent_round_ref(RoundingMode::Exact)
                        .ok_or(FloatFromRationalError)?;
                    let f = $f::from_sci_mantissa_and_exponent(mantissa, i64::exact_from(exponent))
                        .ok_or(FloatFromRationalError);
                    if value.sign {
                        f
                    } else {
                        f.map(|x| -x)
                    }
                }
            }
        }

        impl<'a> ConvertibleFrom<&'a Rational> for $f {
            /// Determines whether a [`Rational`] can be exactly converted to a primitive float,
            /// taking the [`Rational`] by reference.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
            ///
            /// # Examples
            /// See [here](super::primitive_float_from_rational#convertible_from).
            fn convertible_from(value: &'a Rational) -> bool {
                if *value == 0 {
                    true
                } else {
                    if let Some((mantissa, exponent, _)) =
                        value.sci_mantissa_and_exponent_round_ref::<$f>(RoundingMode::Exact)
                    {
                        let exponent = i64::exact_from(exponent);
                        if !($f::MIN_EXPONENT..=$f::MAX_EXPONENT).contains(&exponent) {
                            return false;
                        }
                        let (orig_mantissa, orig_exponent) = mantissa.raw_mantissa_and_exponent();
                        orig_exponent == u64::wrapping_from($f::MAX_EXPONENT)
                            && exponent >= $f::MIN_NORMAL_EXPONENT
                            || orig_mantissa.divisible_by_power_of_2(u64::wrapping_from(
                                $f::MIN_NORMAL_EXPONENT - exponent,
                            ))
                    } else {
                        false
                    }
                }
            }
        }
    };
}
apply_to_primitive_floats!(float_impls);