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 © 2016–2024 Trevor Spiteri

// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License and
// a copy of the GNU General Public License along with this program. If not, see
// <https://www.gnu.org/licenses/>.

/*!
Multi-precision floating-point numbers with correct rounding.

This module provides support for floating-point numbers of type
[`Float`][crate::Float].
*/

pub(crate) mod arith;
pub(crate) mod big;
mod borrow;
mod casts;
mod cmp;
#[cfg(feature = "num-traits")]
mod impl_num_traits;
pub(crate) mod mini;
mod ord;
#[cfg(feature = "serde")]
mod serde;
pub(crate) mod small;
#[cfg(test)]
pub(crate) mod tests;
mod traits;

pub use crate::float::big::ParseFloatError;
pub use crate::float::borrow::BorrowFloat;
pub use crate::float::mini::{MiniFloat, ToMini};
pub use crate::float::ord::OrdFloat;
#[allow(deprecated)]
pub use crate::float::small::{SmallFloat, ToSmall};
use az::SaturatingCast;
use gmp_mpfr_sys::mpfr;
use gmp_mpfr_sys::mpfr::prec_t;

/**
Returns the minimum value for the exponent.

# Examples

```rust
use rug::float;
println!("Minimum exponent is {}", float::exp_min());
```
*/
#[inline]
pub fn exp_min() -> i32 {
    unsafe { mpfr::get_emin() }.saturating_cast()
}

/**
Returns the maximum value for the exponent.

# Examples

```rust
use rug::float;
println!("Maximum exponent is {}", float::exp_max());
```
*/
#[inline]
pub fn exp_max() -> i32 {
    unsafe { mpfr::get_emax() }.saturating_cast()
}

/**
Returns the maximum allowed range for the exponent.

# Examples

```rust
use rug::float;
let (min, max) = float::allowed_exp_range();
println!("Minimum and maximum exponents are in [{}, {}]", min, max);
```
*/
#[inline]
pub fn allowed_exp_range() -> (i32, i32) {
    unsafe {
        (
            mpfr::get_emin_min().saturating_cast(),
            mpfr::get_emax_max().saturating_cast(),
        )
    }
}

/**
Returns the minimum value for the precision.

# Examples

```rust
use rug::float;
println!("Minimum precision is {}", float::prec_min());
```
*/
#[inline]
pub const fn prec_min() -> u32 {
    mpfr::PREC_MIN as u32
}

/**
Returns the maximum value for the precision.

# Examples

```rust
use rug::float;
println!("Maximum precision is {}", float::prec_max());
```
*/
#[inline]
pub const fn prec_max() -> u32 {
    if mpfr::PREC_MAX < u32::MAX as prec_t {
        mpfr::PREC_MAX as u32
    } else {
        u32::MAX
    }
}

/**
The rounding methods for floating-point values.

When rounding to the nearest, if the number to be rounded is exactly between two
representable numbers, it is rounded to the even one, that is, the one with the
least significant bit set to zero.

# Examples

```rust
use rug::float::Round;
use rug::ops::AssignRound;
use rug::Float;
let mut f4 = Float::new(4);
f4.assign_round(10.4, Round::Nearest);
assert_eq!(f4, 10);
f4.assign_round(10.6, Round::Nearest);
assert_eq!(f4, 11);
f4.assign_round(-10.7, Round::Zero);
assert_eq!(f4, -10);
f4.assign_round(10.3, Round::Up);
assert_eq!(f4, 11);
```

Rounding to the nearest will round numbers exactly between two representable
numbers to the even one.

```rust
use rug::float::Round;
use rug::ops::AssignRound;
use rug::Float;
// 24 is 11000 in binary
// 25 is 11001 in binary
// 26 is 11010 in binary
// 27 is 11011 in binary
// 28 is 11100 in binary
let mut f4 = Float::new(4);
f4.assign_round(25, Round::Nearest);
assert_eq!(f4, 24);
f4.assign_round(27, Round::Nearest);
assert_eq!(f4, 28);
```
*/
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum Round {
    /// Round towards the nearest, with ties rounding to even.
    #[default]
    Nearest,
    /// Round towards zero.
    Zero,
    /// Round towards plus infinity.
    Up,
    /// Round towards minus infinity.
    Down,
    /// Round away from zero.
    AwayZero,
}

impl Round {
    #[inline]
    /// Reverses the rounding direction.
    ///
    ///   * [`Up`] becomes [`Down`].
    ///   * [`Down`] becomes [`Up`].
    ///   * Other variants are not affected.
    ///
    /// [`Up`]: Round::Up
    /// [`Down`]: Round::Down
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::float::Round;
    ///
    /// assert_eq!(Round::Up.reverse(), Round::Down);
    /// assert_eq!(Round::Down.reverse(), Round::Up);
    /// assert_eq!(Round::Nearest.reverse(), Round::Nearest);
    /// ```
    #[must_use]
    pub fn reverse(self) -> Round {
        match self {
            Round::Up => Round::Down,
            Round::Down => Round::Up,
            _ => self,
        }
    }
}

/**
The available floating-point constants.

# Examples

```rust
use rug::float::Constant;
use rug::Float;

let log2 = Float::with_val(53, Constant::Log2);
let pi = Float::with_val(53, Constant::Pi);
let euler = Float::with_val(53, Constant::Euler);
let catalan = Float::with_val(53, Constant::Catalan);

assert_eq!(log2.to_string_radix(10, Some(5)), "6.9315e-1");
assert_eq!(pi.to_string_radix(10, Some(5)), "3.1416");
assert_eq!(euler.to_string_radix(10, Some(5)), "5.7722e-1");
assert_eq!(catalan.to_string_radix(10, Some(5)), "9.1597e-1");
```
*/
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum Constant {
    /// The logarithm of two, 0.693147…
    Log2,
    /// The value of pi, π = 3.14159…
    Pi,
    /// Euler’s constant, also known as the Euler-Mascheroni constant, γ = 0.577215…
    ///
    /// Note that this is *not* Euler’s number e, which can be obtained using
    /// one of the [`exp`][crate::Float::exp] functions.
    Euler,
    /// Catalan’s constant, 0.915965…
    Catalan,
}

/**
Special floating-point values.

# Examples

```rust
use rug::float::Special;
use rug::Float;

let zero = Float::with_val(53, Special::Zero);
let neg_zero = Float::with_val(53, Special::NegZero);
let infinity = Float::with_val(53, Special::Infinity);
let neg_infinity = Float::with_val(53, Special::NegInfinity);
let nan = Float::with_val(53, Special::Nan);

assert_eq!(zero, 0);
assert!(zero.is_sign_positive());
assert_eq!(neg_zero, 0);
assert!(neg_zero.is_sign_negative());
assert!(infinity.is_infinite());
assert!(infinity.is_sign_positive());
assert!(neg_infinity.is_infinite());
assert!(neg_infinity.is_sign_negative());
assert!(nan.is_nan());
```
*/
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum Special {
    /// Positive zero.
    Zero,
    /// Negative zero.
    NegZero,
    /// Positive infinity.
    Infinity,
    /// Negative infinity.
    NegInfinity,
    /// Not a number.
    Nan,
}

/**
Specifies which cache to free.

# Examples

```rust
use rug::float;
use rug::float::FreeCache;
use std::thread;

fn main() {
    let child = thread::spawn(move || {
        // some work here that uses Float
        float::free_cache(FreeCache::Local);
    });
    // some work here
    child.join().expect("couldn't join thread");
    float::free_cache(FreeCache::All);
}
```
*/
#[allow(clippy::needless_doctest_main)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum FreeCache {
    /// Free caches local to the current thread.
    Local,
    /// Free caches shared by all threads.
    Global,
    /// Free both local and global caches.
    All,
}

/**
Frees various caches and memory pools that are used internally.

To avoid memory leaks being reported when using tools like [Valgrind], it is
advisable to free thread-local caches before terminating a thread and all caches
before exiting.

# Examples

```rust
use rug::float;
use rug::float::FreeCache;
use std::thread;

fn main() {
    let child = thread::spawn(move || {
        // some work here that uses Float
        float::free_cache(FreeCache::Local);
    });
    // some work here
    child.join().expect("couldn't join thread");
    float::free_cache(FreeCache::All);
}
```

[Valgrind]: https://www.valgrind.org/
*/
#[allow(clippy::needless_doctest_main)]
#[inline]
pub fn free_cache(which: FreeCache) {
    let way = match which {
        FreeCache::Local => mpfr::FREE_LOCAL_CACHE,
        FreeCache::Global => mpfr::FREE_GLOBAL_CACHE,
        FreeCache::All => mpfr::FREE_LOCAL_CACHE | mpfr::FREE_GLOBAL_CACHE,
    };
    unsafe {
        mpfr::free_cache2(way);
    }
}