malachite_base/num/arithmetic/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::PowerOf2;
10use crate::num::basic::signeds::PrimitiveSigned;
11use crate::num::basic::unsigneds::PrimitiveUnsigned;
12use crate::num::conversion::traits::IntegerMantissaAndExponent;
13
14fn power_of_2_unsigned<T: PrimitiveUnsigned>(pow: u64) -> T {
15 assert!(pow < T::WIDTH);
16 T::ONE << pow
17}
18
19macro_rules! impl_power_of_2_unsigned {
20 ($t:ident) => {
21 impl PowerOf2<u64> for $t {
22 /// Raises 2 to an integer power.
23 ///
24 /// $f(k) = 2^k$.
25 ///
26 /// # Worst-case complexity
27 /// Constant time and additional memory.
28 ///
29 /// # Panics
30 /// Panics if the result is not representable.
31 ///
32 /// # Examples
33 /// See [here](super::power_of_2#power_of_2).
34 #[inline]
35 fn power_of_2(pow: u64) -> $t {
36 power_of_2_unsigned(pow)
37 }
38 }
39 };
40}
41apply_to_unsigneds!(impl_power_of_2_unsigned);
42
43fn power_of_2_signed<T: PrimitiveSigned>(pow: u64) -> T {
44 assert!(pow < T::WIDTH - 1);
45 T::ONE << pow
46}
47
48macro_rules! impl_power_of_2_signed {
49 ($t:ident) => {
50 impl PowerOf2<u64> for $t {
51 /// Raises 2 to an integer power.
52 ///
53 /// $f(k) = 2^k$.
54 ///
55 /// # Worst-case complexity
56 /// Constant time and additional memory.
57 ///
58 /// # Panics
59 /// Panics if the result is not representable.
60 ///
61 /// # Examples
62 /// See [here](super::power_of_2#power_of_2).
63 #[inline]
64 fn power_of_2(pow: u64) -> $t {
65 power_of_2_signed(pow)
66 }
67 }
68 };
69}
70apply_to_signeds!(impl_power_of_2_signed);
71
72macro_rules! impl_power_of_2_primitive_float {
73 ($t:ident) => {
74 impl PowerOf2<i64> for $t {
75 /// Raises 2 to an integer power.
76 ///
77 /// $f(k) = 2^k$.
78 ///
79 /// # Worst-case complexity
80 /// Constant time and additional memory.
81 ///
82 /// # Panics
83 /// Panics if the power is smaller than `Self::MIN_EXPONENT` or greater than
84 /// `Self::MAX_EXPONENT`.
85 ///
86 /// # Examples
87 /// See [here](super::power_of_2#power_of_2).
88 #[inline]
89 fn power_of_2(pow: i64) -> $t {
90 $t::from_integer_mantissa_and_exponent(1, pow).unwrap()
91 }
92 }
93 };
94}
95apply_to_primitive_floats!(impl_power_of_2_primitive_float);