Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

bit_math.gno

1.35 Kb · 52 lines
 1package gnsmath
 2
 3import (
 4	"math/bits"
 5
 6	u256 "gno.land/p/gnoswap/uint256/v1"
 7)
 8
 9// BitMathMostSignificantBit returns the 0-based position of the most significant bit in x.
10// This function is essential for AMM calculations involving price ranges and tick boundaries.
11//
12// Parameters:
13//   - x: the non-zero value for which to compute the most significant set bit
14//
15// Returns:
16//   - bitIndex: the zero-based position of the most significant set bit (0-255)
17//
18// Panics if x is zero.
19func BitMathMostSignificantBit(x *u256.Uint) uint8 {
20	if x.IsZero() {
21		panic(errMSBZeroInput)
22	}
23
24	return uint8(x.BitLen() - 1)
25}
26
27// BitMathLeastSignificantBit returns the 0-based position of the least significant bit in x.
28// This function is used in AMM calculations for efficient bit manipulation and range queries.
29//
30// Parameters:
31//   - x: the non-zero value for which to compute the least significant set bit
32//
33// Returns:
34//   - bitIndex: the zero-based position of the least significant set bit (0-255)
35//
36// Panics if x is zero.
37func BitMathLeastSignificantBit(x *u256.Uint) uint8 {
38	if x.IsZero() {
39		panic(errLSBZeroInput)
40	}
41
42	if x[0] != 0 {
43		return uint8(bits.TrailingZeros64(x[0]))
44	}
45	if x[1] != 0 {
46		return uint8(64 + bits.TrailingZeros64(x[1]))
47	}
48	if x[2] != 0 {
49		return uint8(128 + bits.TrailingZeros64(x[2]))
50	}
51	return uint8(192 + bits.TrailingZeros64(x[3]))
52}