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
// 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::InnerFloat::Finite;
use crate::{significand_bits, Float};
use core::cmp::Ordering::{self, *};
use malachite_base::num::arithmetic::traits::{
    RoundToMultipleOfPowerOf2, RoundToMultipleOfPowerOf2Assign,
};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_nz::natural::Natural;
use malachite_nz::platform::Limb;

impl Float {
    /// Gets the significand of a [`Float`], taking the [`Float`] by value.
    ///
    /// The significand is the smallest positive integer which is some power of 2 times the
    /// [`Float`], and whose number of significant bits is a multiple of the limb width. If the
    /// [`Float`] is NaN, infinite, or zero, then `None` is returned.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::arithmetic::traits::PowerOf2;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::basic::traits::One;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, Zero};
    /// use malachite_float::Float;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_nz::natural::Natural;
    ///
    /// assert_eq!(Float::NAN.to_significand(), None);
    /// assert_eq!(Float::INFINITY.to_significand(), None);
    /// assert_eq!(Float::ZERO.to_significand(), None);
    ///
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// {
    ///     assert_eq!(Float::ONE.to_significand(), Some(Natural::power_of_2(63)));
    ///     assert_eq!(
    ///         Float::from(std::f64::consts::PI).to_significand().unwrap(),
    ///         14488038916154245120u64
    ///     );
    /// }
    /// ```
    #[inline]
    pub fn to_significand(&self) -> Option<Natural> {
        match self {
            Float(Finite { significand, .. }) => Some(significand.clone()),
            _ => None,
        }
    }

    /// Gets the significand of a [`Float`], taking the [`Float`] by reference.
    ///
    /// The significand is the smallest positive integer which is some power of 2 times the
    /// [`Float`], and whose number of significant bits is a multiple of the limb width. If the
    /// [`Float`] is NaN, infinite, or zero, then `None` is returned.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::arithmetic::traits::PowerOf2;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::basic::traits::One;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, Zero};
    /// use malachite_float::Float;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_nz::natural::Natural;
    ///
    /// assert_eq!(Float::NAN.into_significand(), None);
    /// assert_eq!(Float::INFINITY.into_significand(), None);
    /// assert_eq!(Float::ZERO.into_significand(), None);
    ///
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// {
    ///     assert_eq!(Float::ONE.into_significand(), Some(Natural::power_of_2(63)));
    ///     assert_eq!(
    ///         Float::from(std::f64::consts::PI)
    ///             .into_significand()
    ///             .unwrap(),
    ///         14488038916154245120u64
    ///     );
    /// }
    /// ```
    #[allow(clippy::missing_const_for_fn)] // destructor doesn't work with const
    #[inline]
    pub fn into_significand(self) -> Option<Natural> {
        match self {
            Float(Finite { significand, .. }) => Some(significand),
            _ => None,
        }
    }

    /// Returns a reference to the significand of a [`Float`].
    ///
    /// The significand is the smallest positive integer which is some power of 2 times the
    /// [`Float`], and whose number of significant bits is a multiple of the limb width. If the
    /// [`Float`] is NaN, infinite, or zero, then `None` is returned.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::arithmetic::traits::PowerOf2;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_base::num::basic::traits::One;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, Zero};
    /// use malachite_float::Float;
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// use malachite_nz::natural::Natural;
    ///
    /// assert_eq!(Float::NAN.significand_ref(), None);
    /// assert_eq!(Float::INFINITY.significand_ref(), None);
    /// assert_eq!(Float::ZERO.significand_ref(), None);
    ///
    /// #[cfg(not(feature = "32_bit_limbs"))]
    /// {
    ///     assert_eq!(
    ///         *Float::ONE.significand_ref().unwrap(),
    ///         Natural::power_of_2(63)
    ///     );
    ///     assert_eq!(
    ///         *Float::from(std::f64::consts::PI).significand_ref().unwrap(),
    ///         14488038916154245120u64
    ///     );
    /// }
    /// ```
    #[inline]
    pub const fn significand_ref(&self) -> Option<&Natural> {
        match self {
            Float(Finite { significand, .. }) => Some(significand),
            _ => None,
        }
    }

    /// Returns a [`Float`]'s exponent.
    ///
    /// $$
    /// f(\text{NaN}) = f(\pm\infty) = f(\pm 0.0) = \text{None},
    /// $$
    ///
    /// and, if $x$ is finite and nonzero,
    ///
    /// $$
    /// f(x) = \operatorname{Some}(\lfloor \log_2 x \rfloor + 1).
    /// $$
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::PowerOf2;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, One, Zero};
    /// use malachite_float::Float;
    ///
    /// assert_eq!(Float::NAN.get_exponent(), None);
    /// assert_eq!(Float::INFINITY.get_exponent(), None);
    /// assert_eq!(Float::ZERO.get_exponent(), None);
    ///
    /// assert_eq!(Float::ONE.get_exponent(), Some(1));
    /// assert_eq!(Float::from(std::f64::consts::PI).get_exponent(), Some(2));
    /// assert_eq!(Float::power_of_2(100u64).get_exponent(), Some(101));
    /// assert_eq!(Float::power_of_2(-100i64).get_exponent(), Some(-99));
    /// ```
    #[inline]
    pub const fn get_exponent(&self) -> Option<i64> {
        match self {
            Float(Finite { exponent, .. }) => Some(*exponent),
            _ => None,
        }
    }

    /// Returns a [`Float`]'s precision. The precision is a positive integer denoting how many of
    /// the [`Float`]'s bits are significant.
    ///
    /// Only [`Float`]s that are finite and nonzero have a precision. For other [`Float`]s, `None`
    /// is returned.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::traits::{Infinity, NaN, One, Zero};
    /// use malachite_float::Float;
    ///
    /// assert_eq!(Float::NAN.get_prec(), None);
    /// assert_eq!(Float::INFINITY.get_prec(), None);
    /// assert_eq!(Float::ZERO.get_prec(), None);
    ///
    /// assert_eq!(Float::ONE.get_prec(), Some(1));
    /// assert_eq!(Float::one_prec(100).get_prec(), Some(100));
    /// assert_eq!(Float::from(std::f64::consts::PI).get_prec(), Some(53));
    /// ```
    #[inline]
    pub const fn get_prec(&self) -> Option<u64> {
        match self {
            Float(Finite { precision, .. }) => Some(*precision),
            _ => None,
        }
    }

    /// Returns the minimum precision necessary to represent the given [`Float`]'s value.
    ///
    /// For example, `Float:one_prec(100)` has a precision of 100, but its minimum precision is 1,
    /// because that's all that's necessary to represent the value 1.
    ///
    /// The minimum precision is always less than or equal to the actual precision.
    ///
    /// Only [`Float`]s that are finite and nonzero have a minimum precision. For other [`Float`]s,
    /// `None` is returned.
    ///
    /// # Worst-case complexity
    /// Constant time and additional memory.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::basic::traits::{Infinity, NaN, One, Zero};
    /// use malachite_float::Float;
    ///
    /// assert_eq!(Float::NAN.get_min_prec(), None);
    /// assert_eq!(Float::INFINITY.get_min_prec(), None);
    /// assert_eq!(Float::ZERO.get_min_prec(), None);
    ///
    /// assert_eq!(Float::ONE.get_min_prec(), Some(1));
    /// assert_eq!(Float::one_prec(100).get_min_prec(), Some(1));
    /// assert_eq!(Float::from(std::f64::consts::PI).get_min_prec(), Some(50));
    /// ```
    pub fn get_min_prec(&self) -> Option<u64> {
        match self {
            Float(Finite { significand, .. }) => {
                Some(significand_bits(significand) - significand.trailing_zeros().unwrap())
            }
            _ => None,
        }
    }

    /// Changes a [`Float`]'s precision. If the precision decreases, rounding may be necessary, and
    /// will use the provided [`RoundingMode`].
    ///
    /// Returns an [`Ordering`], indicating whether the final value is less than, greater than, or
    /// equal to the original value.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero or if `rm` is [`Exact`] but setting the desired precision requires
    /// rounding.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let original_x = Float::from(1.0f64 / 3.0);
    /// assert_eq!(original_x.to_string(), "0.33333333333333331");
    /// assert_eq!(original_x.get_prec(), Some(53));
    ///
    /// let mut x = original_x.clone();
    /// assert_eq!(x.set_prec_round(100, Exact), Equal);
    /// assert_eq!(x.to_string(), "0.3333333333333333148296162562474");
    /// assert_eq!(x.get_prec(), Some(100));
    ///
    /// let mut x = original_x.clone();
    /// assert_eq!(x.set_prec_round(10, Floor), Less);
    /// assert_eq!(x.to_string(), "0.333");
    /// assert_eq!(x.get_prec(), Some(10));
    ///
    /// let mut x = original_x.clone();
    /// assert_eq!(x.set_prec_round(10, Ceiling), Greater);
    /// assert_eq!(x.to_string(), "0.3335");
    /// assert_eq!(x.get_prec(), Some(10));
    /// ```
    pub fn set_prec_round(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
        assert_ne!(prec, 0);
        match self {
            Float(Finite {
                sign,
                exponent,
                precision,
                significand,
            }) => {
                let target_bits = prec
                    .round_to_multiple_of_power_of_2(Limb::LOG_WIDTH, Ceiling)
                    .0;
                let significant_bits = significand_bits(significand);
                let o;
                if target_bits > significant_bits {
                    *significand <<= target_bits - significant_bits;
                    o = Equal;
                } else {
                    let limb_count = significand.limb_count();
                    let abs_rm = if *sign { rm } else { -rm };
                    o = significand
                        .round_to_multiple_of_power_of_2_assign(significant_bits - prec, abs_rm);
                    if significand.limb_count() > limb_count {
                        *significand >>= 1;
                        *exponent = exponent.checked_add(1).unwrap();
                    }
                    *significand >>= significant_bits - target_bits;
                }
                *precision = prec;
                if *sign {
                    o
                } else {
                    o.reverse()
                }
            }
            _ => Equal,
        }
    }

    /// Changes a [`Float`]'s precision. If the precision decreases, rounding may be necessary, and
    /// [`Nearest`] will be used.
    ///
    /// Returns an [`Ordering`], indicating whether the final value is less than, greater than, or
    /// equal to the original value.
    ///
    /// To use a different rounding mode, try [`Float::set_prec_round`].
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n)$
    ///
    /// $M(n) = O(n)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let original_x = Float::from(1.0f64 / 3.0);
    /// assert_eq!(original_x.to_string(), "0.33333333333333331");
    /// assert_eq!(original_x.get_prec(), Some(53));
    ///
    /// let mut x = original_x.clone();
    /// assert_eq!(x.set_prec(100), Equal);
    /// assert_eq!(x.to_string(), "0.3333333333333333148296162562474");
    /// assert_eq!(x.get_prec(), Some(100));
    ///
    /// let mut x = original_x.clone();
    /// assert_eq!(x.set_prec(10), Greater);
    /// assert_eq!(x.to_string(), "0.3335");
    /// assert_eq!(x.get_prec(), Some(10));
    /// ```
    #[inline]
    pub fn set_prec(&mut self, p: u64) -> Ordering {
        self.set_prec_round(p, Nearest)
    }
}