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
pub trait IsPowerOfTwo {
    /// Checks if a number is a power of 2.
    /// ```
    /// use traiter::numbers::IsPowerOfTwo;
    /// // signed integers
    /// assert!(!IsPowerOfTwo::is_power_of_two(&-1i8));
    /// assert!(!IsPowerOfTwo::is_power_of_two(&0i8));
    /// assert!(IsPowerOfTwo::is_power_of_two(&1i8));
    /// // unsigned integers
    /// assert!(!IsPowerOfTwo::is_power_of_two(&0u8));
    /// assert!(IsPowerOfTwo::is_power_of_two(&1u8));
    /// assert!(IsPowerOfTwo::is_power_of_two(&2i8));
    /// ```
    fn is_power_of_two(&self) -> bool;
}

macro_rules! unsigned_integer_is_power_of_two_impl {
    ($($integer:ty)*) => ($(
        impl IsPowerOfTwo for $integer {
            #[inline(always)]
            fn is_power_of_two(&self) -> bool {
                <$integer>::is_power_of_two(*self)
            }
        }
    )*)
}

unsigned_integer_is_power_of_two_impl!(u8 u16 u32 u64 u128 usize);

trait Unsigned {
    type Output;
}

impl Unsigned for i8 {
    type Output = u8;
}

impl Unsigned for i16 {
    type Output = u8;
}

impl Unsigned for i32 {
    type Output = u16;
}

impl Unsigned for i64 {
    type Output = u32;
}

impl Unsigned for i128 {
    type Output = u64;
}

impl Unsigned for isize {
    type Output = usize;
}

macro_rules! signed_integer_is_power_of_two_impl {
    ($($integer:ty)*) => ($(
        impl IsPowerOfTwo for $integer {
            #[inline(always)]
            fn is_power_of_two(&self) -> bool {
                <$integer>::is_positive(*self)
                    && (*self as <$integer as Unsigned>::Output)
                        .is_power_of_two()
            }
        }
    )*)
}

signed_integer_is_power_of_two_impl!(i8 i16 i32 i64 i128 isize);