diff --git a/src/value.rs b/src/value.rs index 908829b..a9eef23 100644 --- a/src/value.rs +++ b/src/value.rs @@ -175,6 +175,18 @@ impl RuntimeValue { } } +impl From for RuntimeValue { + fn from(val: i8) -> Self { + RuntimeValue::I32(val as i32) + } +} + +impl From for RuntimeValue { + fn from(val: i16) -> Self { + RuntimeValue::I32(val as i32) + } +} + impl From for RuntimeValue { fn from(val: i32) -> Self { RuntimeValue::I32(val) @@ -187,6 +199,18 @@ impl From for RuntimeValue { } } +impl From for RuntimeValue { + fn from(val: u8) -> Self { + RuntimeValue::I32(val as i32) + } +} + +impl From for RuntimeValue { + fn from(val: u16) -> Self { + RuntimeValue::I32(val as i32) + } +} + impl From 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 { + 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 { + 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 { + 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 { + 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);