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#[cfg(test)]
36mod tests {
37 use rstest::rstest;
38
39 use super::*;
40
41 #[rstest]
42 fn test_most_significant_bit() {
43 for i in 0..=255 {
44 let x = U256::ONE << i;
45 assert_eq!(most_significant_bit(x), i);
46 }
47 for i in 1..=255 {
48 let x = (U256::ONE << i) - U256::ONE;
49 assert_eq!(most_significant_bit(x), i - 1);
50 }
51 assert_eq!(most_significant_bit(U256::MAX), 255);
52 }
53
54 #[rstest]
55 fn test_least_significant_bit() {
56 for i in 0..=255 {
57 let x = U256::ONE << i;
58 assert_eq!(least_significant_bit(x), i);
59 }
60 for i in 1..=255 {
61 let x = (U256::ONE << i) - U256::ONE;
62 assert_eq!(least_significant_bit(x), 0);
63 }
64 assert_eq!(least_significant_bit(U256::MAX), 0);
65 }
66}