malachite_nz/natural/conversion/from_primitive_float.rs
1// Copyright © 2026 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::natural::Natural;
10use core::cmp::Ordering::{self, *};
11use malachite_base::num::arithmetic::traits::ShlRound;
12use malachite_base::num::basic::traits::Zero;
13use malachite_base::num::conversion::from::UnsignedFromFloatError;
14use malachite_base::num::conversion::traits::{
15 ConvertibleFrom, IntegerMantissaAndExponent, IsInteger, RoundingFrom,
16};
17use malachite_base::rounding_modes::RoundingMode::{self, *};
18
19macro_rules! float_impls {
20 ($f: ident) => {
21 impl RoundingFrom<$f> for Natural {
22 /// Converts a floating-point value to a [`Natural`], using the specified rounding mode.
23 /// An [`Ordering`] is also returned, indicating whether the returned value is less
24 /// than, equal to, or greater than the original value.
25 ///
26 /// The floating-point value cannot be NaN or infinite, and it cannot round to a
27 /// negative integer.
28 ///
29 /// # Worst-case complexity
30 /// $T(n) = O(n)$
31 ///
32 /// $M(n) = O(n)$
33 ///
34 /// where $T$ is time, $M$ is additional memory, and $n$ is `value.sci_exponent()`.
35 ///
36 /// # Panics
37 /// Panics if `value` is NaN or infinite, if it would round to a negative integer, or if
38 /// the rounding mode is `Exact` and `value` is not an integer.
39 ///
40 /// # Examples
41 /// See [here](super::from_primitive_float#rounding_from).
42 fn rounding_from(value: $f, rm: RoundingMode) -> (Self, Ordering) {
43 if value.is_nan() || value == $f::INFINITY {
44 panic!("Cannot convert {} to Natural", value);
45 } else if value == 0.0 {
46 (Natural::ZERO, Equal)
47 } else if value < 0.0 {
48 if rm == Down || rm == Ceiling || rm == Nearest {
49 (Natural::ZERO, Greater)
50 } else {
51 panic!("Result is negative and cannot be converted to a Natural");
52 }
53 } else {
54 let (mantissa, exponent) = value.integer_mantissa_and_exponent();
55 Natural::from(mantissa).shl_round(exponent, rm)
56 }
57 }
58 }
59
60 impl TryFrom<$f> for Natural {
61 type Error = UnsignedFromFloatError;
62
63 /// Converts a floating-point value to a [`Natural`].
64 ///
65 /// If the input isn't exactly equal to some [`Natural`], an error is returned.
66 ///
67 /// # Worst-case complexity
68 /// $T(n) = O(n)$
69 ///
70 /// $M(n) = O(n)$
71 ///
72 /// where $T$ is time, $M$ is additional memory, and $n$ is `value.sci_exponent()`.
73 ///
74 /// # Examples
75 /// See [here](super::from_primitive_float#try_from).
76 fn try_from(value: $f) -> Result<Natural, Self::Error> {
77 if value.is_nan() || value.is_infinite() {
78 Err(UnsignedFromFloatError::FloatInfiniteOrNan)
79 } else if value < 0.0 {
80 Err(UnsignedFromFloatError::FloatNegative)
81 } else if value == 0.0 {
82 Ok(Natural::ZERO)
83 } else {
84 let (mantissa, exponent) = value.integer_mantissa_and_exponent();
85 if exponent >= 0 {
86 Ok(Natural::from(mantissa) << exponent)
87 } else {
88 Err(UnsignedFromFloatError::FloatNonIntegerOrOutOfRange)
89 }
90 }
91 }
92 }
93
94 impl ConvertibleFrom<$f> for Natural {
95 /// Determines whether a floating-point value can be exactly converted to a [`Natural`].
96 ///
97 /// # Worst-case complexity
98 /// Constant time and additional memory.
99 ///
100 /// # Examples
101 /// See [here](super::from_primitive_float#convertible_from).
102 #[inline]
103 fn convertible_from(value: $f) -> bool {
104 value >= 0.0 && value.is_integer()
105 }
106 }
107 };
108}
109apply_to_primitive_floats!(float_impls);