diff --git a/sway-lib-std/src/primitive_conversions/u32.sw b/sway-lib-std/src/primitive_conversions/u32.sw index 0a44d8e3090..99f88ec7671 100644 --- a/sway-lib-std/src/primitive_conversions/u32.sw +++ b/sway-lib-std/src/primitive_conversions/u32.sw @@ -1,6 +1,6 @@ library; -use ::convert::TryFrom; +use ::convert::{From, TryFrom}; use ::option::Option::{self, *}; impl u32 { @@ -25,6 +25,50 @@ impl u32 { } } +impl From 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 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 for u32 { fn try_from(u: u64) -> Option { if u > u32::max().as_u64() { @@ -57,6 +101,35 @@ impl TryFrom for u32 { } } +// TODO: Replace > 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 = >::from(u8_1); + let u32_2 = >::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 = >::from(u16_1); + let u32_2 = >::from(u16_2); + + assert(u32_1 == 0u32); + assert(u32_2 == 65535u32); +} + #[test] fn test_u32_try_from_u64() { use ::assert::assert;