implement from and into RuntimeValue for i8, u8, i16 and u16 (#104)

This works under the assumption that these values
are represented as an `I32` in WASM, which seems
reasonable.
This commit is contained in:
Leonardo Yvens 2018-06-25 10:59:30 -03:00 committed by Sergey Pepyakin
parent 75406dd8ff
commit 9db7896e48
1 changed files with 80 additions and 0 deletions

View File

@ -175,6 +175,18 @@ impl RuntimeValue {
}
}
impl From<i8> for RuntimeValue {
fn from(val: i8) -> Self {
RuntimeValue::I32(val as i32)
}
}
impl From<i16> for RuntimeValue {
fn from(val: i16) -> Self {
RuntimeValue::I32(val as i32)
}
}
impl From<i32> for RuntimeValue {
fn from(val: i32) -> Self {
RuntimeValue::I32(val)
@ -187,6 +199,18 @@ impl From<i64> for RuntimeValue {
}
}
impl From<u8> for RuntimeValue {
fn from(val: u8) -> Self {
RuntimeValue::I32(val as i32)
}
}
impl From<u16> for RuntimeValue {
fn from(val: u16) -> Self {
RuntimeValue::I32(val as i32)
}
}
impl From<u32> for RuntimeValue {
fn from(val: u32) -> Self {
RuntimeValue::I32(val.transmute_into())
@ -237,6 +261,62 @@ impl FromRuntimeValue for bool {
}
}
/// This conversion assumes that `i8` is represented as an [`I32`].
///
/// [`I32`]: enum.RuntimeValue.html#variant.I32
impl FromRuntimeValue for i8 {
fn from_runtime_value(val: RuntimeValue) -> Option<Self> {
let min = i8::min_value() as i32;
let max = i8::max_value() as i32;
match val {
RuntimeValue::I32(val) if min <= val && val <= max => Some(val as i8),
_ => None,
}
}
}
/// This conversion assumes that `i16` is represented as an [`I32`].
///
/// [`I32`]: enum.RuntimeValue.html#variant.I32
impl FromRuntimeValue for i16 {
fn from_runtime_value(val: RuntimeValue) -> Option<Self> {
let min = i16::min_value() as i32;
let max = i16::max_value() as i32;
match val {
RuntimeValue::I32(val) if min <= val && val <= max => Some(val as i16),
_ => None,
}
}
}
/// This conversion assumes that `u8` is represented as an [`I32`].
///
/// [`I32`]: enum.RuntimeValue.html#variant.I32
impl FromRuntimeValue for u8 {
fn from_runtime_value(val: RuntimeValue) -> Option<Self> {
let min = u8::min_value() as i32;
let max = u8::max_value() as i32;
match val {
RuntimeValue::I32(val) if min <= val && val <= max => Some(val as u8),
_ => None,
}
}
}
/// This conversion assumes that `u16` is represented as an [`I32`].
///
/// [`I32`]: enum.RuntimeValue.html#variant.I32
impl FromRuntimeValue for u16 {
fn from_runtime_value(val: RuntimeValue) -> Option<Self> {
let min = u16::min_value() as i32;
let max = u16::max_value() as i32;
match val {
RuntimeValue::I32(val) if min <= val && val <= max => Some(val as u16),
_ => None,
}
}
}
impl_from_runtime_value!(I32, i32);
impl_from_runtime_value!(I64, i64);
impl_from_runtime_value!(F32, F32);