diff --git a/sway-lib-std/src/u128.sw b/sway-lib-std/src/u128.sw index 8bb53376064..a7fe70523a8 100644 --- a/sway-lib-std/src/u128.sw +++ b/sway-lib-std/src/u128.sw @@ -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 @@ -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 diff --git a/test/src/in_language_tests/test_programs/u128_inline_tests/src/main.sw b/test/src/in_language_tests/test_programs/u128_inline_tests/src/main.sw index 584a1716ad4..4ace0c839f9 100644 --- a/test/src/in_language_tests/test_programs/u128_inline_tests/src/main.sw +++ b/test/src/in_language_tests/test_programs/u128_inline_tests/src/main.sw @@ -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); + } + } +} \ No newline at end of file