From 1d1ffcc10af0799accab90b996cad87cdf27ad49 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Thu, 21 Nov 2019 15:15:56 +0100 Subject: [PATCH] feat(runtime-core) Implement `TryFrom` for `Value`. --- lib/runtime-core/src/types.rs | 49 ++++++++++++++++------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/lib/runtime-core/src/types.rs b/lib/runtime-core/src/types.rs index 1b19bbc3d91..c894447c875 100644 --- a/lib/runtime-core/src/types.rs +++ b/lib/runtime-core/src/types.rs @@ -2,7 +2,7 @@ //! convert to other represenations. use crate::{memory::MemoryType, module::ModuleInfo, structures::TypedIndex, units::Pages}; -use std::borrow::Cow; +use std::{borrow::Cow, convert::TryFrom}; /// Represents a WebAssembly type. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -67,35 +67,32 @@ impl Value { } } -impl From for Value { - fn from(i: i32) -> Self { - Value::I32(i) - } -} - -impl From for Value { - fn from(i: i64) -> Self { - Value::I64(i) - } -} +macro_rules! value_conversions { + ($native_type:ty, $value_variant:ident) => { + impl From<$native_type> for Value { + fn from(n: $native_type) -> Self { + Self::$value_variant(n) + } + } -impl From for Value { - fn from(f: f32) -> Self { - Value::F32(f) - } -} + impl TryFrom<&Value> for $native_type { + type Error = &'static str; -impl From for Value { - fn from(f: f64) -> Self { - Value::F64(f) - } + fn try_from(value: &Value) -> Result { + match value { + Value::$value_variant(value) => Ok(*value), + _ => Err("Invalid cast."), + } + } + } + }; } -impl From for Value { - fn from(v: u128) -> Self { - Value::V128(v) - } -} +value_conversions!(i32, I32); +value_conversions!(i64, I64); +value_conversions!(f32, F32); +value_conversions!(f64, F64); +value_conversions!(u128, V128); /// Represents a native wasm type. pub unsafe trait NativeWasmType: Copy + Into