tp_runtime_interface/
host.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 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//! Traits required by the runtime interface from the host side.
19
20use crate::RIType;
21
22use tetcore_wasm_interface::{FunctionContext, Result};
23
24/// Something that can be converted into a ffi value.
25pub trait IntoFFIValue: RIType {
26	/// Convert `self` into a ffi value.
27	fn into_ffi_value(self, context: &mut dyn FunctionContext) -> Result<Self::FFIType>;
28}
29
30/// Something that can be converted into a preallocated ffi value.
31///
32/// Every type parameter that should be given as `&mut` into a runtime interface function, needs
33/// to implement this trait. After executing the host implementation of the runtime interface
34/// function, the value is copied into the preallocated wasm memory.
35///
36/// This should only be used for types which have a fixed size, like slices. Other types like a vec
37/// do not work with this interface, as we can not call into wasm to reallocate memory. So, this
38/// trait should be implemented carefully.
39pub trait IntoPreallocatedFFIValue: RIType {
40	/// As `Self` can be an unsized type, it needs to be represented by a sized type at the host.
41	/// This `SelfInstance` is the sized type.
42	type SelfInstance;
43
44	/// Convert `self_instance` into the given preallocated ffi value.
45	fn into_preallocated_ffi_value(
46		self_instance: Self::SelfInstance,
47		context: &mut dyn FunctionContext,
48		allocated: Self::FFIType,
49	) -> Result<()>;
50}
51
52/// Something that can be created from a ffi value.
53/// Implementations are safe to assume that the `arg` given to `from_ffi_value`
54/// is only generated by the corresponding [`wasm::IntoFFIValue`](crate::wasm::IntoFFIValue)
55/// implementation.
56pub trait FromFFIValue: RIType {
57	/// As `Self` can be an unsized type, it needs to be represented by a sized type at the host.
58	/// This `SelfInstance` is the sized type.
59	type SelfInstance;
60
61	/// Create `SelfInstance` from the given
62	fn from_ffi_value(
63		context: &mut dyn FunctionContext,
64		arg: Self::FFIType,
65	) -> Result<Self::SelfInstance>;
66}