Skip to content

Commit fe1b84b

Browse files
committed
feat(math): add clamp function
1 parent e195542 commit fe1b84b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

packages/utils/src/math/utils.cairo

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,23 @@ impl SameSignImpl<
154154
}
155155
}
156156

157+
pub trait Clamp<T> {
158+
fn clamp(self: T, min: T, max: T) -> T;
159+
}
160+
161+
impl ClampImpl<T, +PartialOrd<T>, +Drop<T>, +Copy<T>> of Clamp<T> {
162+
fn clamp(self: T, min: T, max: T) -> T {
163+
assert!(min <= max, "min must be less than or equal to max");
164+
if self < min {
165+
min
166+
} else if self > max {
167+
max
168+
} else {
169+
self
170+
}
171+
}
172+
}
173+
157174
#[cfg(test)]
158175
mod tests {
159176
use starkware_utils::constants::{MAX_U128, MAX_U64};
@@ -415,4 +432,18 @@ mod tests {
415432
let num6: u64 = 0;
416433
assert_eq!(num5.same_sign(num6), true, "same_sign failed");
417434
}
435+
436+
#[test]
437+
fn clamp_test() {
438+
assert_eq!(10_u64.clamp(0_u64, 20_u64), 10_u64, "clamp failed");
439+
assert_eq!((-10_i64).clamp(0_i64, 20_i64), 0_i64, "clamp failed");
440+
assert_eq!(30_i64.clamp(0_i64, 20_i64), 20_i64, "clamp failed");
441+
assert_eq!(10_u256.clamp(20_u256, 20_u256), 20_u256, "clamp failed");
442+
}
443+
444+
#[test]
445+
#[should_panic(expected: "min must be less than or equal to max")]
446+
fn clamp_test_panic() {
447+
10_i64.clamp(20_i64, 0_i64);
448+
}
418449
}

0 commit comments

Comments
 (0)