diff --git a/sway-lib-std/src/primitive_conversions/u64.sw b/sway-lib-std/src/primitive_conversions/u64.sw index b4a400c1bd1..fd4e98b4a86 100644 --- a/sway-lib-std/src/primitive_conversions/u64.sw +++ b/sway-lib-std/src/primitive_conversions/u64.sw @@ -35,6 +35,72 @@ impl u64 { } } +impl From for u64 { + /// Casts a `u8` to a `u64`. + /// + /// # Returns + /// + /// * [u64] - The `u64` representation of the `u8` value. + /// + /// # Examples + /// + /// ```sway + /// + /// fn foo() { + /// let u64_value = u64::from(0u8); + /// } + /// ``` + fn from(u: u8) -> Self { + asm(r1: u) { + r1: u64 + } + } +} + +impl From for u64 { + /// Casts a `u16` to a `u64`. + /// + /// # Returns + /// + /// * [u64] - The `u64` representation of the `u16` value. + /// + /// # Examples + /// + /// ```sway + /// + /// fn foo() { + /// let u64_value = u64::from(0u16); + /// } + /// ``` + fn from(u: u16) -> Self { + asm(r1: u) { + r1: u64 + } + } +} + +impl From for u64 { + /// Casts a `u32` to a `u64`. + /// + /// # Returns + /// + /// * [u64] - The `u64` representation of the `u32` value. + /// + /// # Examples + /// + /// ```sway + /// + /// fn foo() { + /// let u64_value = u64::from(0u32); + /// } + /// ``` + fn from(u: u32) -> Self { + asm(r1: u) { + r1: u64 + } + } +} + impl TryFrom for u64 { fn try_from(u: u256) -> Option { let parts = asm(r1: u) { @@ -49,6 +115,49 @@ impl TryFrom for u64 { } } +// TODO: Replace > with u64::from when https://github.com/FuelLabs/sway/issues/5798 is resolved. +#[test] +fn test_u64_from_u8() { + use ::assert::assert; + + let u8_1: u8 = 0u8; + let u8_2: u8 = 255u8; + + let u64_1 = >::from(u8_1); + let u64_2 = >::from(u8_2); + + assert(u64_1 == 0u64); + assert(u64_2 == 255u64); +} + +#[test] +fn test_u64_from_u16() { + use ::assert::assert; + + let u16_1: u16 = 0u16; + let u16_2: u16 = 65535u16; + + let u64_1 = >::from(u16_1); + let u64_2 = >::from(u16_2); + + assert(u64_1 == 0u64); + assert(u64_2 == 65535u64); +} + +#[test] +fn test_u64_from_u32() { + use ::assert::assert; + + let u32_1: u32 = 0u32; + let u32_2: u32 = 4294967295u32; + + let u64_1 = >::from(u32_1); + let u64_2 = >::from(u32_2); + + assert(u64_1 == 0u64); + assert(u64_2 == 4294967295u64); +} + #[test] fn test_u64_try_from_u256() { use ::assert::assert;