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

From<u8, u16> for u32 #5816

Merged
merged 6 commits into from
Apr 3, 2024
Merged
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
75 changes: 74 additions & 1 deletion sway-lib-std/src/primitive_conversions/u32.sw
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
library;

use ::convert::TryFrom;
use ::convert::{From, TryFrom};
use ::option::Option::{self, *};

impl u32 {
Expand All @@ -25,6 +25,50 @@ impl u32 {
}
}

impl From<u8> for u32 {
/// Casts a `u8` to a `u32`.
///
/// # Returns
///
/// * [u32] - The `u32` representation of the `u8` value.
///
/// # Examples
///
/// ```sway
///
/// fn foo() {
/// let u32_value = u32::from(0u8);
/// }
/// ```
fn from(u: u8) -> Self {
asm(r1: u) {
r1: u32
}
}
}

impl From<u16> for u32 {
/// Casts a `u16` to a `u32`.
///
/// # Returns
///
/// * [u32] - The `u32` representation of the `u16` value.
///
/// # Examples
///
/// ```sway
///
/// fn foo() {
/// let u32_value = u32::from(0u16);
/// }
/// ```
fn from(u: u16) -> Self {
asm(r1: u) {
r1: u32
}
}
}

impl TryFrom<u64> for u32 {
fn try_from(u: u64) -> Option<Self> {
if u > u32::max().as_u64() {
Expand Down Expand Up @@ -57,6 +101,35 @@ impl TryFrom<u256> for u32 {
}
}

// TODO: Replace <u32 as From<T>> with u32::from when https://github.com/FuelLabs/sway/issues/5798 is resolved.
#[test]
fn test_u32_from_u8() {
use ::assert::assert;

let u8_1: u8 = 0u8;
let u8_2: u8 = 255u8;

let u32_1 = <u32 as From<u8>>::from(u8_1);
let u32_2 = <u32 as From<u8>>::from(u8_2);

assert(u32_1 == 0u32);
assert(u32_2 == 255u32);
}

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

let u16_1: u16 = 0u16;
let u16_2: u16 = 65535u16;

let u32_1 = <u32 as From<u16>>::from(u16_1);
let u32_2 = <u32 as From<u16>>::from(u16_2);

assert(u32_1 == 0u32);
assert(u32_2 == 65535u32);
}

#[test]
fn test_u32_try_from_u64() {
use ::assert::assert;
Expand Down
Loading