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 conversion methods for u256,b256 from tuple of u64s #5889

Merged
merged 11 commits into from
Apr 29, 2024
36 changes: 36 additions & 0 deletions sway-lib-std/src/primitive_conversions/b256.sw
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@ impl From<u256> for b256 {
}
}

impl From<(u64, u64, u64, u64)> for b256 {
/// Casts a tuple of 4 `u64` values to a `b256`.
///
/// # Arguments
///
/// * `nums`: (u64, u64, u64, u64) - The tuple of `u64` values to be casted.
///
/// # Returns
///
/// * [b256] - The `b256` representation of the tuple of `u64` values.
///
/// # Examples
///
/// ```sway
///
/// fn foo() {
/// let b256_value = b256::from((1, 2, 3, 4));
/// }
/// ```
fn from(nums: (u64, u64, u64, u64)) -> Self {
asm(nums: nums) {
nums: b256
}
}
}

#[test]
fn test_b256_try_from_bytes() {
use ::assert::assert;
Expand Down Expand Up @@ -76,3 +102,13 @@ fn test_b256_from_u256() {
let res = b256::from(val);
assert(res == 0x0000000000000000000000000000000000000000000000000000000000000000);
}

#[test]
fn test_b256_from_tuple() {
use ::assert::assert;

let b256_value = <b256 as From<(u64, u64, u64, u64)>>::from((1, 2, 3, 4));
assert(
b256_value == 0x0000000000000001000000000000000200000000000000030000000000000004,
);
}
36 changes: 36 additions & 0 deletions sway-lib-std/src/primitive_conversions/u256.sw
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,32 @@ impl From<b256> for u256 {
}
}

impl From<(u64, u64, u64, u64)> for u256 {
/// Casts a tuple of 4 `u64` values to a `u256`.
///
/// # Arguments
///
/// * `nums`: (u64, u64, u64, u64) - The tuple of `u64` values to be casted.
///
/// # Returns
///
/// * [u256] - The `u256` representation of the tuple of `u64` values.
///
/// # Examples
///
/// ```sway
///
/// fn foo() {
/// let u256_value = u256::from((1, 2, 3, 4));
/// }
/// ```
fn from(nums: (u64, u64, u64, u64)) -> Self {
asm(nums: nums) {
nums: u256
}
}
}

// TODO: Replace <u256 as From<T>> with u256::from when https://github.com/FuelLabs/sway/issues/5798 is resolved.
#[test]
fn test_u256_from_u8() {
Expand Down Expand Up @@ -179,3 +205,13 @@ fn test_u256_from_b256() {
u256_value == 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff_u256,
);
}

#[test]
fn test_u256_from_tuple() {
use ::assert::assert;

let u256_value = <u256 as From<(u64, u64, u64, u64)>>::from((1, 2, 3, 4));
assert(
u256_value == 0x0000000000000001000000000000000200000000000000030000000000000004_u256,
);
}
Loading