From 2dba500a175d257cedc5856ab421eb1d7271d58f Mon Sep 17 00:00:00 2001 From: gaetbout Date: Mon, 5 Aug 2024 18:18:51 +0200 Subject: [PATCH] generic SHR --- packages/math/src/lib.cairo | 33 ++++++--------------------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/packages/math/src/lib.cairo b/packages/math/src/lib.cairo index 58d832e8..751ac0e3 100644 --- a/packages/math/src/lib.cairo +++ b/packages/math/src/lib.cairo @@ -63,59 +63,43 @@ fn count_digits_of_base(mut num: u128, base: u128) -> u128 { res } -pub trait BitShift { +pub trait BitShift< + T, +Sub, +Mul, +Div, +Rem, +PartialEq, +Into, +Drop, +Copy, +> { fn shl(x: T, n: T) -> T; - fn shr(x: T, n: T) -> T; + fn shr(x: T, n: T) -> T { + x / pow(2_u8.into(), n) + } } pub impl U8BitShift of BitShift { fn shl(x: u8, n: u8) -> u8 { (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } - - fn shr(x: u8, n: u8) -> u8 { - x / pow(2, n) - } } pub impl U16BitShift of BitShift { fn shl(x: u16, n: u16) -> u16 { (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } - - fn shr(x: u16, n: u16) -> u16 { - x / pow(2, n) - } } pub impl U32BitShift of BitShift { fn shl(x: u32, n: u32) -> u32 { (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } - - fn shr(x: u32, n: u32) -> u32 { - x / pow(2, n) - } } pub impl U64BitShift of BitShift { fn shl(x: u64, n: u64) -> u64 { (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } - - fn shr(x: u64, n: u64) -> u64 { - x / pow(2, n) - } } pub impl U128BitShift of BitShift { fn shl(x: u128, n: u128) -> u128 { WideMul::wide_mul(x, pow(2, n)).low } - - fn shr(x: u128, n: u128) -> u128 { - x / pow(2, n) - } } pub impl U256BitShift of BitShift { @@ -123,13 +107,8 @@ pub impl U256BitShift of BitShift { let (r, _) = x.overflowing_mul(pow(2, n)); r } - - fn shr(x: u256, n: u256) -> u256 { - x / pow(2, n) - } } -// TODO Can prob make a generic version of this, Need to know how this Target type works. /// Rotate the bits of an unsigned integer of type T trait BitRotate { /// Take the bits of an unsigned integer and rotate in the left direction