Skip to content

Commit

Permalink
From<u8> for u16 implementation (#5815)
Browse files Browse the repository at this point in the history
## Description
Adds From<u8> for u16

Partially addresses #5797

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: IGI-111 <igi-111@protonmail.com>
  • Loading branch information
SwayStar123 and IGI-111 committed Apr 2, 2024
1 parent 73fd7ec commit 343bc34
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion sway-lib-std/src/primitive_conversions/u16.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 u16 {
Expand All @@ -15,6 +15,28 @@ impl u16 {
}
}

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

impl TryFrom<u32> for u16 {
fn try_from(u: u32) -> Option<Self> {
if u > u16::max().as_u32() {
Expand Down Expand Up @@ -59,6 +81,20 @@ impl TryFrom<u256> for u16 {
}
}

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

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

let u16_1 = u16::from(u8_1);
let u16_2 = u16::from(u8_2);

assert(u16_1 == 0u16);
assert(u16_2 == 255u16);
}

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

0 comments on commit 343bc34

Please sign in to comment.