malachite_base/num/arithmetic/
is_power_of_2.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::num::arithmetic::traits::IsPowerOf2;
10use crate::num::conversion::traits::IntegerMantissaAndExponent;
11
12macro_rules! impl_is_power_of_2_unsigned {
13    ($t:ident) => {
14        impl IsPowerOf2 for $t {
15            /// This is a wrapper over the `is_power_of_two` functions in the standard library, for
16            /// example [this one](u32::is_power_of_two).
17            #[inline]
18            fn is_power_of_2(&self) -> bool {
19                $t::is_power_of_two(*self)
20            }
21        }
22    };
23}
24apply_to_unsigneds!(impl_is_power_of_2_unsigned);
25
26macro_rules! impl_is_power_of_2_primitive_float {
27    ($t:ident) => {
28        impl IsPowerOf2 for $t {
29            /// Determines whether a number is an integer power of 2.
30            ///
31            /// $f(x) = (\exists n \in \Z : 2^n = x)$.
32            ///
33            /// # Worst-case complexity
34            /// Constant time and additional memory.
35            ///
36            /// # Examples
37            /// See [here](super::is_power_of_2#is_power_of_2).
38            #[inline]
39            fn is_power_of_2(&self) -> bool {
40                self.is_finite() && *self > 0.0 && self.integer_mantissa() == 1
41            }
42        }
43    };
44}
45apply_to_primitive_floats!(impl_is_power_of_2_primitive_float);