malachite_nz/integer/conversion/
from_primitive_float.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use crate::natural::Natural;
11use core::cmp::Ordering;
12use malachite_base::num::conversion::from::{SignedFromFloatError, UnsignedFromFloatError};
13use malachite_base::num::conversion::traits::{ConvertibleFrom, RoundingFrom};
14use malachite_base::rounding_modes::RoundingMode;
15
16macro_rules! float_impls {
17    ($f: ident) => {
18        impl RoundingFrom<$f> for Integer {
19            /// Converts a primitive float to an [`Integer`], using the specified rounding mode. An
20            /// [`Ordering`] is also returned, indicating whether the returned value is less than,
21            /// equal to, or greater than the original value.
22            ///
23            /// The floating-point value cannot be NaN or infinite.
24            ///
25            /// # Worst-case complexity
26            /// $T(n) = O(n)$
27            ///
28            /// $M(n) = O(n)$
29            ///
30            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.sci_exponent()`.
31            ///
32            /// # Panics
33            /// Panics if `value` is NaN or infinite or if the rounding mode is `Exact` and `value`
34            /// is not an integer.
35            ///
36            /// # Examples
37            /// See [here](super::from_primitive_float#rounding_from).
38            fn rounding_from(value: $f, rm: RoundingMode) -> (Self, Ordering) {
39                if value >= 0.0 {
40                    let (abs, o) = Natural::rounding_from(value, rm);
41                    (Integer { sign: true, abs }, o)
42                } else {
43                    let (n, o) = Natural::rounding_from(-value, -rm);
44                    (-n, o.reverse())
45                }
46            }
47        }
48
49        impl TryFrom<$f> for Integer {
50            type Error = SignedFromFloatError;
51
52            /// Converts a primitive float to an [`Integer`].
53            ///
54            /// If the input isn't exactly equal to some [`Integer`], an error is returned.
55            ///
56            /// # Worst-case complexity
57            /// $T(n) = O(n)$
58            ///
59            /// $M(n) = O(n)$
60            ///
61            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.sci_exponent()`.
62            ///
63            /// # Examples
64            /// See [here](super::from_primitive_float#try_from).
65            fn try_from(value: $f) -> Result<Integer, Self::Error> {
66                Natural::try_from(value.abs())
67                    .map(|n| Integer {
68                        sign: value >= 0.0,
69                        abs: n,
70                    })
71                    .map_err(|e| match e {
72                        UnsignedFromFloatError::FloatInfiniteOrNan => {
73                            SignedFromFloatError::FloatInfiniteOrNan
74                        }
75                        UnsignedFromFloatError::FloatNonIntegerOrOutOfRange => {
76                            SignedFromFloatError::FloatNonIntegerOrOutOfRange
77                        }
78                        _ => unreachable!(),
79                    })
80            }
81        }
82
83        impl ConvertibleFrom<$f> for Integer {
84            /// Determines whether a primitive float can be exactly converted to an [`Integer`].
85            ///
86            /// # Worst-case complexity
87            /// Constant time and additional memory.
88            ///
89            /// # Examples
90            /// See [here](super::from_primitive_float#convertible_from).
91            fn convertible_from(value: $f) -> bool {
92                Natural::convertible_from(value.abs())
93            }
94        }
95    };
96}
97apply_to_primitive_floats!(float_impls);