Skip to main content

gsp_wasm_interface_common/
wasmi_impl.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Implementation of conversions between Substrate and wasmi types.
19use crate::{Signature, Value, ValueType};
20use sp_std::vec::Vec;
21
22impl From<Value> for wasmi::RuntimeValue {
23    fn from(value: Value) -> Self {
24        match value {
25            Value::I32(val) => Self::I32(val),
26            Value::I64(val) => Self::I64(val),
27            Value::F32(val) => Self::F32(val.into()),
28            Value::F64(val) => Self::F64(val.into()),
29        }
30    }
31}
32
33impl From<wasmi::RuntimeValue> for Value {
34    fn from(value: wasmi::RuntimeValue) -> Self {
35        match value {
36            wasmi::RuntimeValue::I32(val) => Self::I32(val),
37            wasmi::RuntimeValue::I64(val) => Self::I64(val),
38            wasmi::RuntimeValue::F32(val) => Self::F32(val.into()),
39            wasmi::RuntimeValue::F64(val) => Self::F64(val.into()),
40        }
41    }
42}
43
44impl From<ValueType> for wasmi::ValueType {
45    fn from(value: ValueType) -> Self {
46        match value {
47            ValueType::I32 => Self::I32,
48            ValueType::I64 => Self::I64,
49            ValueType::F32 => Self::F32,
50            ValueType::F64 => Self::F64,
51        }
52    }
53}
54
55impl From<wasmi::ValueType> for ValueType {
56    fn from(value: wasmi::ValueType) -> Self {
57        match value {
58            wasmi::ValueType::I32 => Self::I32,
59            wasmi::ValueType::I64 => Self::I64,
60            wasmi::ValueType::F32 => Self::F32,
61            wasmi::ValueType::F64 => Self::F64,
62        }
63    }
64}
65
66impl From<Signature> for wasmi::Signature {
67    fn from(sig: Signature) -> Self {
68        let args = sig.args.iter().map(|a| (*a).into()).collect::<Vec<_>>();
69        wasmi::Signature::new(args, sig.return_value.map(Into::into))
70    }
71}
72
73impl From<&wasmi::Signature> for Signature {
74    fn from(sig: &wasmi::Signature) -> Self {
75        Signature::new(
76            sig.params()
77                .iter()
78                .copied()
79                .map(Into::into)
80                .collect::<Vec<_>>(),
81            sig.return_type().map(Into::into),
82        )
83    }
84}