nautilus_model/defi/tick_map/
bit_math.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use alloy_primitives::U256;
17
18/// Returns the position of the most significant bit (highest set bit) in a U256 number.
19pub fn most_significant_bit(x: U256) -> i32 {
20    if x.is_zero() {
21        return 0;
22    }
23
24    255 - x.leading_zeros() as i32
25}
26
27/// Returns the position of the least significant bit (lowest set bit) in a U256 number.
28pub fn least_significant_bit(x: U256) -> i32 {
29    if x.is_zero() {
30        return 0;
31    }
32    x.trailing_zeros() as i32
33}
34
35////////////////////////////////////////////////////////////////////////////////
36// Tests
37////////////////////////////////////////////////////////////////////////////////
38
39#[cfg(test)]
40mod tests {
41    use rstest::rstest;
42
43    use super::*;
44
45    #[rstest]
46    fn test_most_significant_bit() {
47        for i in 0..=255 {
48            let x = U256::ONE << i;
49            assert_eq!(most_significant_bit(x), i);
50        }
51        for i in 1..=255 {
52            let x = (U256::ONE << i) - U256::ONE;
53            assert_eq!(most_significant_bit(x), i - 1);
54        }
55        assert_eq!(most_significant_bit(U256::MAX), 255);
56    }
57
58    #[rstest]
59    fn test_least_significant_bit() {
60        for i in 0..=255 {
61            let x = U256::ONE << i;
62            assert_eq!(least_significant_bit(x), i);
63        }
64        for i in 1..=255 {
65            let x = (U256::ONE << i) - U256::ONE;
66            assert_eq!(least_significant_bit(x), 0);
67        }
68        assert_eq!(least_significant_bit(U256::MAX), 0);
69    }
70}