Skip to content

Commit

Permalink
Add TryInto<u512, u256> (#5031)
Browse files Browse the repository at this point in the history
Co-authored-by: Marek Kaput <[email protected]>
Co-authored-by: Gil Ben-Shachar <[email protected]>
Co-authored-by: ilyalesokhin-starkware <[email protected]>
Co-authored-by: yuvalsw <[email protected]>
  • Loading branch information
5 people authored Feb 14, 2024
1 parent c20ac70 commit 1ac6771
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
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

0 comments on commit 1ac6771

Please sign in to comment.