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, u32> for u64 implementations #5817

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
109 changes: 109 additions & 0 deletions sway-lib-std/src/primitive_conversions/u64.sw
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,72 @@ impl u64 {
}
}

impl From<u8> 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<u16> 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<u32> 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<u256> for u64 {
fn try_from(u: u256) -> Option<Self> {
let parts = asm(r1: u) {
Expand All @@ -49,6 +115,49 @@ impl TryFrom<u256> for u64 {
}
}

// TODO: Replace <u64 as From<T>> 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 = <u64 as From<u8>>::from(u8_1);
let u64_2 = <u64 as From<u8>>::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 = <u64 as From<u16>>::from(u16_1);
let u64_2 = <u64 as From<u16>>::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 = <u64 as From<u32>>::from(u32_1);
let u64_2 = <u64 as From<u32>>::from(u32_2);

assert(u64_1 == 0u64);
assert(u64_2 == 4294967295u64);
}

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