File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff 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)]
158175mod tests {
159176 use starkware_utils :: constants :: {MAX_U128 , MAX_U64 };
@@ -415,4 +432,17 @@ 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+ }
442+
443+ #[test]
444+ #[should_panic(expected: " min must be less than or equal to max" )]
445+ fn clamp_test_panic () {
446+ 10_i64 . clamp (20_i64 , 0_i64 );
447+ }
418448}
You can’t perform that action at this time.
0 commit comments