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 as_u256 for U128 #6951

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions sway-lib-std/src/u128.sw
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ impl U128 {
}
}

// TODO: Rename to `try_as_u64` to be consistent with all other downcasts
/// Safely downcast to `u64` without loss of precision.
///
/// # Additional Information
Expand Down Expand Up @@ -333,6 +334,27 @@ impl U128 {
}
}

/// Upcasts a `U128` to a `u256`.
///
/// # Returns
///
/// * [u256] - The `u256` representation of the `U128` value.
///
/// # Examples
///
/// ```sway
/// use std::u128::U128;
///
/// fn foo() {
/// let u128_value = U128::from(0u64);
/// let u256_value = u128_value.as_u256();
/// }
pub fn as_u256(self) -> u256 {
asm(nums: (0, 0, self.upper, self.lower)) {
nums: u256
}
}

/// The smallest value that can be represented by this integer type.
///
/// # Returns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1188,3 +1188,39 @@ fn u128_unsafemath_log2() {

set_flags(prior_flags);
}

#[test]
fn u128_as_u256() {
let mut vals = Vec::new();
vals.push(0);
vals.push(1);
vals.push(2);
vals.push(u64::max() - 1);
vals.push(u64::max());

for val in vals.iter() {
// Ensure parity with u256::from(val)
let u128_val = U128::from(val);
let u256_val = u128_val.as_u256();
assert(u256_val == u256::from(val));

// Ensure parity with asm u256 conversion
let asm_val = asm(nums: (0, 0, 0, val)) {
nums: u256
};
assert(u256_val == asm_val);

for val2 in vals.iter() {
// Ensure parity with u256::from(0, 0, val, val2)
let u128_val = U128::from((val, val2));
let u256_val = u128_val.as_u256();
assert(u256_val == u256::from((0, 0, val, val2)));

// Ensure parity with asm u256 conversion
let asm_val = asm(nums: (0, 0, val, val2)) {
nums: u256
};
assert(u256_val == asm_val);
}
}
}
Loading