subsoil 0.2.0

Soil primitives foundation crate
Documentation
// This file is part of Soil.

// Copyright (C) Soil contributors.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later WITH Classpath-exception-2.0

//! Traits required by the runtime interface from the host side.

use super::RIType;

use crate::wasm_interface::{FunctionContext, Result};

/// A type used as a return value in a host function. Can be turned into an FFI value.
pub trait IntoFFIValue: RIType {
	/// Convert `Self::Inner` into an FFI value.
	fn into_ffi_value(
		value: Self::Inner,
		context: &mut dyn FunctionContext,
	) -> Result<Self::FFIType>;
}

/// A type used as a parameter in a host function. Can be created from an FFI value.
///
/// Implementations are safe to assume that the `arg` given to `from_ffi_value`
/// is only generated by the corresponding [`wasm::IntoFFIValue`](super::wasm::IntoFFIValue)
/// implementation.
pub trait FromFFIValue<'a>: RIType {
	/// The owned inner type.
	type Owned;

	/// Creates `Self::Owned` from the given `arg` received through the FFI boundary from the
	/// runtime.
	fn from_ffi_value(context: &mut dyn FunctionContext, arg: Self::FFIType)
		-> Result<Self::Owned>;

	/// Creates `Self::Inner` from an owned value.
	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner;

	/// Write back a modified `value` back into the runtime's memory.
	///
	/// Only makes sense for parameters like e.g. `&mut [u8]`.
	#[inline]
	fn write_back_into_runtime(
		_value: Self::Owned,
		_context: &mut dyn FunctionContext,
		_arg: Self::FFIType,
	) -> Result<()> {
		// Default dummy implementation, because the vast majority of impls won't need this.
		Ok(())
	}
}