sp_runtime_interface/host.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//! Traits required by the runtime interface from the host side.
19
20use crate::RIType;
21
22use sp_wasm_interface::{FunctionContext, Result};
23
24/// A type used as a return value in a host function. Can be turned into an FFI value.
25pub trait IntoFFIValue: RIType {
26 /// Convert `Self::Inner` into an FFI value.
27 fn into_ffi_value(
28 value: Self::Inner,
29 context: &mut dyn FunctionContext,
30 ) -> Result<Self::FFIType>;
31}
32
33/// A type used as a parameter in a host function. Can be created from an FFI value.
34///
35/// Implementations are safe to assume that the `arg` given to `from_ffi_value`
36/// is only generated by the corresponding [`wasm::IntoFFIValue`](crate::wasm::IntoFFIValue)
37/// implementation.
38pub trait FromFFIValue<'a>: RIType {
39 /// The owned inner type.
40 type Owned;
41
42 /// Creates `Self::Owned` from the given `arg` received through the FFI boundary from the
43 /// runtime.
44 fn from_ffi_value(context: &mut dyn FunctionContext, arg: Self::FFIType)
45 -> Result<Self::Owned>;
46
47 /// Creates `Self::Inner` from an owned value.
48 fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner;
49
50 /// Write back a modified `value` back into the runtime's memory.
51 ///
52 /// Only makes sense for parameters like e.g. `&mut [u8]`.
53 #[inline]
54 fn write_back_into_runtime(
55 _value: Self::Owned,
56 _context: &mut dyn FunctionContext,
57 _arg: Self::FFIType,
58 ) -> Result<()> {
59 // Default dummy implementation, because the vast majority of impls won't need this.
60 Ok(())
61 }
62}