nautilus_model/defi/tick_map/bit_math.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2026 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.
19#[must_use]
20pub fn most_significant_bit(x: U256) -> i32 {
21 if x.is_zero() {
22 return 0;
23 }
24
25 255 - x.leading_zeros() as i32
26}
27
28/// Returns the position of the least significant bit (lowest set bit) in a U256 number.
29#[must_use]
30pub fn least_significant_bit(x: U256) -> i32 {
31 if x.is_zero() {
32 return 0;
33 }
34 x.trailing_zeros() as i32
35}
36
37#[cfg(test)]
38mod tests {
39 use rstest::rstest;
40
41 use super::*;
42
43 #[rstest]
44 fn test_most_significant_bit() {
45 for i in 0..=255 {
46 let x = U256::ONE << i;
47 assert_eq!(most_significant_bit(x), i);
48 }
49
50 for i in 1..=255 {
51 let x = (U256::ONE << i) - U256::ONE;
52 assert_eq!(most_significant_bit(x), i - 1);
53 }
54 assert_eq!(most_significant_bit(U256::MAX), 255);
55 }
56
57 #[rstest]
58 fn test_least_significant_bit() {
59 for i in 0..=255 {
60 let x = U256::ONE << i;
61 assert_eq!(least_significant_bit(x), i);
62 }
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}