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
///! Helper functions to get most and least significant non-zero bits
use super::big_num::U256;

/// Returns index of the most significant non-zero bit of the number
///
/// The function satisfies the property:
///     x >= 2**most_significant_bit(x) and x < 2**(most_significant_bit(x)+1)
///
/// # Arguments
///
/// * `x` - the value for which to compute the most significant bit, must be greater than 0
///
pub fn most_significant_bit(x: U256) -> u8 {
    assert!(x > U256::default());
    255 - x.leading_zeros() as u8
}

/// Returns index of the least significant non-zero bit of the number
///
/// The function satisfies the property:
///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
///
///
/// # Arguments
///
/// * `x` - the value for which to compute the least significant bit, must be greater than 0
///
pub fn least_significant_bit(x: U256) -> u8 {
    assert!(x > U256::default());
    x.trailing_zeros() as u8
}

#[cfg(test)]
mod tests {
    use super::*;
    mod most_significant_bit {
        use super::*;

        #[test]
        fn test_msb_at_powers_of_two() {
            for i in 0..255 {
                let a = U256::from(1) << i;
                assert_eq!(most_significant_bit(a), i);
            }
        }

        #[test]
        #[should_panic]
        fn test_msb_for_0() {
            most_significant_bit(U256::default());
        }

        #[test]
        fn test_msb_for_1() {
            assert_eq!(most_significant_bit(U256::from(1)), 0);
        }

        #[test]
        fn test_msb_for_2() {
            assert_eq!(most_significant_bit(U256::from(2)), 1);
        }

        #[test]
        fn test_msb_for_max() {
            assert_eq!(most_significant_bit(U256::MAX), 255);
        }
    }

    mod least_significant_bit {
        use super::*;

        #[test]
        fn test_lsb_at_powers_of_two() {
            for i in 0..255 {
                let a = U256::from(1) << i;
                assert_eq!(least_significant_bit(a), i);
            }
        }

        #[test]
        #[should_panic]
        fn test_lsb_for_0() {
            least_significant_bit(U256::default());
        }

        #[test]
        fn test_lsb_for_1() {
            assert_eq!(least_significant_bit(U256::from(1)), 0);
        }

        #[test]
        fn test_lsb_for_2() {
            assert_eq!(least_significant_bit(U256::from(2)), 1);
        }

        #[test]
        fn test_lsb_for_max() {
            assert_eq!(least_significant_bit(U256::MAX), 0);
        }
    }
}