Skip to content

Commit

Permalink
adds alternative implementation for rotate_left on u256
Browse files Browse the repository at this point in the history
  • Loading branch information
sveamarcus committed Nov 9, 2023
1 parent 469c5af commit 74be1ac
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 12 deletions.
8 changes: 2 additions & 6 deletions src/math/src/lib.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -221,12 +221,8 @@ impl U128BitRotate of BitRotate<u128> {

impl U256BitRotate of BitRotate<u256> {
fn rotate_left(x: u256, n: u256) -> u256 {
// TODO(sveamarcus): missing non-zero implementation for u512
// let word = u256_wide_mul(x, pow(2, n));
// let (quotient, remainder) = DivRem::div_rem(word,
// u512_as_non_zero(u512{limb0: 0, limb1: 0, limb2: 1, limb3: 0 }));
// (quotient + remainder).try_into().unwrap()
panic_with_felt252('missing impl')
// Alternative solution since we cannot divide u512 yet
BitShift::shl(x, n) + BitShift::shr(x, 256 - n)
}

fn rotate_right(x: u256, n: u256) -> u256 {
Expand Down
10 changes: 4 additions & 6 deletions src/math/src/tests/math_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -170,27 +170,25 @@ fn shl_should_not_overflow() {
}

#[test]
#[available_gas(2000000)]
#[available_gas(3000000)]
fn test_rotl_min() {
assert(BitRotate::rotate_left(pow::<u8>(2, 7) + 1, 1) == 3, 'invalid result');
assert(BitRotate::rotate_left(pow::<u16>(2, 15) + 1, 1) == 3, 'invalid result');
assert(BitRotate::rotate_left(pow::<u32>(2, 31) + 1, 1) == 3, 'invalid result');
assert(BitRotate::rotate_left(pow::<u64>(2, 63) + 1, 1) == 3, 'invalid result');
assert(BitRotate::rotate_left(pow::<u128>(2, 127) + 1, 1) == 3, 'invalid result');
// TODO(sveamarcus): missing implementation
// assert(BitRotate::rotate_left(pow::<u256>(2, 255) + 1, 1) == 3, 'invalid result');
assert(BitRotate::rotate_left(pow::<u256>(2, 255) + 1, 1) == 3, 'invalid result');
}

#[test]
#[available_gas(2000000)]
#[available_gas(3000000)]
fn test_rotl_max() {
assert(BitRotate::rotate_left(0b101, 7) == pow::<u8>(2, 7) + 0b10, 'invalid result');
assert(BitRotate::rotate_left(0b101, 15) == pow::<u16>(2, 15) + 0b10, 'invalid result');
assert(BitRotate::rotate_left(0b101, 31) == pow::<u32>(2, 31) + 0b10, 'invalid result');
assert(BitRotate::rotate_left(0b101, 63) == pow::<u64>(2, 63) + 0b10, 'invalid result');
assert(BitRotate::rotate_left(0b101, 127) == pow::<u128>(2, 127) + 0b10, 'invalid result');
// TODO(sveamarcus): missing implementation
// assert(BitRotate::rotate_left(0b101, 255) == pow::<u256>(2, 255) + 0b10, 'invalid result');
assert(BitRotate::rotate_left(0b101, 255) == pow::<u256>(2, 255) + 0b10, 'invalid result');
}

#[test]
Expand Down

0 comments on commit 74be1ac

Please sign in to comment.