Skip to main content

malachite_base/num/arithmetic/
is_unit.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::num::arithmetic::traits::IsUnit;
10
11macro_rules! impl_is_unit_unsigned {
12    ($t:ident) => {
13        impl IsUnit for $t {
14            /// Determines whether a number is a unit: whether it is 1, the only unsigned integer
15            /// with a multiplicative inverse.
16            ///
17            /// # Worst-case complexity
18            /// Constant time and additional memory.
19            ///
20            /// # Examples
21            /// See [here](super::is_unit#is_unit).
22            #[inline]
23            fn is_unit(&self) -> bool {
24                *self == 1
25            }
26        }
27    };
28}
29apply_to_unsigneds!(impl_is_unit_unsigned);
30
31macro_rules! impl_is_unit_signed {
32    ($t:ident) => {
33        impl IsUnit for $t {
34            /// Determines whether a number is a unit: whether it is 1 or $-1$, the only integers
35            /// with a multiplicative inverse.
36            ///
37            /// # Worst-case complexity
38            /// Constant time and additional memory.
39            ///
40            /// # Examples
41            /// See [here](super::is_unit#is_unit).
42            #[inline]
43            fn is_unit(&self) -> bool {
44                *self == 1 || *self == -1
45            }
46        }
47    };
48}
49apply_to_signeds!(impl_is_unit_signed);
50
51macro_rules! impl_is_unit_primitive_float {
52    ($t:ident) => {
53        impl IsUnit for $t {
54            /// Determines whether a number is a unit: whether it is finite and nonzero, so that it
55            /// has a multiplicative inverse. NaN and the infinities are not units.
56            ///
57            /// # Worst-case complexity
58            /// Constant time and additional memory.
59            ///
60            /// # Examples
61            /// See [here](super::is_unit#is_unit).
62            #[inline]
63            fn is_unit(&self) -> bool {
64                self.is_finite() && *self != 0.0
65            }
66        }
67    };
68}
69apply_to_primitive_floats!(impl_is_unit_primitive_float);