From 1b107700cf0c1ac39a3fce8409c5caae9bf78bb7 Mon Sep 17 00:00:00 2001 From: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> Date: Mon, 1 Jan 2024 00:59:42 -0800 Subject: [PATCH] Convert functions to `const` in math and tick utils Functions in the `sqrt_price_math.rs` and `nearest_usable_tick.rs` files, as well as the `constants.rs` file, were changed from regular to `const` functions. This provides the capacity to have these functions evaluated at compile time wherever their usage throughout the codebase makes it possible for constant evaluation. Also, updated the tick comparison in `nearest_usable_tick.rs` which ensures more readability. --- src/constants.rs | 2 +- src/utils/nearest_usable_tick.rs | 4 ++-- src/utils/sqrt_price_math.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index acd0e35..aac627c 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -18,7 +18,7 @@ pub enum FeeAmount { impl FeeAmount { /// The default factory tick spacings by fee amount. - pub fn tick_spacing(&self) -> i32 { + pub const fn tick_spacing(&self) -> i32 { match self { Self::LOWEST => 1, Self::LOW => 10, diff --git a/src/utils/nearest_usable_tick.rs b/src/utils/nearest_usable_tick.rs index 11d3d0b..55a54f8 100644 --- a/src/utils/nearest_usable_tick.rs +++ b/src/utils/nearest_usable_tick.rs @@ -9,9 +9,9 @@ use super::tick_math::{MAX_TICK, MIN_TICK}; /// /// returns: i32 /// -pub fn nearest_usable_tick(tick: i32, tick_spacing: i32) -> i32 { +pub const fn nearest_usable_tick(tick: i32, tick_spacing: i32) -> i32 { assert!(tick_spacing > 0, "TICK_SPACING"); - assert!((MIN_TICK..=MAX_TICK).contains(&tick), "TICK_BOUND"); + assert!(tick >= MIN_TICK && tick <= MAX_TICK, "TICK_BOUND"); let rounded = tick.div_floor(tick_spacing) * tick_spacing; let rounded = rounded + (tick - rounded + tick_spacing / 2) / tick_spacing * tick_spacing; if rounded < MIN_TICK { diff --git a/src/utils/sqrt_price_math.rs b/src/utils/sqrt_price_math.rs index 9da123e..d4cbd25 100644 --- a/src/utils/sqrt_price_math.rs +++ b/src/utils/sqrt_price_math.rs @@ -17,7 +17,7 @@ fn to_uint160(x: U256) -> Result { } } -fn to_uint256(x: u128) -> U256 { +const fn to_uint256(x: u128) -> U256 { U256::from_limbs([x as u64, (x >> 64) as u64, 0, 0]) }