Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TryInto<u512, u256> #5031

Merged
merged 9 commits into from
Feb 14, 2024
Merged
10 changes: 10 additions & 0 deletions corelib/src/integer.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,16 @@ extern fn u512_safe_divmod_by_u256(
U128MulGuarantee
) implicits(RangeCheck) nopanic;

impl U512TryIntoU256 of TryInto<u512, u256> {
fn try_into(self: u512) -> Option<u256> {
if self.limb2 != 0 || self.limb3 != 0 {
Option::None
} else {
Option::Some(u256 { low: self.limb0, high: self.limb1 })
}
}
}

/// Bounded
pub trait BoundedInt<T> {
#[must_use]
Expand Down
11 changes: 11 additions & 0 deletions corelib/src/test/integer_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,17 @@ fn test_u512_safe_div_rem_by_u256() {
assert(r == 0x1e0eb905027d0150d2618bbd71844d50, 'large rem failed');
}

#[test]
fn test_u512_try_into_u256() {
assert!(
u512 { limb0: 1, limb1: 2, limb2: 0, limb3: 0 }
.try_into() == Option::Some(0x200000000000000000000000000000001_u256)
);
assert!(u512 { limb0: 1, limb1: 2, limb2: 3, limb3: 0 }.try_into() == Option::<u256>::None);
assert!(u512 { limb0: 1, limb1: 2, limb2: 0, limb3: 4 }.try_into() == Option::<u256>::None);
assert!(u512 { limb0: 1, limb1: 2, limb2: 3, limb3: 4 }.try_into() == Option::<u256>::None);
}

#[test]
fn test_min() {
let min_u8: u8 = BoundedInt::min();
Expand Down
Loading