repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/import/operations.rs | linera-witty/test-modules/src/import/operations.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper Wasm module that calls some functions that have two parameters and one return value.
#![cfg_attr(target_arch = "wasm32", no_main)]
wit_bindgen::generate!("import-operations");
export_import_operations!(Implementation);
use self::{
exports::witty_macros::test_modules::entrypoint::Entrypoint,
witty_macros::test_modules::operations::*,
};
struct Implementation;
impl Entrypoint for Implementation {
#[expect(clippy::bool_assert_comparison)]
fn entrypoint() {
assert_eq!(and_bool(true, true), true);
assert_eq!(and_bool(true, false), false);
assert_eq!(add_s8(-100, 40), -60);
assert_eq!(add_u8(201, 32), 233);
assert_eq!(add_s16(-20_000, 30_000), 10_000);
assert_eq!(add_u16(50_000, 256), 50_256);
assert_eq!(add_s32(-2_000_000, -1), -2_000_001);
assert_eq!(add_u32(4_000_000, 1), 4_000_001);
assert_eq!(add_s64(-16_000_000, 32_000_000), 16_000_000);
assert_eq!(add_u64(3_000_000_000, 9_345_678_999), 12_345_678_999);
assert_eq!(add_float32(10.5, 120.25), 130.75);
assert_eq!(add_float64(-0.000_08, 1.0), 0.999_92);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/import/setters.rs | linera-witty/test-modules/src/import/setters.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper Wasm module that calls some functions that have one parameter and no return values.
#![cfg_attr(target_arch = "wasm32", no_main)]
wit_bindgen::generate!("import-setters");
export_import_setters!(Implementation);
use self::{
exports::witty_macros::test_modules::entrypoint::Entrypoint,
witty_macros::test_modules::setters::*,
};
struct Implementation;
impl Entrypoint for Implementation {
fn entrypoint() {
set_bool(false);
set_s8(-100);
set_u8(201);
set_s16(-20_000);
set_u16(50_000);
set_s32(-2_000_000);
set_u32(4_000_000);
set_float32(10.4);
set_float64(-0.000_08);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/import/getters.rs | linera-witty/test-modules/src/import/getters.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper Wasm module that calls some functions that have no parameters but return values.
#![cfg_attr(target_arch = "wasm32", no_main)]
wit_bindgen::generate!("import-getters");
export_import_getters!(Implementation);
use self::{
exports::witty_macros::test_modules::entrypoint::Entrypoint,
witty_macros::test_modules::getters::*,
};
struct Implementation;
impl Entrypoint for Implementation {
#[expect(clippy::bool_assert_comparison)]
fn entrypoint() {
assert_eq!(get_true(), true);
assert_eq!(get_false(), false);
assert_eq!(get_s8(), -125);
assert_eq!(get_u8(), 200);
assert_eq!(get_s16(), -410);
assert_eq!(get_u16(), 60_000);
assert_eq!(get_s32(), -100_000);
assert_eq!(get_u32(), 3_000_111);
assert_eq!(get_float32(), -0.125);
assert_eq!(get_float64(), 128.25);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/import/simple_function.rs | linera-witty/test-modules/src/import/simple_function.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper Wasm module that calls a minimal function without parameters or return values.
#![cfg_attr(target_arch = "wasm32", no_main)]
wit_bindgen::generate!("import-simple-function");
export_import_simple_function!(Implementation);
use self::{
exports::witty_macros::test_modules::entrypoint::Entrypoint,
witty_macros::test_modules::simple_function::*,
};
struct Implementation;
impl Entrypoint for Implementation {
fn entrypoint() {
simple();
}
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/test.rs | linera-witty/src/test.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Functions and types useful for writing tests.
use std::{collections::BTreeMap, fmt::Debug};
use crate::{
wit_generation::WitInterface, InstanceWithMemory, Layout, MockInstance, RegisterWitTypes,
WitLoad, WitStore,
};
/// Test storing an instance of `T` to memory, checking that the instance can be loaded from those
/// bytes.
///
/// Also checks if storing the loaded instance results in exactly the same bytes in
/// memory.
pub fn test_memory_roundtrip<T>(input: &T) -> anyhow::Result<()>
where
T: Debug + Eq + WitLoad + WitStore,
{
let mut first_instance = MockInstance::<()>::default();
let mut first_memory = first_instance.memory()?;
let first_address = first_memory.allocate(T::SIZE, <T::Layout as Layout>::ALIGNMENT)?;
input.store(&mut first_memory, first_address)?;
let loaded_instance = T::load(&first_memory, first_address)?;
assert_eq!(&loaded_instance, input);
// Create a clean separate memory instance
let mut second_instance = MockInstance::<()>::default();
let mut second_memory = second_instance.memory()?;
let second_address = second_memory.allocate(T::SIZE, <T::Layout as Layout>::ALIGNMENT)?;
loaded_instance.store(&mut second_memory, second_address)?;
let total_allocated_memory = first_memory.allocate(0, 1)?.0;
assert_eq!(
first_memory.read(first_address, total_allocated_memory)?,
second_memory.read(second_address, total_allocated_memory)?
);
Ok(())
}
/// Test lowering an instance of `T`, checking that the resulting flat layout matches the expected
/// `flat_layout`, and check that the instance can be lifted from that flat layout.
pub fn test_flattening_roundtrip<T>(input: &T) -> anyhow::Result<()>
where
T: Debug + Eq + WitLoad + WitStore,
<T::Layout as Layout>::Flat: Copy + Debug + Eq,
{
let mut first_instance = MockInstance::<()>::default();
let mut first_memory = first_instance.memory()?;
let first_start_address = first_memory.allocate(0, 1)?;
let first_lowered_layout = input.lower(&mut first_memory)?;
let lifted_instance = T::lift_from(first_lowered_layout, &first_memory)?;
assert_eq!(&lifted_instance, input);
// Create a clean separate memory instance
let mut second_instance = MockInstance::<()>::default();
let mut second_memory = second_instance.memory()?;
let second_start_address = second_memory.allocate(0, 1)?;
let second_lowered_layout = lifted_instance.lower(&mut second_memory)?;
assert_eq!(first_lowered_layout, second_lowered_layout);
let total_allocated_memory = first_memory.allocate(0, 1)?.0;
assert_eq!(
first_memory.read(first_start_address, total_allocated_memory)?,
second_memory.read(second_start_address, total_allocated_memory)?
);
Ok(())
}
/// Asserts that the WIT type dependencies of the `Interface` are the `expected_types`.
pub fn assert_interface_dependencies<'i, Interface>(
expected_types: impl IntoIterator<Item = (&'i str, &'i str)>,
) where
Interface: WitInterface,
{
let mut wit_types = BTreeMap::new();
Interface::Dependencies::register_wit_types(&mut wit_types);
assert_eq!(
wit_types
.iter()
.map(|(name, declaration)| (name.as_str(), declaration.as_str()))
.collect::<Vec<_>>(),
expected_types.into_iter().collect::<Vec<_>>(),
);
}
/// Asserts that the function declarations of the `Interface` are the `expected_declarations`.
pub fn assert_interface_functions<Interface>(expected_declarations: &[impl AsRef<str>])
where
Interface: WitInterface,
{
let wit_functions = Interface::wit_functions();
assert_eq!(
wit_functions.iter().map(String::as_str).collect::<Vec<_>>(),
expected_declarations
.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>()
);
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/lib.rs | linera-witty/src/lib.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Linera Witty
//!
//! This crate allows generating [WIT] files and host side code to interface with WebAssembly guests
//! that adhere to the [WIT] interface format. The source of truth for the generated code and WIT
//! files is the Rust source code.
//!
//! [WIT]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md
#![deny(missing_docs)]
#[macro_use]
mod macro_utils;
mod exported_function_interface;
mod imported_function_interface;
mod memory_layout;
mod primitive_types;
mod runtime;
#[cfg(with_testing)]
pub mod test;
mod type_traits;
mod util;
pub mod wit_generation;
pub use frunk::{hlist, hlist::HList, hlist_pat, HCons, HList, HNil};
#[cfg(with_wit_export)]
pub use linera_witty_macros::wit_export;
#[cfg(with_macros)]
pub use linera_witty_macros::{wit_import, WitLoad, WitStore, WitType};
#[cfg(with_wasmer)]
pub use self::runtime::wasmer;
#[cfg(with_wasmtime)]
pub use self::runtime::wasmtime;
#[cfg(with_testing)]
pub use self::runtime::{MockExportedFunction, MockInstance, MockResults, MockRuntime};
pub use self::{
exported_function_interface::{ExportFunction, ExportTo, ExportedFunctionInterface},
imported_function_interface::ImportedFunctionInterface,
memory_layout::{JoinFlatLayouts, Layout},
runtime::{
GuestPointer, Instance, InstanceWithFunction, InstanceWithMemory, Memory, Runtime,
RuntimeError, RuntimeMemory,
},
type_traits::{RegisterWitTypes, WitLoad, WitStore, WitType},
util::{Merge, Split},
};
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/macro_utils.rs | linera-witty/src/macro_utils.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Common macros used by other macros.
/// Repeats a `macro` call with a growing list of `name: Type` or just `name` elements.
///
/// Calls the `macro` repeatedly, starting with list of the elements until the first `|`, then
/// adding the next element for each successive call.
macro_rules! repeat_macro {
(
$macro:tt =>
$( $current_names:ident $( : $current_types:ident )? ),*
| $next_name:ident $( : $next_type:ident )?
$(, $queued_names:ident $( : $queued_types:ident )? )* $(,)?
) => {
$macro!($( $current_names $(: $current_types)? ),*);
repeat_macro!(
$macro =>
$( $current_names $(: $current_types)?, )*
$next_name $(: $next_type)?
| $($queued_names $(: $queued_types)? ),*
);
};
( $macro:tt => $( $current_names:ident $( : $current_types:ident )? ),* |) => {
$macro!($( $current_names $(: $current_types)? ),*);
};
( $macro:tt => $( $current_names:ident $( : $current_types:ident )? ),* $(,)*) => {
repeat_macro!($macro => | $( $current_names $(: $current_types)? ),*);
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/imported_function_interface/parameters.rs | linera-witty/src/imported_function_interface/parameters.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of the parameters of an imported function.
//!
//! The maximum number of parameters that can be used in a WIT function is defined by the
//! [canonical ABI][flattening] as the `MAX_FLAT_PARAMS` constant (16). There is no equivalent
//! constant defined in Witty. Instead, any attempt to use more than the limit should lead to a
//! compiler error.
//!
//! The host parameters type is flattened and if it's made up of `MAX_FLAT_PARAMS` or less flat
//! types, they are sent directly as the guest's function parameters. If there are more than
//! `MAX_FLAT_PARAMS` flat types, then the host type is instead stored in a heap allocated region
//! of memory, and the address to that region is sent as a parameter instead.
//!
//! [flattening]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening
use frunk::HList;
use crate::{
memory_layout::FlatLayout, primitive_types::FlatType, InstanceWithMemory, Layout, Memory,
Runtime, RuntimeError, RuntimeMemory, WitStore, WitType,
};
/// Helper trait for converting from the host parameters to the guest parameters.
///
/// This trait is implemented for the intermediate flat layout of the host parameters type. This
/// allows converting from the host parameters type into this flat layout and finally into the guest
/// parameters type.
pub trait FlatHostParameters: FlatLayout {
/// The actual parameters sent to the guest function.
type GuestParameters: FlatLayout;
/// Converts the `HostParameters` into the guest parameters that can be sent to the guest
/// function.
fn lower_parameters<HostParameters, Instance>(
parameters: HostParameters,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestParameters, RuntimeError>
where
HostParameters: WitStore,
<HostParameters as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
/// Macro to implement [`FlatHostParameters`] for a parameters that are sent directly to the guest.
///
/// Each element in the flat layout type is sent as a separate parameter to the function.
macro_rules! direct_parameters {
($( $types:ident ),*) => {
impl<$( $types ),*> FlatHostParameters for HList![$( $types ),*]
where
$( $types: FlatType, )*
{
type GuestParameters = HList![$( $types ),*];
fn lower_parameters<Parameters, Instance>(
parameters: Parameters,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestParameters, RuntimeError>
where
Parameters: WitStore,
<Parameters as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
parameters.lower(memory)
}
}
};
}
repeat_macro!(direct_parameters => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
/// Implementation of [`FlatHostParameters`] for parameters that are sent to the guest through the
/// heap.
///
/// The maximum number of parameters is defined by the [canonical
/// ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening)
/// as the `MAX_FLAT_PARAMS` constant. When more than `MAX_FLAT_PARAMS` (16) function parameters
/// are needed, they are spilled over into a heap memory allocation and the only parameter sent as
/// a function parameter is the address to that allocation.
impl<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, Tail> FlatHostParameters for HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...Tail]
where
A: FlatType,
B: FlatType,
C: FlatType,
D: FlatType,
E: FlatType,
F: FlatType,
G: FlatType,
H: FlatType,
I: FlatType,
J: FlatType,
K: FlatType,
L: FlatType,
M: FlatType,
N: FlatType,
O: FlatType,
P: FlatType,
Q: FlatType,
Tail: FlatLayout,
{
type GuestParameters = HList![i32];
fn lower_parameters<Parameters, Instance>(
parameters: Parameters,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestParameters, RuntimeError>
where
Parameters: WitStore,
<Parameters as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let location =
memory.allocate(Parameters::SIZE, <Parameters::Layout as Layout>::ALIGNMENT)?;
parameters.store(memory, location)?;
location.lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/imported_function_interface/results.rs | linera-witty/src/imported_function_interface/results.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of the results of an imported function.
//!
//! The results returned from an imported guest function may be empty, a single flat value or a
//! more complex type that's stored in the heap. That depends on the flat layout of the type
//! representing the host results, or more specifically, how many elements that flat layout has. If
//! the flat layout is empty, nothing should be returned from the guest. If there's only one
//! element, it should be returned as a value from the function. If there is more than one element,
//! then the results type is stored in a heap allocated memory region instead, and the address to
//! that region is returned as a value from the function.
//!
//! This is determined by the `MAX_FLAT_RESULTS` in the [canonical ABI's section on
//! flattening](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening)
//! and has the value of `1`. There is no equivalent constant in Witty. Instead, the
//! [`FlatHostResults`] implementations automatically handle flat layouts with more or less
//! elements than the limit.
use frunk::HList;
use crate::{
memory_layout::FlatLayout, primitive_types::FlatType, GuestPointer, InstanceWithMemory, Layout,
Memory, Runtime, RuntimeError, RuntimeMemory, WitLoad, WitType,
};
/// Helper trait for converting from the guest results to the host results.
///
/// This trait is implemented for the intermediate flat layout of the host results type. This
/// allows converting from the guest results type into this flat layout and finally into the host
/// results type.
pub trait FlatHostResults: FlatLayout {
/// The results received from the guest function.
type GuestResults: FlatLayout;
/// Converts the received guest `results` into the `HostResults` type.
fn lift_results<HostResults, Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<HostResults, RuntimeError>
where
HostResults: WitLoad,
<HostResults as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
/// Implementation for host results that are zero-sized types.
impl FlatHostResults for HList![] {
type GuestResults = HList![];
fn lift_results<Results, Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<Results, RuntimeError>
where
Results: WitLoad,
<Results as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Results::lift_from(results, memory)
}
}
/// Implementation for host results that are flattened into a single value.
impl<FlatResult> FlatHostResults for HList![FlatResult]
where
FlatResult: FlatType,
{
type GuestResults = HList![FlatResult];
fn lift_results<Results, Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<Results, RuntimeError>
where
Results: WitLoad,
<Results as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Results::lift_from(results, memory)
}
}
/// Implementation for host results that are flattened into multiple values.
///
/// The value received from the guest is an address to a heap allocated region of memory containing
/// the results. The host results type is loaded from that region.
impl<FirstResult, SecondResult, Tail> FlatHostResults for HList![FirstResult, SecondResult, ...Tail]
where
FirstResult: FlatType,
SecondResult: FlatType,
Tail: FlatLayout,
{
type GuestResults = HList![i32];
fn lift_results<Results, Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<Results, RuntimeError>
where
Results: WitLoad,
<Results as WitType>::Layout: Layout<Flat = Self>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let location = GuestPointer::lift_from(results, memory)?;
Results::load(memory, location)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/imported_function_interface/mod.rs | linera-witty/src/imported_function_interface/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Generic representation of a function the host imports from a guest Wasm instance.
//!
//! This helps determining the actual signature of the imported guest Wasm function based on host
//! types for the parameters and the results.
//!
//! The signature depends on the number of flat types used to represent the parameters and the
//! results, as specified in the [canonical
//! ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening).
mod parameters;
mod results;
use self::{parameters::FlatHostParameters, results::FlatHostResults};
use crate::{
memory_layout::FlatLayout, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError,
RuntimeMemory, WitLoad, WitStore,
};
/// Representation of an imported function's interface.
///
/// Implemented for a tuple pair of the host parameters type and the host results type, and then
/// allows converting to the guest function's signature.
pub trait ImportedFunctionInterface {
/// The type representing the host-side parameters.
type HostParameters: WitStore;
/// The type representing the host-side results.
type HostResults: WitLoad;
/// The flat layout representing the guest-side parameters.
type GuestParameters: FlatLayout;
/// The flat layout representing the guest-side results.
type GuestResults: FlatLayout;
/// Converts the host-side parameters into the guest-side parameters.
fn lower_parameters<Instance>(
parameters: Self::HostParameters,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestParameters, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
/// Converts the guest-side results into the host-side results.
fn lift_results<Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<Self::HostResults, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
impl<Parameters, Results> ImportedFunctionInterface for (Parameters, Results)
where
Parameters: WitStore,
Results: WitLoad,
<Parameters::Layout as Layout>::Flat: FlatHostParameters,
<Results::Layout as Layout>::Flat: FlatHostResults,
{
type HostParameters = Parameters;
type HostResults = Results;
type GuestParameters =
<<Parameters::Layout as Layout>::Flat as FlatHostParameters>::GuestParameters;
type GuestResults = <<Results::Layout as Layout>::Flat as FlatHostResults>::GuestResults;
fn lower_parameters<Instance>(
parameters: Self::HostParameters,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestParameters, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
<<Parameters::Layout as Layout>::Flat as FlatHostParameters>::lower_parameters(
parameters, memory,
)
}
fn lift_results<Instance>(
results: Self::GuestResults,
memory: &Memory<'_, Instance>,
) -> Result<Self::HostResults, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
<<Results::Layout as Layout>::Flat as FlatHostResults>::lift_results(results, memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/util/merge.rs | linera-witty/src/util/merge.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper types and functions that aren't specific to WIT or WebAssembly.
use either::Either;
use frunk::{HCons, HNil};
/// Merging of two heterogeneous lists, resulting in a new heterogeneous list where every element is
/// of type `Either<Left, Right>`, where `Left` is an element from the current list and `Right` is
/// an element from the `Other` list.
pub trait Merge<Other>: Sized {
/// The resulting heterogeneous list with elements of both input lists.
type Output;
}
impl Merge<HNil> for HNil {
type Output = HNil;
}
impl<Head, Tail> Merge<HNil> for HCons<Head, Tail>
where
Tail: Merge<HNil>,
{
type Output = HCons<Either<Head, ()>, <Tail as Merge<HNil>>::Output>;
}
impl<Head, Tail> Merge<HCons<Head, Tail>> for HNil
where
HNil: Merge<Tail>,
{
type Output = HCons<Either<(), Head>, <HNil as Merge<Tail>>::Output>;
}
impl<LeftHead, LeftTail, RightHead, RightTail> Merge<HCons<RightHead, RightTail>>
for HCons<LeftHead, LeftTail>
where
LeftTail: Merge<RightTail>,
{
type Output = HCons<Either<LeftHead, RightHead>, <LeftTail as Merge<RightTail>>::Output>;
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/util/zero_extend.rs | linera-witty/src/util/zero_extend.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Conversions with zero-extension.
/// Converts from a type into a wider `Target` type by zero-extending the most significant bits.
pub trait ZeroExtend<Target> {
/// Converts into the `Target` type by zero-extending the most significant bits.
fn zero_extend(self) -> Target;
}
impl ZeroExtend<i64> for i32 {
fn zero_extend(self) -> i64 {
self as u32 as u64 as i64
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/util/mod.rs | linera-witty/src/util/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper types and functions that aren't specific to WIT or WebAssembly.
mod merge;
mod split;
mod zero_extend;
pub use self::{merge::Merge, split::Split, zero_extend::ZeroExtend};
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/util/split.rs | linera-witty/src/util/split.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Compile time splitting of heterogeneous lists.
use frunk::{hlist, HCons, HNil};
/// Compile time splitting of heterogeneous lists.
///
/// Allows splitting a heterogeneous list at a certain point, determined by the `Target` type,
/// which should match this list type until a certain element. The list after that point is
/// returned as the `Remainder` type.
pub trait Split<Target> {
/// The tail of remaining elements after splitting up the list.
type Remainder;
/// Splits the current heterogeneous list in two.
fn split(self) -> (Target, Self::Remainder);
}
impl<AnyTail> Split<HNil> for AnyTail {
type Remainder = AnyTail;
fn split(self) -> (HNil, Self::Remainder) {
(hlist![], self)
}
}
impl<Head, SourceTail, TargetTail> Split<HCons<Head, TargetTail>> for HCons<Head, SourceTail>
where
SourceTail: Split<TargetTail>,
{
type Remainder = <SourceTail as Split<TargetTail>>::Remainder;
fn split(self) -> (HCons<Head, TargetTail>, Self::Remainder) {
let (tail, remainder) = self.tail.split();
(
HCons {
head: self.head,
tail,
},
remainder,
)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/exported_function_interface/result_storage.rs | linera-witty/src/exported_function_interface/result_storage.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of where a function's results should be stored.
//!
//! The [canonical ABI][flattening] describes a `MAX_FLAT_RESULTS` limit on the number of flat
//! types that are returned from a function. The limit is currently one. That means that any type
//! returned from a host function that needs more than one flat type to represent it after lowering
//! needs to be placed in memory.
//!
//! The [`ResultStorage`] trait below allows representing in compile time if the results should be
//! returned as a single flat value (scenario represented by the `()` unit type) or placed in
//! memory and not have any return value (scenario represented by a [`GuestPointer`] instance with
//! the address where the results should be stored).
//!
//! [flattening]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening
use frunk::HNil;
use crate::{
memory_layout::FlatLayout, GuestPointer, InstanceWithMemory, Layout, Memory, Runtime,
RuntimeError, RuntimeMemory, WitStore,
};
/// Representation of where a function's results should be stored.
///
/// See the module level documentation for details.
pub trait ResultStorage {
/// A helper associated type that maps the flat layout of a `HostResults` type into the flat
/// layout of the returned value.
///
/// This is either an empty layout representing a function that has no return values or a
/// layout with a single flat type representing a function that returns one flat value.
type OutputFor<HostResults>: FlatLayout
where
HostResults: WitStore;
/// Lowers the `HostResults` and prepares the output for the function, storing it in memory if
/// needed.
fn lower_result<HostResults, Instance>(
self,
result: HostResults,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::OutputFor<HostResults>, RuntimeError>
where
HostResults: WitStore,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
impl ResultStorage for () {
type OutputFor<HostResults>
= <HostResults::Layout as Layout>::Flat
where
HostResults: WitStore;
fn lower_result<HostResults, Instance>(
self,
result: HostResults,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::OutputFor<HostResults>, RuntimeError>
where
HostResults: WitStore,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
result.lower(memory)
}
}
impl ResultStorage for GuestPointer {
type OutputFor<HostResults>
= HNil
where
HostResults: WitStore;
fn lower_result<HostResults, Instance>(
self,
result: HostResults,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::OutputFor<HostResults>, RuntimeError>
where
HostResults: WitStore,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
result.store(memory, self)?;
Ok(HNil)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/exported_function_interface/guest_interface.rs | linera-witty/src/exported_function_interface/guest_interface.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of the interface a guest Wasm instance uses for a host function.
//!
//! The [`GuestInterface`] trait is implemented for the tuple pair of the flattened representation
//! of the host function's parameters type and results type. The trait then maps the flattened host
//! function signature into the interface guest Wasm instances expect. This involves selecting
//! where the host function's parameters and results are stored and if the guest Wasm instance
//! needs to provide additional parameters to the function with the addresses to store the
//! parameters and/or results in memory.
//!
//! The [canonical ABI][flattening] describes a `MAX_FLAT_PARAMS` limit on the number of flat types
//! that can be sent to the function through Wasm parameters. If more flat parameters are needed,
//! then all of them are stored in memory instead, and the guest Wasm instance must provide a
//! single parameter with the address in memory of where the parameters are stored. The same must
//! be done if more flat result types than the `MAX_FLAT_RESULTS` limit defined by the [canonical
//! ABI][flattening] need to be returned from the function. In that case, the guest Wasm instance
//! is responsible for sending an additional parameter with an address in memory where the results
//! can be stored. See [`ResultStorage`] for more information.
//!
//! [flattening]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening
use std::ops::Add;
use frunk::HList;
use super::result_storage::ResultStorage;
use crate::{
memory_layout::FlatLayout, primitive_types::FlatType, util::Split, GuestPointer,
InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory, WitLoad,
};
/// Representation of the interface a guest Wasm instance uses for a host function.
///
/// See the module level documentation for more information.
pub trait GuestInterface {
/// The flattened layout of the host function's parameters type.
///
/// This is used as a generic input type in all implementations, but is needed here so it can
/// be used in the constraints of the [`Self::lift_parameters`] method.
type FlatHostParameters: FlatLayout;
/// The flat types the guest Wasm instances use as parameters for the host function.
type FlatGuestParameters: FlatLayout;
/// How the host function's results type is sent back to the guest Wasm instance.
type ResultStorage: ResultStorage;
/// Lifts the parameters received from the guest Wasm instance into the parameters type the
/// host function expects.
///
/// Returns the lifted host function's parameters together with a [`ResultStorage`]
/// implementation which is later used to lower the host function's results to where the guest
/// Wasm instance expects them to be. The [`ResultStorage`] is either the unit type `()`
/// indicating that the results should just be lowered and sent to the guest as the function's
/// return value, or a [`GuestPointer`] with the address of where the results should be stored
/// in memory.
fn lift_parameters<Instance, HostParameters>(
guest_parameters: Self::FlatGuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(HostParameters, Self::ResultStorage), RuntimeError>
where
HostParameters: WitLoad,
HostParameters::Layout: Layout<Flat = Self::FlatHostParameters>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
/// Implements [`GuestInterface`] for the cases where the parameters and the results are sent
/// directly as the function's parameters and results, without requiring any of them to be moved to
/// memory.
macro_rules! direct_interface {
($( $types:ident ),* $(,)*) => {
direct_interface_with_result!($( $types ),* =>);
direct_interface_with_result!($( $types ),* => FlatResult);
};
}
/// Helper macro to [`direct_interface`] so that it can handle the two possible return signatures
/// with all parameter combinations.
macro_rules! direct_interface_with_result {
($( $types:ident ),* => $( $flat_result:ident )?) => {
impl<$( $types, )* $( $flat_result )*> GuestInterface
for (HList![$( $types, )*], HList![$( $flat_result )*])
where
HList![$( $types, )*]: FlatLayout,
$( $flat_result: FlatType, )*
{
type FlatHostParameters = HList![$( $types, )*];
type FlatGuestParameters = HList![$( $types, )*];
type ResultStorage = ();
fn lift_parameters<Instance, HostParameters>(
guest_parameters: Self::FlatGuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(HostParameters, Self::ResultStorage), RuntimeError>
where
HostParameters: WitLoad,
HostParameters::Layout: Layout<Flat = Self::FlatHostParameters>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let parameters = HostParameters::lift_from(guest_parameters, memory)?;
Ok((parameters, ()))
}
}
};
}
repeat_macro!(direct_interface => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
/// Implements [`GuestInterface`] for the cases where the parameters are sent directly as the
/// function's parameters but the results are stored in memory instead.
macro_rules! indirect_results {
($( $types:ident ),*) => {
impl<$( $types, )* Y, Z, Tail> GuestInterface
for (HList![$( $types, )*], HList![Y, Z, ...Tail])
where
HList![$( $types, )*]: FlatLayout + Add<HList![i32]>,
<HList![$( $types, )*] as Add<HList![i32]>>::Output:
FlatLayout + Split<HList![$( $types, )*], Remainder = HList![i32]>,
{
type FlatHostParameters = HList![$( $types, )*];
type FlatGuestParameters = <Self::FlatHostParameters as Add<HList![i32]>>::Output;
type ResultStorage = GuestPointer;
fn lift_parameters<Instance, Parameters>(
guest_parameters: Self::FlatGuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(Parameters, Self::ResultStorage), RuntimeError>
where
Parameters: WitLoad,
Parameters::Layout: Layout<Flat = Self::FlatHostParameters>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (parameters_layout, result_storage_layout) = guest_parameters.split();
let parameters = Parameters::lift_from(parameters_layout, memory)?;
let result_storage = Self::ResultStorage::lift_from(result_storage_layout, memory)?;
Ok((parameters, result_storage))
}
}
};
}
repeat_macro!(indirect_results => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
/// Implements [`GuestInterface`] for the cases where the results are sent directly as the
/// function's return value but the parameters are stored in memory instead.
macro_rules! indirect_parameters {
(=> $( $flat_result:ident )? ) => {
impl<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, Tail $(, $flat_result )*>
GuestInterface
for (
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...Tail],
HList![$( $flat_result )*],
)
where
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...Tail]: FlatLayout,
$( $flat_result: FlatType, )*
{
type FlatHostParameters =
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...Tail];
type FlatGuestParameters = HList![i32];
type ResultStorage = ();
fn lift_parameters<Instance, Parameters>(
guest_parameters: Self::FlatGuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(Parameters, Self::ResultStorage), RuntimeError>
where
Parameters: WitLoad,
Parameters::Layout: Layout<Flat = Self::FlatHostParameters>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let parameters_location = GuestPointer::lift_from(guest_parameters, memory)?;
let parameters = Parameters::load(memory, parameters_location)?;
Ok((parameters, ()))
}
}
};
}
indirect_parameters!(=>);
indirect_parameters!(=> Z);
/// Implements [`GuestInterface`] for the cases where the parameters and the results need to be
/// stored in memory.
impl<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, OtherParameters, Y, Z, OtherResults>
GuestInterface
for (
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...OtherParameters],
HList![Y, Z, ...OtherResults],
)
where
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...OtherParameters]: FlatLayout,
HList![Y, Z, ...OtherResults]: FlatLayout,
{
type FlatHostParameters =
HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ...OtherParameters];
type FlatGuestParameters = HList![i32, i32];
type ResultStorage = GuestPointer;
fn lift_parameters<Instance, Parameters>(
guest_parameters: Self::FlatGuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(Parameters, Self::ResultStorage), RuntimeError>
where
Parameters: WitLoad,
Parameters::Layout: Layout<Flat = Self::FlatHostParameters>,
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (parameters_layout, result_storage_layout) = guest_parameters.split();
let parameters_location = GuestPointer::lift_from(parameters_layout, memory)?;
let parameters = Parameters::load(memory, parameters_location)?;
let result_storage = Self::ResultStorage::lift_from(result_storage_layout, memory)?;
Ok((parameters, result_storage))
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/exported_function_interface/mod.rs | linera-witty/src/exported_function_interface/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper traits for exporting host functions to guest Wasm instances.
//!
//! These help determining the function signature the guest expects based on the host function
//! signature.
mod guest_interface;
mod result_storage;
use self::{guest_interface::GuestInterface, result_storage::ResultStorage};
use crate::{
InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory, WitLoad, WitStore,
WitType,
};
/// A type that can register some functions as exports for the target `Instance`.
pub trait ExportTo<Instance> {
/// Registers some host functions as exports to the provided guest Wasm `instance`.
fn export_to(instance: &mut Instance) -> Result<(), RuntimeError>;
}
/// A type that accepts registering a host function as an export for a guest Wasm instance.
///
/// The `Handler` represents the closure type required for the host function, and `Parameters` and
/// `Results` are the input and output types of the closure, respectively.
pub trait ExportFunction<Handler, Parameters, Results> {
/// Registers a host function executed by the `handler` with the provided `module_name` and
/// `function_name` as an export for a guest Wasm instance.
fn export(
&mut self,
module_name: &str,
function_name: &str,
handler: Handler,
) -> Result<(), RuntimeError>;
}
/// Representation of an exported host function's interface.
///
/// Implemented for a tuple pair of the host parameters type and the host results type, and allows
/// converting to the signature the guest Wasm instance uses for that host function.
pub trait ExportedFunctionInterface {
/// The type representing the host-side parameters.
type HostParameters: WitType;
/// The type representing the host-side results.
type HostResults: WitStore;
/// The representation of the guest-side function interface.
type GuestInterface: GuestInterface<
FlatHostParameters = <<Self::HostParameters as WitType>::Layout as Layout>::Flat,
ResultStorage = Self::ResultStorage,
>;
/// The type representing the guest-side parameters.
type GuestParameters;
/// The type representing the guest-side results.
type GuestResults;
/// How the results from the exported host function should be sent back to the guest.
type ResultStorage: ResultStorage<OutputFor<Self::HostResults> = Self::GuestResults>;
/// Converts the guest-side parameters into the host-side parameters.
fn lift_parameters<Instance>(
guest_parameters: Self::GuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(Self::HostParameters, Self::ResultStorage), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
/// Converts the host-side results into the guest-side results.
fn lower_results<Instance>(
results: Self::HostResults,
result_storage: Self::ResultStorage,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestResults, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
impl<Parameters, Results> ExportedFunctionInterface for (Parameters, Results)
where
Parameters: WitLoad,
Results: WitStore,
(
<Parameters::Layout as Layout>::Flat,
<Results::Layout as Layout>::Flat,
): GuestInterface<FlatHostParameters = <Parameters::Layout as Layout>::Flat>,
<() as WitType>::Layout: Layout<Flat = frunk::HNil>,
{
type HostParameters = Parameters;
type HostResults = Results;
type GuestInterface = (
<Parameters::Layout as Layout>::Flat,
<Results::Layout as Layout>::Flat,
);
type GuestParameters = <Self::GuestInterface as GuestInterface>::FlatGuestParameters;
type GuestResults =
<<Self::GuestInterface as GuestInterface>::ResultStorage as ResultStorage>::OutputFor<
Self::HostResults,
>;
type ResultStorage = <Self::GuestInterface as GuestInterface>::ResultStorage;
fn lift_parameters<Instance>(
guest_parameters: Self::GuestParameters,
memory: &Memory<'_, Instance>,
) -> Result<(Self::HostParameters, Self::ResultStorage), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Self::GuestInterface::lift_parameters(guest_parameters, memory)
}
fn lower_results<Instance>(
results: Self::HostResults,
result_storage: Self::ResultStorage,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::GuestResults, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
result_storage.lower_result(results, memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/wit_generation/mod.rs | linera-witty/src/wit_generation/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Generation of WIT files.
mod stub_instance;
use std::{collections::BTreeMap, io::Write};
pub use self::stub_instance::StubInstance;
pub use crate::type_traits::RegisterWitTypes;
/// Generates WIT snippets for an interface.
pub trait WitInterface {
/// The [`WitType`][`crate::WitType`]s that this interface uses.
type Dependencies: RegisterWitTypes;
/// The name of the package the interface belongs to.
fn wit_package() -> &'static str;
/// The name of the interface.
fn wit_name() -> &'static str;
/// The WIT definitions of each function in this interface.
fn wit_functions() -> Vec<String>;
}
/// Trait for content generation.
pub trait FileContentGenerator {
/// Generate file contents.
fn generate_file_contents(&self, writer: impl Write) -> std::io::Result<()>;
}
/// Helper type to write a [`WitInterface`] to a file.
#[derive(Clone, Debug)]
pub struct WitInterfaceWriter {
package: &'static str,
name: &'static str,
types: BTreeMap<String, String>,
functions: Vec<String>,
}
impl WitInterfaceWriter {
/// Prepares a new [`WitInterfaceWriter`] to write the provided `Interface`.
pub fn new<Interface>() -> Self
where
Interface: WitInterface,
{
let mut types = BTreeMap::new();
Interface::Dependencies::register_wit_types(&mut types);
WitInterfaceWriter {
package: Interface::wit_package(),
name: Interface::wit_name(),
types,
functions: Interface::wit_functions(),
}
}
}
impl FileContentGenerator for WitInterfaceWriter {
fn generate_file_contents(&self, mut writer: impl Write) -> std::io::Result<()> {
writeln!(writer, "package {};\n", self.package)?;
writeln!(writer, "interface {} {{", self.name)?;
for function in &self.functions {
writeln!(writer, "{}", function)?;
}
for type_declaration in self.types.values() {
if !type_declaration.is_empty() {
writeln!(writer)?;
write!(writer, "{}", type_declaration)?;
}
}
writeln!(writer, "}}")?;
Ok(())
}
}
/// Helper type to write a WIT file declaring a
/// [world](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#wit-worlds).
#[derive(Clone, Debug)]
pub struct WitWorldWriter {
package: Option<&'static str>,
name: String,
imports: Vec<&'static str>,
exports: Vec<&'static str>,
}
impl WitWorldWriter {
/// Creates a new [`WitWorldWriter`] to write a world with the provided `name`.
pub fn new(package: impl Into<Option<&'static str>>, name: impl Into<String>) -> Self {
WitWorldWriter {
package: package.into(),
name: name.into(),
imports: Vec::new(),
exports: Vec::new(),
}
}
/// Registers a [`WitInterface`] to be imported into this world.
pub fn import<Interface>(mut self) -> Self
where
Interface: WitInterface,
{
self.imports.push(Interface::wit_name());
self
}
/// Registers a [`WitInterface`] to be exported from this world.
pub fn export<Interface>(mut self) -> Self
where
Interface: WitInterface,
{
self.exports.push(Interface::wit_name());
self
}
}
impl FileContentGenerator for WitWorldWriter {
fn generate_file_contents(&self, mut writer: impl Write) -> std::io::Result<()> {
if let Some(package) = &self.package {
writeln!(writer, "package {};\n", package)?;
}
writeln!(writer, "world {} {{", &self.name)?;
for import in &self.imports {
writeln!(writer, " import {};", import)?;
}
if !self.imports.is_empty() {
writeln!(writer)?;
}
for export in &self.exports {
writeln!(writer, " export {};", export)?;
}
writeln!(writer, "}}")?;
Ok(())
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/wit_generation/stub_instance.rs | linera-witty/src/wit_generation/stub_instance.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Contains a [`StubInstance`] type and the code it requires to implement the necessary
//! trait to be used as a Wasm instance type during compile time.
use std::{borrow::Cow, marker::PhantomData};
use crate::{
memory_layout::FlatLayout, GuestPointer, Instance, InstanceWithFunction, InstanceWithMemory,
Runtime, RuntimeError, RuntimeMemory,
};
/// A stub Wasm instance.
///
/// This is when a Wasm instance type is needed for type-checking but is not needed during
/// runtime.
pub struct StubInstance<UserData = ()> {
_user_data: PhantomData<UserData>,
}
impl<UserData> Default for StubInstance<UserData> {
fn default() -> Self {
StubInstance {
_user_data: PhantomData,
}
}
}
impl<UserData> Instance for StubInstance<UserData> {
type Runtime = StubRuntime;
type UserData = UserData;
type UserDataReference<'a>
= &'a UserData
where
Self::UserData: 'a,
Self: 'a;
type UserDataMutReference<'a>
= &'a mut UserData
where
Self::UserData: 'a,
Self: 'a;
fn load_export(&mut self, _name: &str) -> Option<()> {
unimplemented!("`StubInstance` can not be used as a real `Instance`");
}
fn user_data(&self) -> Self::UserDataReference<'_> {
unimplemented!("`StubInstance` can not be used as a real `Instance`");
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
unimplemented!("`StubInstance` can not be used as a real `Instance`");
}
}
impl<Parameters, Results, UserData> InstanceWithFunction<Parameters, Results>
for StubInstance<UserData>
where
Parameters: FlatLayout + 'static,
Results: FlatLayout + 'static,
{
type Function = ();
fn function_from_export(
&mut self,
_name: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError> {
unimplemented!("`StubInstance` can not be used as a real `InstanceWithFunction`");
}
fn call(
&mut self,
_function: &Self::Function,
_parameters: Parameters,
) -> Result<Results, RuntimeError> {
unimplemented!("`StubInstance` can not be used as a real `InstanceWithFunction`");
}
}
impl<UserData> InstanceWithMemory for StubInstance<UserData> {
fn memory_from_export(&self, _export: ()) -> Result<Option<StubMemory>, RuntimeError> {
unimplemented!("`StubInstance` can not be used as a real `InstanceWithMemory`");
}
}
/// A stub Wasm runtime.
pub struct StubRuntime;
impl Runtime for StubRuntime {
type Export = ();
type Memory = StubMemory;
}
/// A stub Wasm runtime memory.
pub struct StubMemory;
impl<UserData> RuntimeMemory<StubInstance<UserData>> for StubMemory {
fn read<'instance>(
&self,
_instance: &'instance StubInstance<UserData>,
_location: GuestPointer,
_length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError> {
unimplemented!("`StubMemory` can not be used as a real `RuntimeMemory`");
}
fn write(
&mut self,
_instance: &mut StubInstance<UserData>,
_location: GuestPointer,
_bytes: &[u8],
) -> Result<(), RuntimeError> {
unimplemented!("`StubMemory` can not be used as a real `RuntimeMemory`");
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/memory_layout/element.rs | linera-witty/src/memory_layout/element.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of a single element in a memory layout type.
//!
//! This is analogous to what [`MaybeFlatType`] is to [`crate::primitive_types::FlatType`]. Empty
//! slots (represented by the `()` unit type) make it easier to generate code for zero sized types.
use either::Either;
use crate::primitive_types::{JoinFlatTypes, MaybeFlatType, SimpleType};
/// Marker trait to prevent [`LayoutElement`] to be implemented for other types.
pub trait Sealed {}
/// Representation of a single element in a memory layout type.
pub trait LayoutElement: Sealed + Sized {
/// The alignment boundary of the element type.
const ALIGNMENT: u32;
/// If the element is a zero sized type.
const IS_EMPTY: bool;
/// The flattened representation of this element.
type Flat: MaybeFlatType;
/// Converts the element into its flattened representation.
fn flatten(self) -> Self::Flat;
}
impl Sealed for () {}
impl<T> Sealed for T where T: SimpleType {}
impl LayoutElement for () {
const ALIGNMENT: u32 = 1;
const IS_EMPTY: bool = true;
type Flat = ();
fn flatten(self) -> Self::Flat {}
}
impl<T> LayoutElement for T
where
T: SimpleType,
{
const ALIGNMENT: u32 = <T as SimpleType>::ALIGNMENT;
const IS_EMPTY: bool = false;
type Flat = <T as SimpleType>::Flat;
fn flatten(self) -> Self::Flat {
<T as SimpleType>::flatten(self)
}
}
impl<L, R> Sealed for Either<L, R>
where
L: LayoutElement,
R: LayoutElement,
{
}
impl<L, R> LayoutElement for Either<L, R>
where
L: LayoutElement,
R: LayoutElement,
Either<L::Flat, R::Flat>: JoinFlatTypes,
{
const ALIGNMENT: u32 = if L::ALIGNMENT > R::ALIGNMENT {
L::ALIGNMENT
} else {
R::ALIGNMENT
};
const IS_EMPTY: bool = L::IS_EMPTY && R::IS_EMPTY;
type Flat = <Either<L::Flat, R::Flat> as JoinFlatTypes>::Flat;
fn flatten(self) -> Self::Flat {
match self {
Either::Left(left) => Either::Left(left.flatten()).join(),
Either::Right(right) => Either::Right(right.flatten()).join(),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/memory_layout/join_flat_layouts.rs | linera-witty/src/memory_layout/join_flat_layouts.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Joining of flat layouts of different variants of a `variant` type.
//!
//! When flattening `variant` types, a single flat layout must be obtained for the type by joining
//! the flat layout of each variant. This means finding a flat type for each layout element to
//! represent the flat type of any of the variants. See [`crate::primitive_types::JoinFlatTypes`]
//! for more information on how flat types are joined.
use either::Either;
use frunk::{HCons, HNil};
use crate::primitive_types::{FlatType, JoinFlatTypes};
/// Allows converting between the current flat layout and the joined `Target` flat layout, which
/// may be longer or have some elements wider than the current elements.
pub trait JoinFlatLayouts<Target> {
/// Converts the current flat layout into a the joined `Target` flat layout.
fn into_joined(self) -> Target;
/// Converts from the joined `Target` flat layout into the current flat layout.
fn from_joined(joined: Target) -> Self;
}
impl JoinFlatLayouts<HNil> for HNil {
fn into_joined(self) -> HNil {
HNil
}
fn from_joined(_joined: HNil) -> Self {
HNil
}
}
impl<TargetHead, TargetTail> JoinFlatLayouts<HCons<TargetHead, TargetTail>> for HNil
where
TargetHead: Default,
HNil: JoinFlatLayouts<TargetTail>,
{
fn into_joined(self) -> HCons<TargetHead, TargetTail> {
HCons {
head: TargetHead::default(),
tail: HNil.into_joined(),
}
}
fn from_joined(_joined: HCons<TargetHead, TargetTail>) -> Self {
HNil
}
}
impl<SourceHead, SourceTail, TargetHead, TargetTail> JoinFlatLayouts<HCons<TargetHead, TargetTail>>
for HCons<SourceHead, SourceTail>
where
SourceHead: FlatType,
TargetHead: FlatType,
Either<SourceHead, TargetHead>: JoinFlatTypes<Flat = TargetHead>,
SourceTail: JoinFlatLayouts<TargetTail>,
{
fn into_joined(self) -> HCons<TargetHead, TargetTail> {
HCons {
head: Either::Left(self.head).join(),
tail: self.tail.into_joined(),
}
}
fn from_joined(joined: HCons<TargetHead, TargetTail>) -> Self {
HCons {
head: joined.head.split_into(),
tail: SourceTail::from_joined(joined.tail),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/memory_layout/mod.rs | linera-witty/src/memory_layout/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Memory layout of non-fundamental WIT types.
//!
//! Complex WIT types are stored in memory as a sequence of fundamental types. The [`Layout`] type
//! allows representing the memory layout as a type, a heterogeneous list ([`frunk::hlist::HList`])
//! of fundamental types.
mod element;
mod flat_layout;
mod join_flat_layouts;
mod layout;
pub use self::{flat_layout::FlatLayout, join_flat_layouts::JoinFlatLayouts, layout::Layout};
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/memory_layout/layout.rs | linera-witty/src/memory_layout/layout.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of the memory layout of complex types as a sequence of fundamental WIT types.
use frunk::{hlist::HList, HCons, HNil};
use super::{element::LayoutElement, FlatLayout};
use crate::primitive_types::MaybeFlatType;
/// Marker trait to prevent [`LayoutElement`] to be implemented for other types.
pub trait Sealed {}
/// Representation of the memory layout of complex types as a sequence of fundamental WIT types.
pub trait Layout: Sealed + HList {
/// The alignment boundary required for the layout.
const ALIGNMENT: u32;
/// Result of flattening this layout.
type Flat: FlatLayout;
/// Flattens this layout into a layout consisting of native WebAssembly types.
///
/// The resulting flat layout does not have any empty items.
fn flatten(self) -> Self::Flat;
}
impl Sealed for HNil {}
impl<Head, Tail> Sealed for HCons<Head, Tail>
where
Head: LayoutElement,
Tail: Layout,
{
}
impl Layout for HNil {
const ALIGNMENT: u32 = 1;
type Flat = HNil;
fn flatten(self) -> Self::Flat {
HNil
}
}
impl<Head, Tail> Layout for HCons<Head, Tail>
where
Head: LayoutElement,
Tail: Layout,
{
const ALIGNMENT: u32 = if Head::ALIGNMENT > Tail::ALIGNMENT {
Head::ALIGNMENT
} else {
Tail::ALIGNMENT
};
type Flat = <Head::Flat as MaybeFlatType>::Flatten<Tail>;
fn flatten(self) -> Self::Flat {
self.head.flatten().flatten(self.tail)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/memory_layout/flat_layout.rs | linera-witty/src/memory_layout/flat_layout.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of the layout of complex types as a sequence of native WebAssembly types.
use frunk::{HCons, HNil};
use super::Layout;
use crate::primitive_types::FlatType;
/// Representation of the layout of complex types as a sequence of native WebAssembly types.
///
/// This allows laying out complex types as a sequence of WebAssembly types that can represent the
/// parameters or the return list of a function. WIT uses this as an optimization to pass complex
/// types as multiple native WebAssembly parameters.
pub trait FlatLayout: Default + Layout<Flat = Self> {}
impl FlatLayout for HNil {}
impl<Head, Tail> FlatLayout for HCons<Head, Tail>
where
Head: FlatType,
Tail: FlatLayout,
{
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/test.rs | linera-witty/src/runtime/test.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! A dummy runtime implementation useful for tests.
//!
//! No WebAssembly bytecode can be executed, but it allows calling the canonical ABI functions
//! related to memory allocation.
use std::{
any::Any,
borrow::Cow,
collections::HashMap,
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex, MutexGuard,
},
};
use frunk::{hlist, hlist_pat, HList};
use super::{
GuestPointer, Instance, InstanceWithFunction, InstanceWithMemory, Runtime, RuntimeError,
RuntimeMemory,
};
use crate::{memory_layout::FlatLayout, ExportFunction, WitLoad, WitStore};
/// A fake Wasm runtime.
pub struct MockRuntime;
impl Runtime for MockRuntime {
type Export = String;
type Memory = Arc<Mutex<Vec<u8>>>;
}
/// A closure for handling calls to mocked functions.
pub type FunctionHandler<UserData> =
Arc<dyn Fn(MockInstance<UserData>, Box<dyn Any>) -> Result<Box<dyn Any>, RuntimeError>>;
/// A fake Wasm instance.
///
/// Only contains exports for the memory and the canonical ABI allocation functions.
pub struct MockInstance<UserData> {
memory: Arc<Mutex<Vec<u8>>>,
exported_functions: HashMap<String, FunctionHandler<UserData>>,
imported_functions: HashMap<String, FunctionHandler<UserData>>,
user_data: Arc<Mutex<UserData>>,
}
impl<UserData> Default for MockInstance<UserData>
where
UserData: Default,
{
fn default() -> Self {
MockInstance::new(UserData::default())
}
}
impl<UserData> Clone for MockInstance<UserData> {
fn clone(&self) -> Self {
MockInstance {
memory: self.memory.clone(),
exported_functions: self.exported_functions.clone(),
imported_functions: self.imported_functions.clone(),
user_data: self.user_data.clone(),
}
}
}
impl<UserData> MockInstance<UserData> {
/// Creates a new [`MockInstance`] using the provided `user_data`.
pub fn new(user_data: UserData) -> Self {
let memory = Arc::new(Mutex::new(Vec::new()));
MockInstance {
memory: memory.clone(),
exported_functions: HashMap::new(),
imported_functions: HashMap::new(),
user_data: Arc::new(Mutex::new(user_data)),
}
.with_exported_function("cabi_free", |_, _: HList![i32]| Ok(hlist![]))
.with_exported_function(
"cabi_realloc",
move |_,
hlist_pat![_old_address, _old_size, alignment, new_size]: HList![
i32, i32, i32, i32
]| {
let allocation_size = usize::try_from(new_size)
.expect("Failed to allocate a negative amount of memory");
let mut memory = memory
.lock()
.expect("Panic while holding a lock to a `MockInstance`'s memory");
let address = GuestPointer(memory.len().try_into()?).aligned_at(alignment as u32);
memory.resize(address.0 as usize + allocation_size, 0);
assert!(
memory.len() <= i32::MAX as usize,
"No more memory for allocations"
);
Ok(hlist![address.0 as i32])
},
)
}
/// Adds a mock exported function to this [`MockInstance`].
///
/// The `handler` will be called whenever the exported function is called.
pub fn with_exported_function<Parameters, Results, Handler>(
mut self,
name: impl Into<String>,
handler: Handler,
) -> Self
where
Parameters: 'static,
Results: 'static,
Handler: Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError> + 'static,
{
self.add_exported_function(name, handler);
self
}
/// Adds a mock exported function to this [`MockInstance`].
///
/// The `handler` will be called whenever the exported function is called.
pub fn add_exported_function<Parameters, Results, Handler>(
&mut self,
name: impl Into<String>,
handler: Handler,
) -> &mut Self
where
Parameters: 'static,
Results: 'static,
Handler: Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError> + 'static,
{
self.exported_functions.insert(
name.into(),
Arc::new(move |caller, boxed_parameters| {
let parameters = boxed_parameters
.downcast()
.expect("Incorrect parameters used to call handler for exported function");
handler(caller, *parameters).map(|results| Box::new(results) as Box<dyn Any>)
}),
);
self
}
/// Calls a function that the mock instance imported from the host.
pub fn call_imported_function<Parameters, Results>(
&self,
function: &str,
parameters: Parameters,
) -> Result<Results, RuntimeError>
where
Parameters: WitStore + 'static,
Results: WitLoad + 'static,
{
let handler = self
.imported_functions
.get(function)
.unwrap_or_else(|| panic!("Missing function imported from host: {function:?}"));
let flat_parameters = parameters.lower(&mut self.clone().memory()?)?;
let boxed_flat_results = handler(self.clone(), Box::new(flat_parameters))?;
let flat_results = *boxed_flat_results
.downcast()
.expect("Expected an incorrect results type from imported host function");
Results::lift_from(flat_results, &self.clone().memory()?)
}
/// Returns a copy of the current memory contents.
pub fn memory_contents(&self) -> Vec<u8> {
self.memory.lock().unwrap().clone()
}
}
impl<UserData> Instance for MockInstance<UserData> {
type Runtime = MockRuntime;
type UserData = UserData;
type UserDataReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
type UserDataMutReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
fn load_export(&mut self, name: &str) -> Option<String> {
if name == "memory" || self.exported_functions.contains_key(name) {
Some(name.to_owned())
} else {
None
}
}
fn user_data(&self) -> Self::UserDataReference<'_> {
self.user_data
.try_lock()
.expect("Unexpected reentrant access to user data in `MockInstance`")
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
self.user_data
.try_lock()
.expect("Unexpected reentrant access to user data in `MockInstance`")
}
}
impl<Parameters, Results, UserData> InstanceWithFunction<Parameters, Results>
for MockInstance<UserData>
where
Parameters: FlatLayout + 'static,
Results: FlatLayout + 'static,
{
type Function = String;
fn function_from_export(
&mut self,
name: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError> {
Ok(Some(name))
}
fn call(
&mut self,
function: &Self::Function,
parameters: Parameters,
) -> Result<Results, RuntimeError> {
let handler = self
.exported_functions
.get(function)
.ok_or_else(|| RuntimeError::FunctionNotFound(function.clone()))?;
let results = handler(self.clone(), Box::new(parameters))?;
Ok(*results.downcast().unwrap_or_else(|_| {
panic!("Incorrect results type expected from handler of expected function: {function}")
}))
}
}
impl<UserData> RuntimeMemory<MockInstance<UserData>> for Arc<Mutex<Vec<u8>>> {
fn read<'instance>(
&self,
instance: &'instance MockInstance<UserData>,
location: GuestPointer,
length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError> {
let memory = instance
.memory
.lock()
.expect("Panic while holding a lock to a `MockInstance`'s memory");
let start = location.0 as usize;
let end = start + length as usize;
Ok(Cow::Owned(memory[start..end].to_owned()))
}
fn write(
&mut self,
instance: &mut MockInstance<UserData>,
location: GuestPointer,
bytes: &[u8],
) -> Result<(), RuntimeError> {
let mut memory = instance
.memory
.lock()
.expect("Panic while holding a lock to a `MockInstance`'s memory");
let start = location.0 as usize;
let end = start + bytes.len();
memory[start..end].copy_from_slice(bytes);
Ok(())
}
}
impl<UserData> InstanceWithMemory for MockInstance<UserData> {
fn memory_from_export(
&self,
export: String,
) -> Result<Option<Arc<Mutex<Vec<u8>>>>, RuntimeError> {
if export == "memory" {
Ok(Some(self.memory.clone()))
} else {
Err(RuntimeError::NotMemory)
}
}
}
impl<Handler, Parameters, Results, UserData> ExportFunction<Handler, Parameters, Results>
for MockInstance<UserData>
where
Handler: Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError> + 'static,
Parameters: 'static,
Results: 'static,
{
fn export(
&mut self,
module_name: &str,
function_name: &str,
handler: Handler,
) -> Result<(), RuntimeError> {
let name = format!("{module_name}#{function_name}");
self.imported_functions.insert(
name.clone(),
Arc::new(move |instance, boxed_parameters| {
let parameters = boxed_parameters.downcast().unwrap_or_else(|_| {
panic!(
"Incorrect parameters used to call handler for exported function {name:?}"
)
});
let results = handler(instance, *parameters)?;
Ok(Box::new(results))
}),
);
Ok(())
}
}
/// A helper trait to serve as an equivalent to `crate::wasmer::WasmerResults` and
/// `crate::wasmtime::WasmtimeResults` for the [`MockInstance`].
///
/// This is in order to help with writing tests generic over the Wasm guest instance type.
pub trait MockResults {
/// The mock native type of the results for the [`MockInstance`].
type Results;
}
impl<T> MockResults for T {
type Results = T;
}
/// A helper type to verify how many times an exported function is called.
pub struct MockExportedFunction<Parameters, Results, UserData> {
name: String,
call_counter: Arc<AtomicUsize>,
expected_calls: usize,
handler: Arc<dyn Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError>>,
}
impl<Parameters, Results, UserData> MockExportedFunction<Parameters, Results, UserData>
where
Parameters: 'static,
Results: 'static,
UserData: 'static,
{
/// Creates a new [`MockExportedFunction`] for the exported function with the provided `name`.
///
/// Every call to the exported function is called is forwarded to the `handler` and an internal
/// counter is incremented. When the [`MockExportedFunction`] instance is dropped (which should
/// be done at the end of the test), it asserts that the function was called `expected_calls`
/// times.
pub fn new(
name: impl Into<String>,
handler: impl Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError> + 'static,
expected_calls: usize,
) -> Self {
MockExportedFunction {
name: name.into(),
call_counter: Arc::default(),
expected_calls,
handler: Arc::new(handler),
}
}
/// Registers this [`MockExportedFunction`] with the mock `instance`.
pub fn register(&self, instance: &mut MockInstance<UserData>) {
let call_counter = self.call_counter.clone();
let handler = self.handler.clone();
instance.add_exported_function(self.name.clone(), move |caller, parameters: Parameters| {
call_counter.fetch_add(1, Ordering::AcqRel);
handler(caller, parameters)
});
}
}
impl<Parameters, Results, UserData> Drop for MockExportedFunction<Parameters, Results, UserData> {
fn drop(&mut self) {
assert_eq!(
self.call_counter.load(Ordering::Acquire),
self.expected_calls,
"Unexpected number of calls to `{}`",
self.name
);
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/memory.rs | linera-witty/src/runtime/memory.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Abstraction over how different runtimes manipulate the guest WebAssembly module's memory.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use super::{
traits::{CabiFreeAlias, CabiReallocAlias},
InstanceWithFunction, Runtime, RuntimeError,
};
use crate::{Layout, WitType};
#[cfg(test)]
#[path = "unit_tests/memory.rs"]
mod tests;
/// An address for a location in a guest WebAssembly module's memory.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GuestPointer(pub(crate) u32);
impl GuestPointer {
/// Returns a new address that's the current address advanced to add padding to ensure it's
/// aligned to the `alignment` byte boundary.
pub const fn aligned_at(&self, alignment: u32) -> Self {
// The following computation is equivalent to:
// `(alignment - (self.0 % alignment)) % alignment`.
// Source: https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding
let padding = (-(self.0 as i32) & (alignment as i32 - 1)) as u32;
GuestPointer(self.0 + padding)
}
/// Returns a new address that's the current address advanced to after the size of `T`.
pub const fn after<T: WitType>(&self) -> Self {
GuestPointer(self.0 + T::SIZE)
}
/// Returns a new address that's the current address advanced to add padding to ensure it's
/// aligned properly for `T`.
pub const fn after_padding_for<T: WitType>(&self) -> Self {
self.aligned_at(<T::Layout as Layout>::ALIGNMENT)
}
/// Returns the address of an element in a contiguous list of properly aligned `T` types.
pub const fn index<T: WitType>(&self, index: u32) -> Self {
let element_size = GuestPointer(T::SIZE).after_padding_for::<T>();
GuestPointer(self.0 + index * element_size.0)
}
}
/// Interface for accessing a runtime specific memory.
pub trait RuntimeMemory<Instance> {
/// Reads `length` bytes from memory from the provided `location`.
fn read<'instance>(
&self,
instance: &'instance Instance,
location: GuestPointer,
length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError>;
/// Writes the `bytes` to memory at the provided `location`.
fn write(
&mut self,
instance: &mut Instance,
location: GuestPointer,
bytes: &[u8],
) -> Result<(), RuntimeError>;
}
/// A handle to interface with a guest Wasm module instance's memory.
#[expect(clippy::type_complexity)]
pub struct Memory<'runtime, Instance>
where
Instance: CabiReallocAlias + CabiFreeAlias,
{
instance: &'runtime mut Instance,
memory: <Instance::Runtime as Runtime>::Memory,
cabi_realloc: Option<
<Instance as InstanceWithFunction<HList![i32, i32, i32, i32], HList![i32]>>::Function,
>,
cabi_free: Option<<Instance as InstanceWithFunction<HList![i32], HList![]>>::Function>,
}
impl<'runtime, Instance> Memory<'runtime, Instance>
where
Instance: CabiReallocAlias + CabiFreeAlias,
{
/// Creates a new [`Memory`] instance using a Wasm module `instance` and its `memory` export.
pub(super) fn new(
instance: &'runtime mut Instance,
memory: <Instance::Runtime as Runtime>::Memory,
) -> Self {
Memory {
instance,
memory,
cabi_realloc: None,
cabi_free: None,
}
}
}
impl<Instance> Memory<'_, Instance>
where
Instance: CabiReallocAlias + CabiFreeAlias,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
/// Reads `length` bytes from `location`.
///
/// The underlying runtime may return either a memory slice or an owned buffer.
pub fn read(&self, location: GuestPointer, length: u32) -> Result<Cow<'_, [u8]>, RuntimeError> {
self.memory.read(&*self.instance, location, length)
}
/// Writes `bytes` to `location`.
pub fn write(&mut self, location: GuestPointer, bytes: &[u8]) -> Result<(), RuntimeError> {
self.memory.write(&mut *self.instance, location, bytes)
}
/// Returns a newly allocated buffer of `size` bytes in the guest module's memory
/// aligned to the requested `alignment`.
///
/// Calls the guest module to allocate the memory, so the resulting allocation is managed by
/// the guest.
pub fn allocate(&mut self, size: u32, alignment: u32) -> Result<GuestPointer, RuntimeError> {
if self.cabi_realloc.is_none() {
self.cabi_realloc = Some(<Instance as InstanceWithFunction<
HList![i32, i32, i32, i32],
HList![i32],
>>::load_function(self.instance, "cabi_realloc")?);
}
let size = i32::try_from(size).map_err(|_| RuntimeError::AllocationTooLarge)?;
let alignment = i32::try_from(alignment).map_err(|_| RuntimeError::InvalidAlignment)?;
let cabi_realloc = self
.cabi_realloc
.as_ref()
.expect("`cabi_realloc` function was not loaded before it was called");
let hlist_pat![allocation_address] = self
.instance
.call(cabi_realloc, hlist![0, 0, alignment, size])?;
Ok(GuestPointer(
allocation_address
.try_into()
.map_err(|_| RuntimeError::AllocationFailed)?,
))
}
/// Deallocates the `allocation` managed by the guest.
pub fn deallocate(&mut self, allocation: GuestPointer) -> Result<(), RuntimeError> {
if self.cabi_free.is_none() {
self.cabi_free = Some(
<Instance as InstanceWithFunction<HList![i32], HList![]>>::load_function(
self.instance,
"cabi_free",
)?,
);
}
let address = allocation
.0
.try_into()
.map_err(|_| RuntimeError::DeallocateInvalidAddress)?;
let cabi_free = self
.cabi_free
.as_ref()
.expect("`cabi_free` function was not loaded before it was called");
self.instance.call(cabi_free, hlist![address])?;
Ok(())
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/error.rs | linera-witty/src/runtime/error.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Common error type for usage of different Wasm runtimes.
use std::{num::TryFromIntError, string::FromUtf8Error};
use thiserror::Error;
/// Errors that can occur when using a Wasm runtime.
#[derive(Debug, Error)]
pub enum RuntimeError {
/// Attempt to allocate a buffer larger than `i32::MAX`.
#[error("Requested allocation size is too large")]
AllocationTooLarge,
/// Attempt to allocate a buffer that's aligned to an invalid boundary.
#[error("Requested allocation alignment is invalid")]
InvalidAlignment,
/// Call to `cabi_realloc` returned a negative value instead of a valid address.
#[error("Memory allocation failed")]
AllocationFailed,
/// Attempt to deallocate an address that's after `i32::MAX`.
#[error("Attempt to deallocate an invalid address")]
DeallocateInvalidAddress,
/// Attempt to load a function not exported from a module.
#[error("Function `{_0}` could not be found in the module's exports")]
FunctionNotFound(String),
/// Attempt to load a function with a name that's used for a different import in the module.
#[error("Export `{_0}` is not a function")]
NotAFunction(String),
/// Attempt to load the memory export from a module that doesn't export it.
#[error("Failed to load `memory` export")]
MissingMemory,
/// Attempt to load the memory export from a module that exports it as something else.
#[error("Unexpected type for `memory` export")]
NotMemory,
/// Attempt to load a string from a sequence of bytes that doesn't contain a UTF-8 string.
#[error("Failed to load string from non-UTF-8 bytes: {0}")]
InvalidString(#[from] FromUtf8Error),
/// Attempt to create a `GuestPointer` from an invalid address representation.
#[error("Invalid address read: {0}")]
InvalidNumber(#[from] TryFromIntError),
/// Attempt to load an `enum` type but the discriminant doesn't match any of the variants.
#[error("Unexpected variant discriminant {discriminant} for `{type_name}`")]
InvalidVariant {
/// The `enum` type that failed being loaded.
type_name: &'static str,
/// The invalid discriminant that was received.
discriminant: i64,
},
/// A custom error reported by one of the Wasm host's function handlers.
#[error("Error reported by host function handler: {_0}")]
Custom(#[source] anyhow::Error),
/// Wasmer runtime error.
#[cfg(with_wasmer)]
#[error(transparent)]
Wasmer(#[from] wasmer::RuntimeError),
/// Attempt to access an invalid memory address using Wasmer.
#[cfg(with_wasmer)]
#[error(transparent)]
WasmerMemory(#[from] wasmer::MemoryAccessError),
/// Wasmtime error.
#[cfg(with_wasmtime)]
#[error(transparent)]
Wasmtime(anyhow::Error),
/// Wasmtime trap during execution.
#[cfg(with_wasmtime)]
#[error(transparent)]
WasmtimeTrap(#[from] wasmtime::Trap),
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/mod.rs | linera-witty/src/runtime/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Code to interface with different runtimes.
mod borrowed_instance;
mod error;
mod memory;
#[cfg(with_testing)]
mod test;
mod traits;
#[cfg(with_wasmer)]
pub mod wasmer;
#[cfg(with_wasmtime)]
pub mod wasmtime;
#[cfg(with_testing)]
pub use self::test::{MockExportedFunction, MockInstance, MockResults, MockRuntime};
pub use self::{
error::RuntimeError,
memory::{GuestPointer, Memory, RuntimeMemory},
traits::{Instance, InstanceWithFunction, InstanceWithMemory, Runtime},
};
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/traits.rs | linera-witty/src/runtime/traits.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Abstractions over different Wasm runtime implementations.
use std::ops::{Deref, DerefMut};
use frunk::HList;
use super::{memory::Memory, RuntimeError};
use crate::memory_layout::FlatLayout;
/// A Wasm runtime.
///
/// Shared types between different guest instances that use the same runtime.
pub trait Runtime: Sized {
/// A handle to something exported from a guest Wasm module.
type Export;
/// A handle to the guest Wasm module's memory.
type Memory;
}
/// An active guest Wasm module.
pub trait Instance: Sized {
/// The runtime this instance is running in.
type Runtime: Runtime;
/// Custom user data stored in the instance.
type UserData;
/// A reference to the custom user data stored in the instance.
type UserDataReference<'a>: Deref<Target = Self::UserData>
where
Self::UserData: 'a,
Self: 'a;
/// A mutable reference to the custom user data stored in the instance.
type UserDataMutReference<'a>: DerefMut<Target = Self::UserData>
where
Self::UserData: 'a,
Self: 'a;
/// Loads an export from the guest module.
fn load_export(&mut self, name: &str) -> Option<<Self::Runtime as Runtime>::Export>;
/// Returns a reference to the custom user data stored in this instance.
fn user_data(&self) -> Self::UserDataReference<'_>;
/// Returns a mutable reference to the custom user data stored in this instance.
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_>;
}
/// How a runtime supports a function signature.
pub trait InstanceWithFunction<Parameters, Results>: Instance
where
Parameters: FlatLayout,
Results: FlatLayout,
{
/// The runtime-specific type to represent the function.
type Function;
/// Converts an export into a function, if it is one.
fn function_from_export(
&mut self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError>;
/// Calls the `function` from this instance using the specified `parameters`.
fn call(
&mut self,
function: &Self::Function,
parameters: Parameters,
) -> Result<Results, RuntimeError>;
/// Loads a function from the guest Wasm instance.
fn load_function(&mut self, name: &str) -> Result<Self::Function, RuntimeError> {
let export = self
.load_export(name)
.ok_or_else(|| RuntimeError::FunctionNotFound(name.to_string()))?;
self.function_from_export(export)?
.ok_or_else(|| RuntimeError::NotAFunction(name.to_string()))
}
}
/// Trait alias for a Wasm module instance with the WIT Canonical ABI `cabi_realloc` function.
pub trait CabiReallocAlias: InstanceWithFunction<HList![i32, i32, i32, i32], HList![i32]> {}
impl<AnyInstance> CabiReallocAlias for AnyInstance where
AnyInstance: InstanceWithFunction<HList![i32, i32, i32, i32], HList![i32]>
{
}
/// Trait alias for a Wasm module instance with the WIT Canonical ABI `cabi_free` function.
pub trait CabiFreeAlias: InstanceWithFunction<HList![i32], HList![]> {}
impl<AnyInstance> CabiFreeAlias for AnyInstance where
AnyInstance: InstanceWithFunction<HList![i32], HList![]>
{
}
/// Trait alias for a Wasm module instance with the WIT Canonical ABI functions.
pub trait InstanceWithMemory: CabiReallocAlias + CabiFreeAlias {
/// Converts an `export` into the runtime's specific memory type.
fn memory_from_export(
&self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<<Self::Runtime as Runtime>::Memory>, RuntimeError>;
/// Returns the memory export from the current Wasm module instance.
fn memory(&mut self) -> Result<Memory<'_, Self>, RuntimeError> {
let export = self
.load_export("memory")
.ok_or(RuntimeError::MissingMemory)?;
let memory = self
.memory_from_export(export)?
.ok_or(RuntimeError::NotMemory)?;
Ok(Memory::new(self, memory))
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/borrowed_instance.rs | linera-witty/src/runtime/borrowed_instance.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of Wasm instance-related traits for mutable borrows of instances.
//!
//! This allows using the same traits without having to move the type implementation around, for
//! example as parameters in reentrant functions.
use std::borrow::Cow;
use super::{
traits::{CabiFreeAlias, CabiReallocAlias},
Instance, InstanceWithFunction, InstanceWithMemory, Runtime, RuntimeError, RuntimeMemory,
};
use crate::{memory_layout::FlatLayout, GuestPointer};
impl<I> Instance for &mut I
where
I: Instance,
{
type Runtime = I::Runtime;
type UserData = I::UserData;
type UserDataReference<'a>
= I::UserDataReference<'a>
where
Self::UserData: 'a,
Self: 'a;
type UserDataMutReference<'a>
= I::UserDataMutReference<'a>
where
Self::UserData: 'a,
Self: 'a;
fn load_export(&mut self, name: &str) -> Option<<Self::Runtime as Runtime>::Export> {
I::load_export(*self, name)
}
fn user_data(&self) -> Self::UserDataReference<'_> {
I::user_data(*self)
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
I::user_data_mut(*self)
}
}
impl<Parameters, Results, I> InstanceWithFunction<Parameters, Results> for &mut I
where
I: InstanceWithFunction<Parameters, Results>,
Parameters: FlatLayout,
Results: FlatLayout,
{
type Function = I::Function;
fn function_from_export(
&mut self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError> {
I::function_from_export(*self, export)
}
fn call(
&mut self,
function: &Self::Function,
parameters: Parameters,
) -> Result<Results, RuntimeError> {
I::call(*self, function, parameters)
}
}
impl<'a, I> InstanceWithMemory for &'a mut I
where
I: InstanceWithMemory,
&'a mut I: Instance<Runtime = I::Runtime> + CabiReallocAlias + CabiFreeAlias,
{
fn memory_from_export(
&self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<<Self::Runtime as Runtime>::Memory>, RuntimeError> {
I::memory_from_export(&**self, export)
}
}
impl<M, I> RuntimeMemory<&mut I> for M
where
M: RuntimeMemory<I>,
{
/// Reads `length` bytes from memory from the provided `location`.
fn read<'instance>(
&self,
instance: &'instance &mut I,
location: GuestPointer,
length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError> {
self.read(&**instance, location, length)
}
/// Writes the `bytes` to memory at the provided `location`.
fn write(
&mut self,
instance: &mut &mut I,
location: GuestPointer,
bytes: &[u8],
) -> Result<(), RuntimeError> {
self.write(&mut **instance, location, bytes)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/parameters.rs | linera-witty/src/runtime/wasmer/parameters.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of Wasmer function parameter types.
use frunk::{hlist, hlist_pat, HList};
use wasmer::FromToNativeWasmType;
use crate::{memory_layout::FlatLayout, primitive_types::FlatType};
/// Conversions between flat layouts and Wasmer parameter types.
pub trait WasmerParameters: FlatLayout {
/// The type Wasmer uses to represent the parameters in a function imported from a guest.
type ImportParameters;
/// The type Wasmer uses to represent the parameters in a function exported from a host.
type ExportParameters;
/// Converts from this flat layout into Wasmer's representation for functions imported from a
/// guest.
fn into_wasmer(self) -> Self::ImportParameters;
/// Converts from Wasmer's representation for functions exported from the host into this flat
/// layout.
fn from_wasmer(parameters: Self::ExportParameters) -> Self;
}
impl WasmerParameters for HList![] {
type ImportParameters = ();
type ExportParameters = ();
fn into_wasmer(self) -> Self::ImportParameters {}
fn from_wasmer((): Self::ExportParameters) -> Self {
hlist![]
}
}
impl<Parameter> WasmerParameters for HList![Parameter]
where
Parameter: FlatType + FromToNativeWasmType,
{
type ImportParameters = Parameter;
type ExportParameters = (Parameter,);
fn into_wasmer(self) -> Self::ImportParameters {
let hlist_pat![parameter] = self;
parameter
}
fn from_wasmer((parameter,): Self::ExportParameters) -> Self {
hlist![parameter]
}
}
/// Helper macro to implement [`WasmerParameters`] for flat layouts up to the maximum limit.
///
/// The maximum number of parameters is defined by the [canonical
/// ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening)
/// as the `MAX_FLAT_PARAMS` constant. There is no equivalent constant defined in Witty. Instead,
/// any attempt to use more than the limit should lead to a compiler error. Therefore, this macro
/// only implements the trait up to the limit. The same is done in other parts of the code, like
/// for example in
/// [`FlatHostParameters`][`crate::imported_function_interface::FlatHostParameters`].
macro_rules! parameters {
($( $names:ident : $types:ident ),*) => {
impl<$( $types ),*> WasmerParameters for HList![$( $types ),*]
where
$( $types: FlatType + FromToNativeWasmType, )*
{
type ImportParameters = ($( $types, )*);
type ExportParameters = ($( $types, )*);
#[allow(clippy::unused_unit)]
fn into_wasmer(self) -> Self::ImportParameters {
let hlist_pat![$( $names ),*] = self;
($( $names, )*)
}
fn from_wasmer(($( $names, )*): Self::ExportParameters) -> Self {
hlist![$( $names ),*]
}
}
};
}
repeat_macro!(parameters =>
a: A,
b: B |
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/export_function.rs | linera-witty/src/runtime/wasmer/export_function.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Wasmer support for host functions exported to guests Wasm instances.
#![allow(clippy::let_unit_value)]
use std::error::Error;
use wasmer::{FromToNativeWasmType, Function, FunctionEnvMut, WasmTypeList};
use super::{Environment, InstanceBuilder};
use crate::{primitive_types::MaybeFlatType, ExportFunction, RuntimeError};
/// Implements [`ExportFunction`] for [`InstanceBuilder`] using the supported function signatures.
macro_rules! export_function {
($( $names:ident: $types:ident ),*) => {
impl<Handler, HandlerError, $( $types, )* FlatResult, UserData>
ExportFunction<Handler, ($( $types, )*), FlatResult> for InstanceBuilder<UserData>
where
$( $types: FromToNativeWasmType, )*
FlatResult: MaybeFlatType + WasmTypeList,
UserData: 'static,
HandlerError: Error + Send + Sync + 'static,
Handler:
Fn(
FunctionEnvMut<'_, Environment<UserData>>,
($( $types, )*),
) -> Result<FlatResult, HandlerError>
+ Send
+ Sync
+ 'static,
{
fn export(
&mut self,
module_name: &str,
function_name: &str,
handler: Handler,
) -> Result<(), RuntimeError> {
let environment = self.environment();
let function = Function::new_typed_with_env(
self,
&environment,
move |
environment: FunctionEnvMut<'_, Environment<UserData>>,
$( $names: $types ),*
| -> Result<FlatResult, wasmer::RuntimeError> {
handler(environment, ($( $names, )*))
.map_err(|error| -> Box<dyn std::error::Error + Send + Sync> {
Box::new(error)
})
.map_err(wasmer::RuntimeError::user)
},
);
self.define(
module_name,
function_name,
function,
);
Ok(())
}
}
};
}
repeat_macro!(export_function =>
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q,
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/results.rs | linera-witty/src/runtime/wasmer/results.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of Wasmer function result types.
use frunk::{hlist, hlist_pat, HList};
use wasmer::{FromToNativeWasmType, WasmTypeList};
use crate::{memory_layout::FlatLayout, primitive_types::FlatType};
/// Conversions between flat layouts and Wasmer function result types.
pub trait WasmerResults: FlatLayout {
/// The type Wasmer uses to represent the results.
type Results: WasmTypeList;
/// Converts from Wasmer's representation into a flat layout.
fn from_wasmer(results: Self::Results) -> Self;
/// Converts from this flat layout into Wasmer's representation.
fn into_wasmer(self) -> Self::Results;
}
impl WasmerResults for HList![] {
type Results = ();
fn from_wasmer((): Self::Results) -> Self::Flat {
hlist![]
}
fn into_wasmer(self) -> Self::Results {}
}
impl<T> WasmerResults for HList![T]
where
T: FlatType + FromToNativeWasmType,
{
type Results = T;
fn from_wasmer(value: Self::Results) -> Self {
hlist![value]
}
fn into_wasmer(self) -> Self::Results {
let hlist_pat![value] = self;
value
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/memory.rs | linera-witty/src/runtime/wasmer/memory.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! How to access the memory of a Wasmer guest instance.
use std::borrow::Cow;
use wasmer::{Extern, Memory};
use super::{super::traits::InstanceWithMemory, EntrypointInstance, ReentrantInstance};
use crate::{GuestPointer, RuntimeError, RuntimeMemory};
macro_rules! impl_memory_traits {
($instance:ty) => {
impl<UserData: 'static> InstanceWithMemory for $instance {
fn memory_from_export(&self, export: Extern) -> Result<Option<Memory>, RuntimeError> {
Ok(match export {
Extern::Memory(memory) => Some(memory),
_ => None,
})
}
}
impl<UserData: 'static> RuntimeMemory<$instance> for Memory {
fn read<'instance>(
&self,
instance: &'instance $instance,
location: GuestPointer,
length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError> {
let mut buffer = vec![0u8; length as usize];
let start = location.0 as u64;
self.view(instance).read(start, &mut buffer)?;
Ok(Cow::Owned(buffer))
}
fn write(
&mut self,
instance: &mut $instance,
location: GuestPointer,
bytes: &[u8],
) -> Result<(), RuntimeError> {
let start = location.0 as u64;
self.view(&*instance).write(start, bytes)?;
Ok(())
}
}
};
}
impl_memory_traits!(EntrypointInstance<UserData>);
impl_memory_traits!(ReentrantInstance<'_, UserData>);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/function.rs | linera-witty/src/runtime/wasmer/function.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of [`InstanceWithFunction`] for Wasmer instances.
use frunk::{hlist_pat, HList};
use wasmer::{AsStoreRef, Extern, FromToNativeWasmType, NativeWasmTypeInto, TypedFunction};
use super::{
parameters::WasmerParameters, results::WasmerResults, EntrypointInstance, ReentrantInstance,
};
use crate::{
memory_layout::FlatLayout, primitive_types::FlatType, InstanceWithFunction, Runtime,
RuntimeError,
};
/// Implements [`InstanceWithFunction`] for functions with the provided amount of parameters for
/// the [`EntrypointInstance`] and [`ReentrantInstance`] types.
macro_rules! impl_instance_with_function {
($( $names:ident : $types:ident ),*) => {
impl_instance_with_function_for!(EntrypointInstance<UserData>, $( $names: $types ),*);
impl_instance_with_function_for!(ReentrantInstance<'_, UserData>, $( $names: $types ),*);
};
}
/// Implements [`InstanceWithFunction`] for functions with the provided amount of parameters for
/// the provided `instance` type.
macro_rules! impl_instance_with_function_for {
($instance:ty, $( $names:ident : $types:ident ),*) => {
impl<$( $types, )* Results, UserData> InstanceWithFunction<HList![$( $types ),*], Results>
for $instance
where
$( $types: FlatType + FromToNativeWasmType + NativeWasmTypeInto, )*
Results: FlatLayout + WasmerResults,
UserData: 'static,
{
type Function = TypedFunction<
<HList![$( $types ),*] as WasmerParameters>::ImportParameters,
<Results as WasmerResults>::Results,
>;
fn function_from_export(
&mut self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError> {
Ok(match export {
Extern::Function(function) => Some(function.typed(&self.as_store_ref())?),
_ => None,
})
}
fn call(
&mut self,
function: &Self::Function,
hlist_pat![$( $names ),*]: HList![$( $types ),*],
) -> Result<Results, RuntimeError> {
let results = function.call(&mut *self, $( $names ),*)?;
Ok(Results::from_wasmer(results))
}
}
};
}
repeat_macro!(impl_instance_with_function =>
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmer/mod.rs | linera-witty/src/runtime/wasmer/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Support for the [Wasmer](https://wasmer.io) runtime.
mod export_function;
mod function;
mod memory;
mod parameters;
mod results;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
pub use wasmer::FunctionEnvMut;
use wasmer::{
AsStoreMut, AsStoreRef, Engine, Extern, FunctionEnv, Imports, InstantiationError, Memory,
Module, Store, StoreMut, StoreObjects, StoreRef,
};
pub use self::{parameters::WasmerParameters, results::WasmerResults};
use super::traits::{Instance, Runtime};
/// Representation of the [Wasmer](https://wasmer.io) runtime.
pub struct Wasmer;
impl Runtime for Wasmer {
type Export = Extern;
type Memory = Memory;
}
/// Helper to create Wasmer [`Instance`] implementations.
pub struct InstanceBuilder<UserData> {
store: Store,
imports: Imports,
environment: Environment<UserData>,
}
impl<UserData: 'static> InstanceBuilder<UserData> {
/// Creates a new [`InstanceBuilder`].
pub fn new(engine: Engine, user_data: UserData) -> Self {
InstanceBuilder {
store: Store::new(engine),
imports: Imports::default(),
environment: Environment::new(user_data),
}
}
/// Returns a reference to the [`Store`] used in this [`InstanceBuilder`].
pub fn store(&self) -> &Store {
&self.store
}
/// Creates a [`FunctionEnv`] representing the instance of this [`InstanceBuilder`].
///
/// This can be used when exporting host functions that may perform reentrant calls.
pub fn environment(&mut self) -> FunctionEnv<Environment<UserData>> {
FunctionEnv::new(&mut self.store, self.environment.clone())
}
/// Defines a new import for the Wasm guest instance.
pub fn define(&mut self, namespace: &str, name: &str, value: impl Into<Extern>) {
self.imports.define(namespace, name, value);
}
/// Creates an [`EntrypointInstance`] from this [`InstanceBuilder`].
#[allow(clippy::result_large_err)]
pub fn instantiate(
mut self,
module: &Module,
) -> Result<EntrypointInstance<UserData>, InstantiationError> {
let instance = wasmer::Instance::new(&mut self.store, module, &self.imports)?;
self.environment
.exports
.set(instance.exports.clone())
.expect("Environment already initialized");
Ok(EntrypointInstance {
store: self.store,
instance,
instance_slot: self.environment,
})
}
}
impl<UserData> AsStoreRef for InstanceBuilder<UserData> {
fn as_store_ref(&self) -> StoreRef<'_> {
self.store.as_store_ref()
}
}
impl<UserData> AsStoreMut for InstanceBuilder<UserData> {
fn as_store_mut(&mut self) -> StoreMut<'_> {
self.store.as_store_mut()
}
fn objects_mut(&mut self) -> &mut StoreObjects {
self.store.objects_mut()
}
}
/// Necessary data for implementing an entrypoint [`Instance`].
pub struct EntrypointInstance<UserData> {
store: Store,
instance: wasmer::Instance,
instance_slot: Environment<UserData>,
}
impl<UserData> AsStoreRef for EntrypointInstance<UserData> {
fn as_store_ref(&self) -> StoreRef<'_> {
self.store.as_store_ref()
}
}
impl<UserData> AsStoreMut for EntrypointInstance<UserData> {
fn as_store_mut(&mut self) -> StoreMut<'_> {
self.store.as_store_mut()
}
fn objects_mut(&mut self) -> &mut StoreObjects {
self.store.objects_mut()
}
}
impl<UserData> EntrypointInstance<UserData> {
/// Returns mutable references to the [`Store`] and the [`wasmer::Instance`] stored inside this
/// [`EntrypointInstance`].
pub fn as_store_and_instance_mut(&mut self) -> (StoreMut, &mut wasmer::Instance) {
(self.store.as_store_mut(), &mut self.instance)
}
}
impl<UserData> Instance for EntrypointInstance<UserData> {
type Runtime = Wasmer;
type UserData = UserData;
type UserDataReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
type UserDataMutReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
fn load_export(&mut self, name: &str) -> Option<Extern> {
self.instance_slot.load_export(name)
}
fn user_data(&self) -> Self::UserDataReference<'_> {
self.instance_slot.user_data()
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
self.instance_slot.user_data()
}
}
/// Alias for the [`Instance`] implementation made available inside host functions called by the
/// guest.
pub type ReentrantInstance<'a, UserData> = FunctionEnvMut<'a, Environment<UserData>>;
impl<UserData: 'static> Instance for ReentrantInstance<'_, UserData> {
type Runtime = Wasmer;
type UserData = UserData;
type UserDataReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
type UserDataMutReference<'a>
= MutexGuard<'a, UserData>
where
Self::UserData: 'a,
Self: 'a;
fn load_export(&mut self, name: &str) -> Option<Extern> {
self.data_mut().load_export(name)
}
fn user_data(&self) -> Self::UserDataReference<'_> {
FunctionEnvMut::data(self).user_data()
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
FunctionEnvMut::data_mut(self).user_data()
}
}
/// A slot to store a [`wasmer::Instance`] in a way that can be shared with reentrant calls.
pub struct Environment<UserData> {
exports: Arc<OnceLock<wasmer::Exports>>,
user_data: Arc<Mutex<UserData>>,
}
impl<UserData> Environment<UserData> {
/// Creates a new [`Environment`] with no associated instance.
fn new(user_data: UserData) -> Self {
Environment {
exports: Arc::new(OnceLock::new()),
user_data: Arc::new(Mutex::new(user_data)),
}
}
/// Loads an export from the current instance.
///
/// # Panics
///
/// If the slot is empty.
fn load_export(&mut self, name: &str) -> Option<Extern> {
self.exports
.get()
.expect("Attempted to get export before instance is loaded")
.get_extern(name)
.cloned()
}
/// Returns a reference to the `UserData` stored in this [`Environment`].
fn user_data(&self) -> MutexGuard<'_, UserData> {
self.user_data
.try_lock()
.expect("Unexpected reentrant access to data")
}
}
impl<UserData> Clone for Environment<UserData> {
fn clone(&self) -> Self {
Environment {
exports: self.exports.clone(),
user_data: self.user_data.clone(),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/unit_tests/memory.rs | linera-witty/src/runtime/unit_tests/memory.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Unit tests for guest Wasm module memory manipulation.
use super::GuestPointer;
/// Test aligning memory addresses.
///
/// Checks that the resulting address is aligned and that it never advances more than the alignment
/// amount.
#[test]
fn align_guest_pointer() {
for alignment_bits in 0..3 {
let alignment = 1 << alignment_bits;
let alignment_mask = alignment - 1;
for start_offset in 0..32 {
let address = GuestPointer(start_offset).aligned_at(alignment);
assert_eq!(address.0 & alignment_mask, 0);
assert!(address.0 - start_offset < alignment);
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/parameters.rs | linera-witty/src/runtime/wasmtime/parameters.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of Wasmtime function parameter types.
use frunk::{hlist, hlist_pat, HList};
use wasmtime::{WasmParams, WasmTy};
use crate::{primitive_types::FlatType, Layout};
/// Conversions between flat layouts and Wasmtime parameter types.
pub trait WasmtimeParameters {
/// The type Wasmtime uses to represent the parameters.
type Parameters: WasmParams;
/// Converts from this flat layout into Wasmtime's representation.
fn into_wasmtime(self) -> Self::Parameters;
/// Converts from Wasmtime's representation into a flat layout.
fn from_wasmtime(parameters: Self::Parameters) -> Self;
}
/// Helper macro to implement [`WasmtimeParameters`] for flat layouts up to the maximum limit.
///
/// The maximum number of parameters is defined by the [canonical
/// ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening)
/// as the `MAX_FLAT_PARAMS` constant. There is no equivalent constant defined in Witty. Instead,
/// any attempt to use more than the limit should lead to a compiler error. Therefore, this macro
/// only implements the trait up to the limit. The same is done in other parts of the code, like
/// for example in
/// [`FlatHostParameters`][`crate::imported_function_interface::FlatHostParameters`].
macro_rules! parameters {
($( $names:ident : $types:ident ),*) => {
impl<$( $types ),*> WasmtimeParameters for HList![$( $types ),*]
where
$( $types: FlatType + WasmTy, )*
{
type Parameters = ($( $types, )*);
#[allow(clippy::unused_unit)]
fn into_wasmtime(self) -> Self::Parameters {
let hlist_pat![$( $names ),*] = self;
($( $names, )*)
}
fn from_wasmtime(($( $names, )*): Self::Parameters) -> Self {
hlist![$( $names ),*]
}
}
};
}
repeat_macro!(parameters =>
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q
);
impl<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, Rest> WasmtimeParameters for HList![A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, ...Rest]
where
A: FlatType,
B: FlatType,
C: FlatType,
D: FlatType,
E: FlatType,
F: FlatType,
G: FlatType,
H: FlatType,
I: FlatType,
J: FlatType,
K: FlatType,
L: FlatType,
M: FlatType,
N: FlatType,
O: FlatType,
P: FlatType,
Q: FlatType,
R: FlatType,
Rest: Layout,
{
type Parameters = (i32,);
fn into_wasmtime(self) -> Self::Parameters {
unreachable!("Attempt to convert a list of flat parameters larger than the maximum limit");
}
fn from_wasmtime(_: Self::Parameters) -> Self {
unreachable!(
"Attempt to convert into a list of flat parameters larger than the maximum limit"
);
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/export_function.rs | linera-witty/src/runtime/wasmtime/export_function.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Wasmtime support for host functions exported to guests Wasm instances.
#![allow(clippy::let_unit_value)]
use wasmtime::{Caller, Linker, WasmRet, WasmTy};
use crate::{primitive_types::MaybeFlatType, ExportFunction, RuntimeError};
/// Implements [`ExportFunction`] for Wasmtime's [`Linker`] using the supported function
/// signatures.
macro_rules! export_function {
($( $names:ident: $types:ident ),*) => {
impl<Handler, $( $types, )* FlatResult, Data>
ExportFunction<Handler, ($( $types, )*), FlatResult> for Linker<Data>
where
$( $types: WasmTy, )*
FlatResult: MaybeFlatType + WasmRet,
Handler:
Fn(Caller<'_, Data>, ($( $types, )*)) -> Result<FlatResult, RuntimeError>
+ Send
+ Sync
+ 'static,
{
fn export(
&mut self,
module_name: &str,
function_name: &str,
handler: Handler,
) -> Result<(), RuntimeError> {
self.func_wrap(
module_name,
function_name,
move |
caller: Caller<'_, Data>,
$( $names: $types ),*
| -> anyhow::Result<FlatResult> {
let response = handler(caller, ($( $names, )*))?;
Ok(response)
},
)
.map_err(RuntimeError::Wasmtime)?;
Ok(())
}
}
};
}
repeat_macro!(export_function =>
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q,
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/results.rs | linera-witty/src/runtime/wasmtime/results.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Representation of Wasmtime function result types.
use frunk::{hlist, hlist_pat, HList};
use wasmtime::{WasmResults, WasmTy};
use crate::{memory_layout::FlatLayout, primitive_types::FlatType};
/// Conversions between flat layouts and Wasmtime function result types.
pub trait WasmtimeResults: FlatLayout {
/// The type Wasmtime uses to represent the results.
type Results: WasmResults;
/// Converts from Wasmtime's representation into a flat layout.
fn from_wasmtime(results: Self::Results) -> Self;
/// Converts from this flat layout into Wasmtime's representation.
fn into_wasmtime(self) -> Self::Results;
}
impl WasmtimeResults for HList![] {
type Results = ();
fn from_wasmtime((): Self::Results) -> Self::Flat {
hlist![]
}
fn into_wasmtime(self) -> Self::Results {}
}
impl<T> WasmtimeResults for HList![T]
where
T: FlatType + WasmTy,
{
type Results = T;
fn from_wasmtime(value: Self::Results) -> Self {
hlist![value]
}
fn into_wasmtime(self) -> Self::Results {
let hlist_pat![value] = self;
value
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/memory.rs | linera-witty/src/runtime/wasmtime/memory.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! How to access the memory of a Wasmtime guest instance.
use std::borrow::Cow;
use wasmtime::{Extern, Memory};
use super::{super::traits::InstanceWithMemory, EntrypointInstance, ReentrantInstance};
use crate::{GuestPointer, RuntimeError, RuntimeMemory};
macro_rules! impl_memory_traits {
($instance:ty) => {
impl<UserData> InstanceWithMemory for $instance {
fn memory_from_export(&self, export: Extern) -> Result<Option<Memory>, RuntimeError> {
Ok(match export {
Extern::Memory(memory) => Some(memory),
_ => None,
})
}
}
impl<UserData> RuntimeMemory<$instance> for Memory {
fn read<'instance>(
&self,
instance: &'instance $instance,
location: GuestPointer,
length: u32,
) -> Result<Cow<'instance, [u8]>, RuntimeError> {
let start = location.0 as usize;
let end = start + length as usize;
Ok(Cow::Borrowed(&self.data(instance)[start..end]))
}
fn write(
&mut self,
instance: &mut $instance,
location: GuestPointer,
bytes: &[u8],
) -> Result<(), RuntimeError> {
let start = location.0 as usize;
let end = start + bytes.len();
self.data_mut(instance)[start..end].copy_from_slice(bytes);
Ok(())
}
}
};
}
impl_memory_traits!(EntrypointInstance<UserData>);
impl_memory_traits!(ReentrantInstance<'_, UserData>);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/function.rs | linera-witty/src/runtime/wasmtime/function.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of [`InstanceWithFunction`] for Wasmtime instances.
use wasmtime::{AsContext, AsContextMut, Extern, TypedFunc};
use super::{
parameters::WasmtimeParameters, results::WasmtimeResults, EntrypointInstance, ReentrantInstance,
};
use crate::{memory_layout::FlatLayout, InstanceWithFunction, Runtime, RuntimeError};
/// Implements [`InstanceWithFunction`] for the Wasmtime [`Instance`] implementations.
macro_rules! impl_instance_with_function {
($instance:ty) => {
impl<Parameters, Results, UserData> InstanceWithFunction<Parameters, Results> for $instance
where
Parameters: FlatLayout + WasmtimeParameters,
Results: FlatLayout + WasmtimeResults,
{
type Function = TypedFunc<
<Parameters as WasmtimeParameters>::Parameters,
<Results as WasmtimeResults>::Results,
>;
fn function_from_export(
&mut self,
export: <Self::Runtime as Runtime>::Export,
) -> Result<Option<Self::Function>, RuntimeError> {
Ok(match export {
Extern::Func(function) => Some(
function
.typed(self.as_context())
.map_err(RuntimeError::Wasmtime)?,
),
_ => None,
})
}
fn call(
&mut self,
function: &Self::Function,
parameters: Parameters,
) -> Result<Results, RuntimeError> {
let results = function
.call(self.as_context_mut(), parameters.into_wasmtime())
.map_err(RuntimeError::Wasmtime)?;
Ok(Results::from_wasmtime(results))
}
}
};
}
impl_instance_with_function!(EntrypointInstance<UserData>);
impl_instance_with_function!(ReentrantInstance<'_, UserData>);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/runtime/wasmtime/mod.rs | linera-witty/src/runtime/wasmtime/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Support for the [Wasmtime](https://wasmtime.dev) runtime.
mod export_function;
mod function;
mod memory;
mod parameters;
mod results;
pub use anyhow;
use wasmtime::{AsContext, AsContextMut, Extern, Memory, Store, StoreContext, StoreContextMut};
pub use wasmtime::{Caller, Linker};
pub use self::{parameters::WasmtimeParameters, results::WasmtimeResults};
use super::traits::{Instance, Runtime};
/// Representation of the [Wasmtime](https://wasmtime.dev) runtime.
pub struct Wasmtime;
impl Runtime for Wasmtime {
type Export = Extern;
type Memory = Memory;
}
/// Necessary data for implementing an entrypoint [`Instance`].
pub struct EntrypointInstance<UserData> {
instance: wasmtime::Instance,
store: Store<UserData>,
}
impl<UserData> EntrypointInstance<UserData> {
/// Creates a new [`EntrypointInstance`] with the guest module
/// [`Instance`][`wasmtime::Instance`] and [`Store`].
pub fn new(instance: wasmtime::Instance, store: Store<UserData>) -> Self {
EntrypointInstance { instance, store }
}
}
impl<UserData> AsContext for EntrypointInstance<UserData> {
type Data = UserData;
fn as_context(&self) -> StoreContext<UserData> {
self.store.as_context()
}
}
impl<UserData> AsContextMut for EntrypointInstance<UserData> {
fn as_context_mut(&mut self) -> StoreContextMut<UserData> {
self.store.as_context_mut()
}
}
impl<UserData> Instance for EntrypointInstance<UserData> {
type Runtime = Wasmtime;
type UserData = UserData;
type UserDataReference<'a>
= &'a UserData
where
Self: 'a,
UserData: 'a;
type UserDataMutReference<'a>
= &'a mut UserData
where
Self: 'a,
UserData: 'a;
fn load_export(&mut self, name: &str) -> Option<Extern> {
self.instance.get_export(&mut self.store, name)
}
fn user_data(&self) -> Self::UserDataReference<'_> {
self.store.data()
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
self.store.data_mut()
}
}
/// Alias for the [`Instance`] implementation made available inside host functions called by the
/// guest.
pub type ReentrantInstance<'a, UserData> = Caller<'a, UserData>;
impl<UserData> Instance for Caller<'_, UserData> {
type Runtime = Wasmtime;
type UserData = UserData;
type UserDataReference<'a>
= &'a UserData
where
Self: 'a,
UserData: 'a;
type UserDataMutReference<'a>
= &'a mut UserData
where
Self: 'a,
UserData: 'a;
fn load_export(&mut self, name: &str) -> Option<Extern> {
Caller::get_export(self, name)
}
fn user_data(&self) -> Self::UserDataReference<'_> {
Caller::data(self)
}
fn user_data_mut(&mut self) -> Self::UserDataMutReference<'_> {
Caller::data_mut(self)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/mod.rs | linera-witty/src/type_traits/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Traits used to allow complex types to be sent and received between hosts and guests using WIT.
mod implementations;
mod register_wit_types;
use std::borrow::Cow;
pub use self::register_wit_types::RegisterWitTypes;
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
};
/// A type that is representable by fundamental WIT types.
pub trait WitType {
/// The size of the type when laid out in memory.
const SIZE: u32;
/// The layout of the type as fundamental types.
type Layout: Layout;
/// Other [`WitType`]s that this type depends on.
type Dependencies: RegisterWitTypes;
/// Generates the WIT type name for this type.
fn wit_type_name() -> Cow<'static, str>;
/// Generates the WIT type declaration for this type.
fn wit_type_declaration() -> Cow<'static, str>;
}
/// A type that can be loaded from a guest Wasm module.
pub trait WitLoad: WitType + Sized {
/// Loads an instance of the type from the `location` in the guest's `memory`.
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
/// Lifts an instance of the type from the `flat_layout` representation.
///
/// May read from the `memory` if the type has references to heap data.
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
/// A type that can be stored in a guest Wasm module.
pub trait WitStore: WitType {
/// Stores the type at the `location` in the guest's `memory`.
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
/// Lowers the type into its flat layout representation.
///
/// May write to the `memory` if the type has references to heap data or if it doesn't fit in
/// the maximum flat layout size.
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/register_wit_types.rs | linera-witty/src/type_traits/register_wit_types.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Trait and helper types allow registering a compile-time list of [`WitType`]s.
use std::collections::BTreeMap;
use frunk::{HCons, HNil};
use super::WitType;
/// Marker trait to prevent [`RegisterWitTypes`] to be implemented for other types.
pub trait Sealed {}
/// Trait to register a compile-time list of [`WitType`]s into a [`BTreeMap`].
pub trait RegisterWitTypes: Sealed {
/// Registers this list of [`WitType`]s into `wit_types`.
fn register_wit_types(wit_types: &mut BTreeMap<String, String>);
}
impl Sealed for HNil {}
impl<Head, Tail> Sealed for HCons<Head, Tail>
where
Head: WitType,
Tail: Sealed,
{
}
impl RegisterWitTypes for HNil {
fn register_wit_types(_wit_types: &mut BTreeMap<String, String>) {}
}
impl<Head, Tail> RegisterWitTypes for HCons<Head, Tail>
where
Head: WitType,
Tail: RegisterWitTypes,
{
fn register_wit_types(wit_types: &mut BTreeMap<String, String>) {
let head_name = Head::wit_type_name();
if !wit_types.contains_key(&*head_name) {
wit_types.insert(
head_name.into_owned(),
Head::wit_type_declaration().into_owned(),
);
Head::Dependencies::register_wit_types(wit_types);
}
Tail::register_wit_types(wit_types);
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/tests.rs | linera-witty/src/type_traits/implementations/tests.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Unit tests for implementations of the custom traits for existing types.
use std::{collections::BTreeMap, fmt::Debug, time::Duration};
use frunk::hlist;
use crate::{GuestPointer, InstanceWithMemory, Layout, MockInstance, WitLoad, WitStore, WitType};
/// Test roundtrip of a heterogeneous list that doesn't need any internal padding.
#[test]
fn hlist_without_padding() {
let input = hlist![
0x1011_1213_1415_1617_1819_1a1b_1c1d_1e1f_u128,
0x2021_2223_2425_2627_i64,
0x3031_3233_u32,
0x4041_i16,
true,
false,
];
test_memory_roundtrip(
&input,
&[
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12,
0x11, 0x10, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x33, 0x32, 0x31, 0x30,
0x41, 0x40, 0x01, 0x00,
],
&[],
);
test_flattening_roundtrip(
&input,
hlist![
0x1819_1a1b_1c1d_1e1f_i64,
0x1011_1213_1415_1617_i64,
0x2021_2223_2425_2627_i64,
0x3031_3233_i32,
0x0000_4041_i32,
0x0000_0001_i32,
0x0000_0000_i32,
],
&[],
);
}
/// Test roundtrip of a heterogeneous list that needs some padding at the end to align its
/// size.
#[test]
fn hlist_with_padding_at_the_end_for_size_alignment() {
let input = hlist![0x8081_8283_8485_8687_u64, true];
test_memory_roundtrip(
&input,
&[
0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x01, 0, 0, 0, 0, 0, 0, 0,
],
&[],
);
test_flattening_roundtrip(
&input,
hlist![0x8081_8283_8485_8687_u64 as i64, 0x0000_0001_i32],
&[],
);
}
/// Test roundtrip of a heterogeneous list that needs internal padding between some of its elements.
#[test]
fn hlist_with_padding() {
let input = hlist![
true,
0x1011_i16,
0x2021_u16,
0x3031_3233_u32,
0x4041_4243_4445_4647_i64,
];
test_memory_roundtrip(
&input,
&[
0x01, 0, 0x11, 0x10, 0x21, 0x20, 0, 0, 0x33, 0x32, 0x31, 0x30, 0, 0, 0, 0, 0x47, 0x46,
0x45, 0x44, 0x43, 0x42, 0x41, 0x40,
],
&[],
);
test_flattening_roundtrip(
&input,
hlist![
0x0000_0001_i32,
0x0000_1011_i32,
0x0000_2021_i32,
0x3031_3233_i32,
0x4041_4243_4445_4647_i64,
],
&[],
);
}
/// Test roundtrip of `None::<i8>`.
#[test]
fn none() {
let input = None::<i8>;
test_memory_roundtrip(&input, &[0x00, 0], &[]);
test_flattening_roundtrip(&input, hlist![0_i32, 0_i32], &[]);
}
/// Test roundtrip of `Some::<i8>`.
#[test]
fn some_byte() {
let input = Some(-100_i8);
test_memory_roundtrip(&input, &[0x01, 0x9c], &[]);
test_flattening_roundtrip(&input, hlist![1_i32, -100_i32], &[]);
}
/// Test roundtrip of `Ok::<i16, u128>`.
#[test]
fn ok_two_bytes_but_large_err() {
let input = Ok::<_, u128>(0x1234_i16);
assert_eq!(
<<Result<i16, u128> as WitType>::Layout as Layout>::ALIGNMENT,
8
);
test_memory_roundtrip(
&input,
&[
0x00, 0, 0, 0, 0, 0, 0, 0, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
&[],
);
test_flattening_roundtrip(&input, hlist![0_i32, 0x0000_1234_i64, 0_i64], &[]);
}
/// Test roundtrip of `Err::<i16, u128>`.
#[test]
fn large_err() {
let input = Err::<i16, _>(0x0001_0203_0405_0607_0809_0a0b_0c0d_0e0f_u128);
test_memory_roundtrip(
&input,
&[
0x01, 0, 0, 0, 0, 0, 0, 0, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06,
0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
],
&[],
);
test_flattening_roundtrip(
&input,
hlist![1_i32, 0x0809_0a0b_0c0d_0e0f_i64, 0x0001_0203_0405_0607_i64],
&[],
);
}
/// Test roundtrip of [`Duration`].
#[test]
fn duration() {
let seconds = 0x4aab_acad_aeaf_babb;
let nanos = 0x3837_3635;
let input = Duration::new(seconds, nanos);
assert_eq!(input.as_secs(), seconds);
assert_eq!(input.subsec_nanos(), nanos);
assert_eq!(<<Duration as WitType>::Layout as Layout>::ALIGNMENT, 8);
test_memory_roundtrip(
&input,
&[
0xbb, 0xba, 0xaf, 0xae, 0xad, 0xac, 0xab, 0x4a, 0x35, 0x36, 0x37, 0x38, 0, 0, 0, 0,
],
&[],
);
test_flattening_roundtrip(&input, hlist![seconds as i64, nanos as i32], &[]);
}
/// Test roundtrip of `BTreeMap<u8, i32>`.
#[test]
fn btree_map() {
let input = [(0xaa, 0x1122_3344), (0xbb, 0x7788_99aa)]
.into_iter()
.collect::<BTreeMap<u8, i32>>();
assert_eq!(
<<BTreeMap<u8, i32> as WitType>::Layout as Layout>::ALIGNMENT,
4
);
test_memory_roundtrip(
&input,
&[0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00],
&[
0xaa, 0, 0, 0, 0x44, 0x33, 0x22, 0x11, 0xbb, 0, 0, 0, 0xaa, 0x99, 0x88, 0x77,
],
);
test_flattening_roundtrip(
&input,
hlist![0_i32, 2_i32],
&[
0xaa, 0, 0, 0, 0x44, 0x33, 0x22, 0x11, 0xbb, 0, 0, 0, 0xaa, 0x99, 0x88, 0x77,
],
);
}
/// Test roundtrip of [`log::Level`].
#[cfg(with_log)]
#[test]
fn log_level() {
use log::Level::*;
for (index, level) in [Error, Warn, Info, Debug, Trace].into_iter().enumerate() {
test_memory_roundtrip(&level, &[index as u8], &[]);
test_flattening_roundtrip(&level, hlist![index as i32], &[]);
}
}
/// Test storing an instance of `T` to memory, checking that the `layout_data` bytes followed by
/// the `heap_data` bytes are correctly written, and check that the instance can be loaded from
/// those bytes.
fn test_memory_roundtrip<T>(input: &T, layout_data: &[u8], heap_data: &[u8])
where
T: Debug + Eq + WitLoad + WitStore,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let layout_length = layout_data.len() as u32;
let heap_length = heap_data.len() as u32;
assert_eq!(layout_length, T::SIZE);
let layout_address = memory
.allocate(layout_length, <T::Layout as Layout>::ALIGNMENT)
.unwrap();
let heap_address = layout_address.after::<T>();
input.store(&mut memory, layout_address).unwrap();
assert_eq!(
memory.read(layout_address, layout_length).unwrap(),
layout_data
);
assert_eq!(memory.read(heap_address, heap_length).unwrap(), heap_data);
assert_eq!(&T::load(&memory, layout_address).unwrap(), input);
}
/// Test lowering an instance of `T`, checking that the resulting flat layout matches the expected
/// `flat_layout`, and check that the instance can be lifted from that flat layout.
fn test_flattening_roundtrip<T>(
input: &T,
flat_layout: <T::Layout as Layout>::Flat,
heap_data: &[u8],
) where
T: Debug + Eq + WitLoad + WitStore,
<T::Layout as Layout>::Flat: Debug + Eq,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let heap_address = GuestPointer(0);
let heap_length = heap_data.len() as u32;
let lowered_layout = input.lower(&mut memory).unwrap();
assert_eq!(lowered_layout, flat_layout);
assert_eq!(memory.read(heap_address, heap_length).unwrap(), heap_data);
assert_eq!(&T::lift_from(lowered_layout, &memory).unwrap(), input);
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/log.rs | linera-witty/src/type_traits/implementations/log.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for types from the [`log`] crate.
use std::borrow::Cow;
use frunk::{hlist_pat, HList};
use log::Level;
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for Level {
const SIZE: u32 = 1;
type Layout = HList![i8];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"log-level".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
concat!(
" enum log-level {\n",
" error,\n",
" warn,\n",
" info,\n",
" debug,\n",
" trace,\n",
" }\n",
)
.into()
}
}
impl WitLoad for Level {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
match u8::load(memory, location)? {
0 => Ok(Level::Error),
1 => Ok(Level::Warn),
2 => Ok(Level::Info),
3 => Ok(Level::Debug),
4 => Ok(Level::Trace),
_ => unreachable!("Invalid log level"),
}
}
fn lift_from<Instance>(
hlist_pat![discriminant]: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
match discriminant {
0 => Ok(Level::Error),
1 => Ok(Level::Warn),
2 => Ok(Level::Info),
3 => Ok(Level::Debug),
4 => Ok(Level::Trace),
_ => unreachable!("Invalid log level"),
}
}
}
impl WitStore for Level {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let discriminant: i8 = match self {
Level::Error => 0,
Level::Warn => 1,
Level::Info => 2,
Level::Debug => 3,
Level::Trace => 4,
};
discriminant.store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let discriminant: i8 = match self {
Level::Error => 0,
Level::Warn => 1,
Level::Info => 2,
Level::Debug => 3,
Level::Trace => 4,
};
discriminant.lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/mod.rs | linera-witty/src/type_traits/implementations/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for existing types.
mod custom_types;
mod frunk;
#[cfg(with_log)]
mod log;
mod std;
#[cfg(test)]
mod tests;
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/frunk.rs | linera-witty/src/type_traits/implementations/frunk.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for types from the standard library.
use std::{borrow::Cow, ops::Add};
use frunk::{HCons, HList, HNil};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory, Split,
WitLoad, WitStore, WitType,
};
impl WitType for HNil {
const SIZE: u32 = 0;
type Layout = HNil;
type Dependencies = HNil;
fn wit_type_name() -> Cow<'static, str> {
"hnil".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
"type hnil = unit".into()
}
}
impl WitLoad for HNil {
fn load<Instance>(
_memory: &Memory<'_, Instance>,
_location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
{
Ok(HNil)
}
fn lift_from<Instance>(
HNil: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
{
Ok(HNil)
}
}
impl WitStore for HNil {
fn store<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
_location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(())
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(HNil)
}
}
impl<Head, Tail> WitType for HCons<Head, Tail>
where
Head: WitType,
Tail: WitType + SizeCalculation,
Head::Layout: Add<Tail::Layout>,
<Head::Layout as Add<Tail::Layout>>::Output: Layout,
{
const SIZE: u32 = {
let packed_size = Self::SIZE_STARTING_AT_BYTE_BOUNDARIES[0];
let aligned_size = GuestPointer(packed_size).after_padding_for::<Self>();
aligned_size.0
};
type Layout = <Head::Layout as Add<Tail::Layout>>::Output;
type Dependencies = HList![Head, Tail];
fn wit_type_name() -> Cow<'static, str> {
format!("hcons-{}-{}", Head::wit_type_name(), Tail::wit_type_name()).into()
}
fn wit_type_declaration() -> Cow<'static, str> {
let head = Head::wit_type_name();
let tail = Tail::wit_type_name();
format!("type hcons-{head}-{tail} = tuple<{head}, {tail}>").into()
}
}
impl<Head, Tail> WitLoad for HCons<Head, Tail>
where
Head: WitLoad,
Tail: WitLoad + SizeCalculation,
Head::Layout: Add<Tail::Layout>,
<Head::Layout as Add<Tail::Layout>>::Output: Layout,
<Self::Layout as Layout>::Flat:
Split<<Head::Layout as Layout>::Flat, Remainder = <Tail::Layout as Layout>::Flat>,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(HCons {
head: Head::load(memory, location)?,
tail: Tail::load(
memory,
location
.after::<Head>()
.after_padding_for::<Tail::FirstElement>(),
)?,
})
}
fn lift_from<Instance>(
layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (head_layout, tail_layout) = layout.split();
Ok(HCons {
head: Head::lift_from(head_layout, memory)?,
tail: Tail::lift_from(tail_layout, memory)?,
})
}
}
impl<Head, Tail> WitStore for HCons<Head, Tail>
where
Head: WitStore,
Tail: WitStore + SizeCalculation,
Head::Layout: Add<Tail::Layout>,
<Head::Layout as Add<Tail::Layout>>::Output: Layout,
<Head::Layout as Layout>::Flat: Add<<Tail::Layout as Layout>::Flat>,
Self::Layout: Layout<
Flat = <<Head::Layout as Layout>::Flat as Add<<Tail::Layout as Layout>::Flat>>::Output,
>,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.head.store(memory, location)?;
self.tail.store(
memory,
location
.after::<Head>()
.after_padding_for::<Tail::FirstElement>(),
)?;
Ok(())
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let head_layout = self.head.lower(memory)?;
let tail_layout = self.tail.lower(memory)?;
Ok(head_layout + tail_layout)
}
}
/// Helper trait used to calculate the size of a heterogeneous list considering internal alignment.
///
/// Assumes the maximum alignment necessary for any type is 8 bytes, which is the alignment for the
/// largest flat types (`i64` and `f64`).
trait SizeCalculation {
/// The size of the list considering the current size calculation starts at different offsets
/// inside an 8-byte window.
const SIZE_STARTING_AT_BYTE_BOUNDARIES: [u32; 8];
/// The type of the first element of the list, used to determine the current necessary
/// alignment.
type FirstElement: WitType;
}
impl SizeCalculation for HNil {
const SIZE_STARTING_AT_BYTE_BOUNDARIES: [u32; 8] = [0; 8];
type FirstElement = ();
}
/// Unrolls a `for`-like loop so that it runs in a `const` context.
macro_rules! unroll_for {
($binding:ident in [ $($elements:expr),* $(,)? ] $body:tt) => {
$(
let $binding = $elements;
$body
)*
};
}
impl<Head, Tail> SizeCalculation for HCons<Head, Tail>
where
Head: WitType,
Tail: SizeCalculation,
{
const SIZE_STARTING_AT_BYTE_BOUNDARIES: [u32; 8] = {
let mut size_at_boundaries = [0; 8];
unroll_for!(boundary_offset in [0, 1, 2, 3, 4, 5, 6, 7] {
let memory_location = GuestPointer(boundary_offset)
.after_padding_for::<Head>()
.after::<Head>();
let tail_size = Tail::SIZE_STARTING_AT_BYTE_BOUNDARIES[memory_location.0 as usize % 8];
size_at_boundaries[boundary_offset as usize] =
memory_location.0 - boundary_offset + tail_size;
});
size_at_boundaries
};
type FirstElement = Head;
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/custom_types.rs | linera-witty/src/type_traits/implementations/custom_types.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for types declared in this crate.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for GuestPointer {
const SIZE: u32 = u32::SIZE;
type Layout = HList![i32];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"guest-pointer".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
"type guest-pointer = i32".into()
}
}
impl WitLoad for GuestPointer {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(GuestPointer(u32::load(memory, location)?))
}
fn lift_from<Instance>(
hlist_pat![value]: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(GuestPointer(value.try_into()?))
}
}
impl WitStore for GuestPointer {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.0.store(memory, location)
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(hlist![self.0 as i32])
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/vec.rs | linera-witty/src/type_traits/implementations/std/vec.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`Vec`] type.
use std::{borrow::Cow, ops::Deref};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl<T> WitType for Vec<T>
where
T: WitType,
{
const SIZE: u32 = <[T] as WitType>::SIZE;
type Layout = <[T] as WitType>::Layout;
type Dependencies = <[T] as WitType>::Dependencies;
fn wit_type_name() -> Cow<'static, str> {
<[T] as WitType>::wit_type_name()
}
fn wit_type_declaration() -> Cow<'static, str> {
<[T] as WitType>::wit_type_declaration()
}
}
impl<T> WitLoad for Vec<T>
where
T: WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Box::load(memory, location).map(Vec::from)
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Box::lift_from(flat_layout, memory).map(Vec::from)
}
}
impl<T> WitStore for Vec<T>
where
T: WitStore,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.deref().store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.deref().lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/box.rs | linera-witty/src/type_traits/implementations/std/box.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`Box`] type.
impl_for_wrapper_type!(Box);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/string.rs | linera-witty/src/type_traits/implementations/std/string.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`String`] type.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for String {
const SIZE: u32 = 8;
type Layout = HList![i32, i32];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"string".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// Primitive types don't need to be declared
"".into()
}
}
impl WitLoad for String {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let address = GuestPointer::load(memory, location)?;
let length = u32::load(memory, location.after::<GuestPointer>())?;
let bytes = memory.read(address, length)?.to_vec();
Ok(String::from_utf8(bytes)?)
}
fn lift_from<Instance>(
hlist_pat![address, length]: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let address = GuestPointer(address.try_into()?);
let length = length as u32;
let bytes = memory.read(address, length)?.to_vec();
Ok(String::from_utf8(bytes)?)
}
}
impl WitStore for String {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let length = u32::try_from(self.len())?;
let destination = memory.allocate(length, 1)?;
destination.store(memory, location)?;
length.store(memory, location.after::<GuestPointer>())?;
memory.write(destination, self.as_bytes())
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let length = u32::try_from(self.len())?;
let destination = memory.allocate(length, 1)?;
memory.write(destination, self.as_bytes())?;
Ok(destination.lower(memory)? + hlist![length as i32])
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/sync.rs | linera-witty/src/type_traits/implementations/std/sync.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for types from [`std::sync`].
use std::sync::Arc;
impl_for_wrapper_type!(Arc);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/integers.rs | linera-witty/src/type_traits/implementations/std/integers.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for integer primitives.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
macro_rules! impl_wit_traits {
($integer:ty, $wit_name:literal, 1) => {
impl WitType for $integer {
const SIZE: u32 = 1;
type Layout = HList![$integer];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
$wit_name.into()
}
fn wit_type_declaration() -> Cow<'static, str> {
"".into()
}
}
impl WitLoad for $integer {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let slice = memory.read(location, 1)?;
Ok(slice[0] as $integer)
}
fn lift_from<Instance>(
hlist_pat![value]: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(value as $integer)
}
}
impl WitStore for $integer {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
memory.write(location, &[*self as u8])
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(hlist![*self as i32])
}
}
};
($integer:ty, $wit_name:literal, $size:expr, $flat_type:ty) => {
impl_wit_traits!(
$integer,
$wit_name,
"",
$size,
($integer),
($flat_type),
self -> hlist![*self as $flat_type],
hlist_pat![value] => value as Self
);
};
(
$integer:ty,
$wit_name:literal,
$wit_declaration:literal,
$size:expr,
($( $simple_types:ty ),*),
($( $flat_types:ty ),*),
$this:ident -> $lower:expr,
$lift_pattern:pat => $lift:expr
) => {
impl WitType for $integer {
const SIZE: u32 = $size;
type Layout = HList![$( $simple_types ),*];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
$wit_name.into()
}
fn wit_type_declaration() -> Cow<'static, str> {
$wit_declaration.into()
}
}
impl WitLoad for $integer {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let slice = memory.read(location, Self::SIZE)?;
let bytes = (*slice).try_into().expect("Incorrect number of bytes read");
Ok(Self::from_le_bytes(bytes))
}
fn lift_from<Instance>(
$lift_pattern: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok($lift)
}
}
impl WitStore for $integer {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
memory.write(location, &self.to_le_bytes())
}
fn lower<Instance>(
&$this,
_memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok($lower)
}
}
};
}
impl_wit_traits!(u8, "u8", 1);
impl_wit_traits!(i8, "s8", 1);
impl_wit_traits!(u16, "u16", 2, i32);
impl_wit_traits!(i16, "s16", 2, i32);
impl_wit_traits!(u32, "u32", 4, i32);
impl_wit_traits!(i32, "s32", 4, i32);
impl_wit_traits!(u64, "u64", 8, i64);
impl_wit_traits!(i64, "s64", 8, i64);
macro_rules! x128_lower {
($this:ident) => {
hlist![
($this & ((1 << 64) - 1)) as i64,
(($this >> 64) & ((1 << 64) - 1)) as i64,
]
};
}
impl_wit_traits!(
u128,
"u128",
" type u128 = tuple<u64, u64>;\n",
16,
(u64, u64),
(i64, i64),
self -> x128_lower!(self),
hlist_pat![least_significant_bytes, most_significant_bytes] => {
((most_significant_bytes as Self) << 64)
| (least_significant_bytes as Self & ((1 << 64) - 1))
}
);
impl_wit_traits!(
i128,
"s128",
" type s128 = tuple<s64, s64>;\n",
16,
(i64, i64),
(i64, i64),
self -> x128_lower!(self),
hlist_pat![least_significant_bytes, most_significant_bytes] => {
((most_significant_bytes as Self) << 64)
| (least_significant_bytes as Self & ((1 << 64) - 1))
}
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/floats.rs | linera-witty/src/type_traits/implementations/std/floats.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for float primitives.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
macro_rules! impl_wit_traits {
($float:ty, $wit_name:literal, $size:expr) => {
impl WitType for $float {
const SIZE: u32 = $size;
type Layout = HList![$float];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
$wit_name.into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// Primitive types don't need to be declared
"".into()
}
}
impl WitLoad for $float {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let slice = memory.read(location, Self::SIZE)?;
let bytes = (*slice).try_into().expect("Incorrect number of bytes read");
Ok(Self::from_le_bytes(bytes))
}
fn lift_from<Instance>(
hlist_pat![value]: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(value)
}
}
impl WitStore for $float {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
memory.write(location, &self.to_le_bytes())
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(hlist![*self])
}
}
};
}
impl_wit_traits!(f32, "float32", 4);
impl_wit_traits!(f64, "float64", 8);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/slices.rs | linera-witty/src/type_traits/implementations/std/slices.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for slice types.
use std::{borrow::Cow, ops::Deref, rc::Rc, sync::Arc};
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
/// A macro to implement [`WitType`], [`WitLoad`] and [`WitStore`] for a slice wrapper type.
///
/// This assumes that:
/// - The type is `$wrapper<[T]>`
/// - The type implements `From<Box<[T]>>`
/// - The type implements `Deref<Target = [T]>`
macro_rules! impl_wit_traits_for_slice_wrapper {
($wrapper:ident) => {
impl_wit_type_as_slice!($wrapper);
impl_wit_store_as_slice!($wrapper);
impl_wit_load_as_boxed_slice!($wrapper);
};
}
/// A macro to implement [`WitType`] for a slice wrapper type.
///
/// This assumes that:
/// - The type is `$wrapper<[T]>`
macro_rules! impl_wit_type_as_slice {
($wrapper:ident) => {
impl<T> WitType for $wrapper<[T]>
where
T: WitType,
{
const SIZE: u32 = <[T] as WitType>::SIZE;
type Layout = <[T] as WitType>::Layout;
type Dependencies = <[T] as WitType>::Dependencies;
fn wit_type_name() -> Cow<'static, str> {
<[T] as WitType>::wit_type_name()
}
fn wit_type_declaration() -> Cow<'static, str> {
<[T] as WitType>::wit_type_declaration()
}
}
};
}
/// A macro to implement [`WitStore`] for a slice wrapper type.
///
/// This assumes that:
/// - The type is `$wrapper<[T]>`
/// - The type implements `Deref<Target = [T]>`
macro_rules! impl_wit_store_as_slice {
($wrapper:ident) => {
impl<T> WitStore for $wrapper<[T]>
where
T: WitStore,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.deref().store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
self.deref().lower(memory)
}
}
};
}
/// A macro to implement [`WitLoad`] for a slice wrapper type.
///
/// This assumes that:
/// - The type is `$wrapper<[T]>`
/// - The type implements `From<Box<[T]>>`
macro_rules! impl_wit_load_as_boxed_slice {
($wrapper:ident) => {
impl<T> WitLoad for $wrapper<[T]>
where
T: WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
<Box<[T]> as WitLoad>::load(memory, location).map($wrapper::from)
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
<Box<[T]> as WitLoad>::lift_from(flat_layout, memory).map($wrapper::from)
}
}
};
}
impl<T> WitType for [T]
where
T: WitType,
{
const SIZE: u32 = 8;
type Layout = HList![i32, i32];
type Dependencies = HList![T];
fn wit_type_name() -> Cow<'static, str> {
format!("list<{}>", T::wit_type_name()).into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// The native `list` type doesn't need to be declared
"".into()
}
}
impl<T> WitStore for [T]
where
T: WitStore,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
// There's no need to account for padding between the elements, because the element's size
// is always aligned:
// https://github.com/WebAssembly/component-model/blob/cbdd15d9033446558571824af52a78022aaa3f58/design/mvp/CanonicalABI.md#element-size
let length = u32::try_from(self.len())?;
let size = length * T::SIZE;
let destination = memory.allocate(size, <T::Layout as Layout>::ALIGNMENT)?;
destination.store(memory, location)?;
length.store(memory, location.after::<GuestPointer>())?;
self.iter()
.zip(0..)
.try_for_each(|(element, index)| element.store(memory, destination.index::<T>(index)))
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
// There's no need to account for padding between the elements, because the element's size
// is always aligned:
// https://github.com/WebAssembly/component-model/blob/cbdd15d9033446558571824af52a78022aaa3f58/design/mvp/CanonicalABI.md#element-size
let length = u32::try_from(self.len())?;
let size = length * T::SIZE;
let destination = memory.allocate(size, <T::Layout as Layout>::ALIGNMENT)?;
self.iter().zip(0..).try_for_each(|(element, index)| {
element.store(memory, destination.index::<T>(index))
})?;
Ok(destination.lower(memory)? + hlist![length as i32])
}
}
impl_wit_type_as_slice!(Box);
impl_wit_store_as_slice!(Box);
impl<T> WitLoad for Box<[T]>
where
T: WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let address = GuestPointer::load(memory, location)?;
let length = u32::load(memory, location.after::<GuestPointer>())?;
(0..length)
.map(|index| T::load(memory, address.index::<T>(index)))
.collect()
}
fn lift_from<Instance>(
hlist_pat![address, length]: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let address = GuestPointer(address.try_into()?);
let length = length as u32;
(0..length)
.map(|index| T::load(memory, address.index::<T>(index)))
.collect()
}
}
impl_wit_traits_for_slice_wrapper!(Rc);
impl_wit_traits_for_slice_wrapper!(Arc);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/phantom_data.rs | linera-witty/src/type_traits/implementations/std/phantom_data.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`PhantomData`] type.
use std::{borrow::Cow, marker::PhantomData};
use frunk::{hlist, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl<T> WitType for PhantomData<T> {
const SIZE: u32 = 0;
type Layout = HList![];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"unit".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// The `unit` type used doesn't need to be declared
"".into()
}
}
impl<T> WitLoad for PhantomData<T> {
fn load<Instance>(
_memory: &Memory<'_, Instance>,
_location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(PhantomData)
}
fn lift_from<Instance>(
_flat_layout: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(PhantomData)
}
}
impl<T> WitStore for PhantomData<T> {
fn store<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
_location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(())
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(hlist![])
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/time.rs | linera-witty/src/type_traits/implementations/std/time.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the Rust time types.
use std::{borrow::Cow, time::Duration};
use frunk::HList;
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for Duration {
const SIZE: u32 = <HList![u64, u32] as WitType>::SIZE;
type Layout = <HList![u64, u32] as WitType>::Layout;
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"duration".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
" type duration = tuple<u64, u32>;".into()
}
}
impl WitLoad for Duration {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (secs, nanos) = <(u64, u32) as WitLoad>::load(memory, location)?;
Ok(Duration::new(secs, nanos))
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (secs, nanos) = <(u64, u32) as WitLoad>::lift_from(flat_layout, memory)?;
Ok(Duration::new(secs, nanos))
}
}
impl WitStore for Duration {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let secs = self.as_secs();
let nanos = self.subsec_nanos();
(secs, nanos).store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let secs = self.as_secs();
let nanos = self.subsec_nanos();
(secs, nanos).lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/primitives.rs | linera-witty/src/type_traits/implementations/std/primitives.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for other standard primitive types.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for bool {
const SIZE: u32 = 1;
type Layout = HList![i8];
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"bool".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// Primitive types don't need to be declared
"".into()
}
}
impl WitLoad for bool {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(u8::load(memory, location)? != 0)
}
fn lift_from<Instance>(
hlist_pat![value]: <Self::Layout as Layout>::Flat,
_memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(value != 0)
}
}
impl WitStore for bool {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let value: u8 = if *self { 1 } else { 0 };
value.store(memory, location)
}
fn lower<Instance>(
&self,
_memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
Ok(hlist![i32::from(*self)])
}
}
impl<T> WitType for &T
where
T: WitType + ?Sized,
{
const SIZE: u32 = T::SIZE;
type Layout = T::Layout;
type Dependencies = T::Dependencies;
fn wit_type_name() -> Cow<'static, str> {
T::wit_type_name()
}
fn wit_type_declaration() -> Cow<'static, str> {
T::wit_type_declaration()
}
}
impl<T> WitStore for &T
where
T: WitStore + ?Sized,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
T::store(self, memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
T::lower(self, memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/collections.rs | linera-witty/src/type_traits/implementations/std/collections.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the Rust collection types.
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
};
use frunk::HList;
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl<K, V> WitType for BTreeMap<K, V>
where
K: WitType,
V: WitType,
(K, V): WitType,
{
const SIZE: u32 = <Vec<(K, V)> as WitType>::SIZE;
type Layout = <Vec<(K, V)> as WitType>::Layout;
type Dependencies = HList![K, V];
fn wit_type_name() -> Cow<'static, str> {
<Vec<(K, V)> as WitType>::wit_type_name()
}
fn wit_type_declaration() -> Cow<'static, str> {
<Vec<(K, V)> as WitType>::wit_type_declaration()
}
}
impl<K, V> WitLoad for BTreeMap<K, V>
where
K: WitType + Ord,
V: WitType,
(K, V): WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = <Vec<(K, V)> as WitLoad>::load(memory, location)?;
Ok(entries.into_iter().collect())
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = <Vec<(K, V)> as WitLoad>::lift_from(flat_layout, memory)?;
Ok(entries.into_iter().collect())
}
}
impl<K, V> WitStore for BTreeMap<K, V>
where
K: WitType,
V: WitType,
(K, V): WitStore,
for<'a> (&'a K, &'a V): WitStore,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = self.iter().collect::<Vec<(&K, &V)>>();
entries.store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = self.iter().collect::<Vec<(&K, &V)>>();
entries.lower(memory)
}
}
impl<T> WitType for BTreeSet<T>
where
T: WitType,
{
const SIZE: u32 = <Vec<T> as WitType>::SIZE;
type Layout = <Vec<T> as WitType>::Layout;
type Dependencies = HList![T];
fn wit_type_name() -> Cow<'static, str> {
<Vec<T> as WitType>::wit_type_name()
}
fn wit_type_declaration() -> Cow<'static, str> {
<Vec<T> as WitType>::wit_type_declaration()
}
}
impl<T> WitLoad for BTreeSet<T>
where
T: WitType + Ord + WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = <Vec<T> as WitLoad>::load(memory, location)?;
Ok(entries.into_iter().collect())
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = <Vec<T> as WitLoad>::lift_from(flat_layout, memory)?;
Ok(entries.into_iter().collect())
}
}
impl<T> WitStore for BTreeSet<T>
where
T: WitType + WitStore,
for<'a> &'a T: WitStore,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = self.iter().collect::<Vec<&T>>();
entries.store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<Self::Layout, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let entries = self.iter().collect::<Vec<&T>>();
entries.lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/result.rs | linera-witty/src/type_traits/implementations/std/result.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`Result`] type.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HCons, HList};
use crate::{
GuestPointer, InstanceWithMemory, JoinFlatLayouts, Layout, Memory, Merge, Runtime,
RuntimeError, RuntimeMemory, WitLoad, WitStore, WitType,
};
impl<T, E> WitType for Result<T, E>
where
T: WitType,
E: WitType,
T::Layout: Merge<E::Layout>,
<T::Layout as Merge<E::Layout>>::Output: Layout,
{
const SIZE: u32 = {
let ok_alignment = <T::Layout as Layout>::ALIGNMENT;
let err_alignment = <E::Layout as Layout>::ALIGNMENT;
let padding = if ok_alignment > err_alignment {
ok_alignment - 1
} else {
err_alignment - 1
};
if T::SIZE > E::SIZE {
1 + padding + T::SIZE
} else {
1 + padding + E::SIZE
}
};
type Layout = HCons<i8, <T::Layout as Merge<E::Layout>>::Output>;
type Dependencies = HList![T, E];
fn wit_type_name() -> Cow<'static, str> {
format!("result<{}, {}>", T::wit_type_name(), E::wit_type_name()).into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// The native `result` type doesn't need to be declared
"".into()
}
}
impl<T, E> WitLoad for Result<T, E>
where
T: WitLoad,
E: WitLoad,
T::Layout: Merge<E::Layout>,
<T::Layout as Merge<E::Layout>>::Output: Layout,
<T::Layout as Layout>::Flat:
JoinFlatLayouts<<<T::Layout as Merge<E::Layout>>::Output as Layout>::Flat>,
<E::Layout as Layout>::Flat:
JoinFlatLayouts<<<T::Layout as Merge<E::Layout>>::Output as Layout>::Flat>,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let is_err = bool::load(memory, location)?;
let location = location
.after::<bool>()
.after_padding_for::<T>()
.after_padding_for::<E>();
match is_err {
true => Ok(Err(E::load(memory, location)?)),
false => Ok(Ok(T::load(memory, location)?)),
}
}
fn lift_from<Instance>(
hlist_pat![is_err, ...value_layout]: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let is_err = bool::lift_from(hlist![is_err], memory)?;
match is_err {
false => Ok(Ok(T::lift_from(
JoinFlatLayouts::from_joined(value_layout),
memory,
)?)),
true => Ok(Err(E::lift_from(
JoinFlatLayouts::from_joined(value_layout),
memory,
)?)),
}
}
}
impl<T, E> WitStore for Result<T, E>
where
T: WitStore,
E: WitStore,
T::Layout: Merge<E::Layout>,
<T::Layout as Merge<E::Layout>>::Output: Layout,
<T::Layout as Layout>::Flat:
JoinFlatLayouts<<<T::Layout as Merge<E::Layout>>::Output as Layout>::Flat>,
<E::Layout as Layout>::Flat:
JoinFlatLayouts<<<T::Layout as Merge<E::Layout>>::Output as Layout>::Flat>,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let data_location = location
.after::<bool>()
.after_padding_for::<T>()
.after_padding_for::<E>();
match self {
Ok(value) => {
false.store(memory, location)?;
value.store(memory, data_location)
}
Err(error) => {
true.store(memory, location)?;
error.store(memory, data_location)
}
}
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
match self {
Ok(value) => Ok(false.lower(memory)? + value.lower(memory)?.into_joined()),
Err(error) => Ok(true.lower(memory)? + error.lower(memory)?.into_joined()),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/option.rs | linera-witty/src/type_traits/implementations/std/option.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`Option`] type.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HCons, HList, HNil};
use crate::{
GuestPointer, InstanceWithMemory, JoinFlatLayouts, Layout, Memory, Merge, Runtime,
RuntimeError, RuntimeMemory, WitLoad, WitStore, WitType,
};
impl<T> WitType for Option<T>
where
T: WitType,
HNil: Merge<T::Layout>,
<HNil as Merge<T::Layout>>::Output: Layout,
{
const SIZE: u32 = {
let padding = <T::Layout as Layout>::ALIGNMENT - 1;
1 + padding + T::SIZE
};
type Layout = HCons<i8, <HNil as Merge<T::Layout>>::Output>;
type Dependencies = HList![T];
fn wit_type_name() -> Cow<'static, str> {
format!("option<{}>", T::wit_type_name()).into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// The native `option` type doesn't need to be declared
"".into()
}
}
impl<T> WitLoad for Option<T>
where
T: WitLoad,
HNil: Merge<T::Layout>,
<HNil as Merge<T::Layout>>::Output: Layout,
<T::Layout as Layout>::Flat:
JoinFlatLayouts<<<HNil as Merge<T::Layout>>::Output as Layout>::Flat>,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let is_some = bool::load(memory, location)?;
match is_some {
true => Ok(Some(T::load(
memory,
location.after::<bool>().after_padding_for::<T>(),
)?)),
false => Ok(None),
}
}
fn lift_from<Instance>(
hlist_pat![is_some, ...value_layout]: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let is_some = bool::lift_from(hlist![is_some], memory)?;
if is_some {
Ok(Some(T::lift_from(
JoinFlatLayouts::from_joined(value_layout),
memory,
)?))
} else {
Ok(None)
}
}
}
impl<T> WitStore for Option<T>
where
T: WitStore,
HNil: Merge<T::Layout>,
<HNil as Merge<T::Layout>>::Output: Layout,
<T::Layout as Layout>::Flat:
JoinFlatLayouts<<<HNil as Merge<T::Layout>>::Output as Layout>::Flat>,
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
match self {
Some(value) => {
true.store(memory, location)?;
value.store(memory, location.after::<bool>().after_padding_for::<T>())
}
None => false.store(memory, location),
}
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
match self {
Some(value) => Ok(true.lower(memory)? + value.lower(memory)?.into_joined()),
None => Ok(false.lower(memory)? + Default::default()),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/rc.rs | linera-witty/src/type_traits/implementations/std/rc.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the [`Rc`] type.
use std::rc::Rc;
impl_for_wrapper_type!(Rc);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/mod.rs | linera-witty/src/type_traits/implementations/std/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for types from the standard library.
/// A macro to implement [`WitType`][super::WitType], [`WitLoad`][super::WitLoad] and
/// [`WitStore`][super::WitStore] for a simple wrapper type.
///
/// This assumes that:
/// - The type is `$wrapper<T>`
/// - It can be constructed with `$wrapper::new(instance_to_wrap)`
/// - The type implements `Deref<Target = T>`
macro_rules! impl_for_wrapper_type {
($wrapper:ident) => {
impl<T> crate::WitType for $wrapper<T>
where
T: crate::WitType,
{
const SIZE: u32 = T::SIZE;
type Layout = T::Layout;
type Dependencies = T::Dependencies;
fn wit_type_name() -> ::std::borrow::Cow<'static, str> {
T::wit_type_name()
}
fn wit_type_declaration() -> ::std::borrow::Cow<'static, str> {
T::wit_type_declaration()
}
}
impl<T> crate::WitLoad for $wrapper<T>
where
T: crate::WitLoad,
{
fn load<Instance>(
memory: &crate::Memory<'_, Instance>,
location: crate::GuestPointer,
) -> Result<Self, crate::RuntimeError>
where
Instance: crate::InstanceWithMemory,
<Instance::Runtime as crate::Runtime>::Memory: crate::RuntimeMemory<Instance>,
{
T::load(memory, location).map($wrapper::new)
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as crate::Layout>::Flat,
memory: &crate::Memory<'_, Instance>,
) -> Result<Self, crate::RuntimeError>
where
Instance: crate::InstanceWithMemory,
<Instance::Runtime as crate::Runtime>::Memory: crate::RuntimeMemory<Instance>,
{
T::lift_from(flat_layout, memory).map($wrapper::new)
}
}
impl<T> crate::WitStore for $wrapper<T>
where
T: crate::WitStore,
{
fn store<Instance>(
&self,
memory: &mut crate::Memory<'_, Instance>,
location: crate::GuestPointer,
) -> Result<(), crate::RuntimeError>
where
Instance: crate::InstanceWithMemory,
<Instance::Runtime as crate::Runtime>::Memory: crate::RuntimeMemory<Instance>,
{
<$wrapper<T> as ::std::ops::Deref>::deref(self).store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut crate::Memory<'_, Instance>,
) -> Result<<Self::Layout as crate::Layout>::Flat, crate::RuntimeError>
where
Instance: crate::InstanceWithMemory,
<Instance::Runtime as crate::Runtime>::Memory: crate::RuntimeMemory<Instance>,
{
<$wrapper<T> as ::std::ops::Deref>::deref(self).lower(memory)
}
}
};
}
mod r#box;
mod collections;
mod floats;
mod integers;
mod option;
mod phantom_data;
mod primitives;
mod rc;
mod result;
mod slices;
mod string;
mod sync;
mod time;
mod tuples;
mod vec;
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/type_traits/implementations/std/tuples.rs | linera-witty/src/type_traits/implementations/std/tuples.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the custom traits for the tuple types.
use std::borrow::Cow;
use frunk::{hlist, hlist_pat, HList};
use crate::{
GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
/// Implement [`WitType`], [`WitLoad`] and [`WitStore`].
///
/// When implementing [`WitStore`] for tuples, it's necessary to deconstruct the tuple and rebuild
/// it as a heterogeneous list. However, because the methods receive `&self`, the deconstruction
/// leads to references to the elements. Therefore an extra constraint is necessary, which is that
/// the reference also implements [`WitStore`] and that the layout is the same as the referenced
/// type.
///
/// Using this clause for the unit type leads to a compiler error, because it tries to match the
/// layout type to itself, which the compiler doesn't handle correctly. The solution to this is to
/// only add the clause for the implementations that have elements.
macro_rules! impl_wit_traits {
() => {
impl_wit_traits_with_borrow_store_clause!(;);
};
($( $names:ident : $types:ident ),*) => {
impl_wit_traits_with_borrow_store_clause!(
$( $names: $types ),* ;
for<'a> HList![$( &'a $types ),*]:
WitType<Layout = <HList![$( $types ),*] as WitType>::Layout> + WitStore,
);
};
}
/// Implement [`WitType`], [`WitLoad`] and [`WitStore`], using the optional extra where clause.
///
/// See [`impl_wit_traits`] above for why the extra clause is optional and can't be used with the
/// implementation for the unit type.
macro_rules! impl_wit_traits_with_borrow_store_clause {
($( $names:ident : $types:ident ),* ; $( $borrow_store_clause:tt )*) => {
impl<$( $types ),*> WitType for ($( $types, )*)
where
$( $types: WitType, )*
HList![$( $types ),*]: WitType,
{
const SIZE: u32 = <HList![$( $types ),*] as WitType>::SIZE;
type Layout = <HList![$( $types ),*] as WitType>::Layout;
type Dependencies = HList![$( $types ),*];
fn wit_type_name() -> Cow<'static, str> {
let elements: &[Cow<'static, str>] = &[
$( $types::wit_type_name(), )*
];
format!("tuple<{}>", elements.join(", ")).into()
}
fn wit_type_declaration() -> Cow<'static, str> {
// The native `tuple` type doesn't need to be declared
"".into()
}
}
impl<$( $types ),*> WitLoad for ($( $types, )*)
where
$( $types: WitLoad, )*
HList![$( $types ),*]: WitLoad,
{
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let hlist_pat![$( $names, )*] =
<HList![$( $types, )*] as WitLoad>::load(memory, location)?;
Ok(($( $names, )*))
}
fn lift_from<Instance>(
layout: <Self::Layout as Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let hlist_pat![$( $names, )*] =
<HList![$( $types, )*] as WitLoad>::lift_from(layout, memory)?;
Ok(($( $names, )*))
}
}
impl<$( $types ),*> WitStore for ($( $types, )*)
where
$( $types: WitStore, )*
HList![$( $types ),*]: WitStore,
$( $borrow_store_clause )*
{
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let ($( $names, )*) = self;
hlist![$( $names ),*].store(memory, location)?;
Ok(())
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let ($( $names, )*) = self;
hlist![$( $names ),*].lower(memory)
}
}
};
}
repeat_macro!(
impl_wit_traits =>
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L,
m: M,
n: N,
o: O,
p: P,
q: Q,
r: R,
s: S,
t: T,
u: U,
v: V,
w: W,
x: X,
y: Y,
z: Z,
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/array.rs | linera-witty/src/primitive_types/array.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::borrow::Cow;
use crate::{
GuestPointer, HList, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
WitLoad, WitStore, WitType,
};
impl WitType for [u8; 20] {
const SIZE: u32 = <(u64, u64, u64) as WitType>::SIZE;
type Layout = <(u64, u64, u64) as WitType>::Layout;
type Dependencies = HList![];
fn wit_type_name() -> Cow<'static, str> {
"array20".into()
}
fn wit_type_declaration() -> Cow<'static, str> {
concat!(
" record array20 {\n",
" part1: u64,\n",
" part2: u64,\n",
" part3: u64,\n",
" }\n",
)
.into()
}
}
impl WitLoad for [u8; 20] {
fn load<Instance>(
memory: &Memory<'_, Instance>,
location: GuestPointer,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (part1, part2, part3): (u64, u64, u64) = WitLoad::load(memory, location)?;
let mut dest = [0u8; 20];
dest[0..8].copy_from_slice(&part1.to_be_bytes());
dest[8..16].copy_from_slice(&part2.to_be_bytes());
dest[16..20].copy_from_slice(&part3.to_be_bytes()[0..4]);
Ok(dest)
}
fn lift_from<Instance>(
flat_layout: <Self::Layout as crate::Layout>::Flat,
memory: &Memory<'_, Instance>,
) -> Result<Self, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let (part1, part2, part3): (u64, u64, u64) = WitLoad::lift_from(flat_layout, memory)?;
let mut dest = [0u8; 20];
dest[0..8].copy_from_slice(&part1.to_be_bytes());
dest[8..16].copy_from_slice(&part2.to_be_bytes());
dest[16..20].copy_from_slice(&part3.to_be_bytes()[0..4]);
Ok(dest)
}
}
impl WitStore for [u8; 20] {
fn store<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
location: GuestPointer,
) -> Result<(), RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let part1 = u64::from_be_bytes(self[0..8].try_into().unwrap());
let part2 = u64::from_be_bytes(self[8..16].try_into().unwrap());
let part3 = (u32::from_be_bytes(self[16..20].try_into().unwrap()) as u64) << 32;
(part1, part2, part3).store(memory, location)
}
fn lower<Instance>(
&self,
memory: &mut Memory<'_, Instance>,
) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
where
Instance: InstanceWithMemory,
<Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>,
{
let part1 = u64::from_be_bytes(self[0..8].try_into().unwrap());
let part2 = u64::from_be_bytes(self[8..16].try_into().unwrap());
let part3 = (u32::from_be_bytes(self[16..20].try_into().unwrap()) as u64) << 32;
(part1, part2, part3).lower(memory)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/join_flat_types.rs | linera-witty/src/primitive_types/join_flat_types.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Implementation of the `join` operator for flattening WIT `variant` types.
//!
//! The [Component Model canonical ABI][flattening] used by WIT specifies that in order to flatten
//! a `variant` type, it is necessary to find common flat types to represent individual elements of
//! the flattened variants. This is called the `join` operator, and is basically finding the
//! widest bit-representation for the two types.
//!
//! [flattening]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening
use either::Either;
use super::FlatType;
use crate::util::ZeroExtend;
/// Trait that allows joining one of two possible flat type values into a common flat type.
pub trait JoinFlatTypes {
/// The resulting flat type.
type Flat: FlatType;
/// Joins a value that's one of two flat types into a single flat type.
fn join(self) -> Self::Flat;
}
/// Implement [`JoinFlatTypes`] for an [`Either`] type of two flat types.
macro_rules! join_flat_types {
(
$( ($left:ty, $right:ty) -> $joined:ty => ($join_left:tt, $join_right:tt $(,)?) ),* $(,)?
) => {
$(
impl JoinFlatTypes for Either<$left, $right> {
type Flat = $joined;
fn join(self) -> Self::Flat {
match self {
Either::Left(left) => {
let join_left = $join_left;
join_left(left)
}
Either::Right(right) => {
let join_right = $join_right;
join_right(right)
}
}
}
}
)*
}
}
join_flat_types!(
(i32, i32) -> i32 => (
{ |value| value },
{ |value| value },
),
(i32, i64) -> i64 => (
{ |value: i32| value.zero_extend() },
{ |value| value },
),
(i32, f32) -> i32 => (
{ |value| value },
{ |value| value as i32 },
),
(i32, f64) -> i64 => (
{ |value: i32| value.zero_extend() },
{ |value| value as i64 },
),
(i64, i32) -> i64 => (
{ |value| value },
{ |value: i32| value.zero_extend() },
),
(i64, i64) -> i64 => (
{ |value| value },
{ |value| value },
),
(i64, f32) -> i64 => (
{ |value| value },
{ |value| (value as i32).zero_extend() },
),
(i64, f64) -> i64 => (
{ |value| value },
{ |value| value as i64 },
),
(f32, i32) -> i32 => (
{ |value| value as i32 },
{ |value| value },
),
(f32, i64) -> i64 => (
{ |value| (value as i32).zero_extend() },
{ |value| value },
),
(f32, f32) -> f32 => (
{ |value| value },
{ |value| value },
),
(f32, f64) -> i64 => (
{ |value| (value as i32).zero_extend() },
{ |value| value as i64 },
),
(f64, i32) -> i64 => (
{ |value| value as i64 },
{ |value: i32| value.zero_extend() },
),
(f64, i64) -> i64 => (
{ |value| value as i64 },
{ |value| value },
),
(f64, f32) -> i64 => (
{ |value| value as i64 },
{ |value| (value as i32).zero_extend() },
),
(f64, f64) -> f64 => (
{ |value| value },
{ |value| value },
),
);
impl<AnyFlatType> JoinFlatTypes for Either<(), AnyFlatType>
where
AnyFlatType: FlatType,
{
type Flat = AnyFlatType;
fn join(self) -> Self::Flat {
match self {
Either::Left(()) => AnyFlatType::default(),
Either::Right(value) => value,
}
}
}
impl<AnyFlatType> JoinFlatTypes for Either<AnyFlatType, ()>
where
AnyFlatType: FlatType,
{
type Flat = AnyFlatType;
fn join(self) -> Self::Flat {
match self {
Either::Left(value) => value,
Either::Right(()) => AnyFlatType::default(),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/flat_type.rs | linera-witty/src/primitive_types/flat_type.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Primitive types [supported by
//! WebAssembly](https://webassembly.github.io/spec/core/syntax/types.html).
//!
//! These are types that the WebAssembly virtual machine can operate with. More importantly, these
//! are the types that can be used in function interfaces as parameter types and return types.
//!
//! The [Component Model canonical ABI used by WIT][flattening] specifies that when flattening
//! `variant` types, a "joined" flat type must be found for each element in its flat layout (see
//! [`JoinFlatTypes`][`super::JoinFlatTypes`] for more information). The [`FlatType`] trait
//! includes support for the reverse "split" operation.
//!
//! [flattening]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening
use super::SimpleType;
/// Primitive types supported by WebAssembly.
pub trait FlatType: SimpleType<Flat = Self> {
/// Splits itself from a joined `i32` flat value.
///
/// # Panics
///
/// If this flat type can't be joined into an `i32`.
fn split_from_i32(joined_i32: i32) -> Self;
/// Splits itself from a joined `i64` flat value.
///
/// # Panics
///
/// If this flat type can't be joined into an `i64`.
fn split_from_i64(joined_i64: i64) -> Self;
/// Splits itself from a joined `f32` flat value.
///
/// # Panics
///
/// If this flat type can't be joined into an `f32`.
fn split_from_f32(joined_f32: f32) -> Self;
/// Splits itself from a joined `f64` flat value.
///
/// # Panics
///
/// If this flat type can't be joined into an `f64`.
fn split_from_f64(joined_f64: f64) -> Self;
/// Splits off the `Target` flat type from this flat type.
///
/// # Panics
///
/// If the `Target` type can't be joined into this flat type.
fn split_into<Target: FlatType>(self) -> Target;
}
impl FlatType for i32 {
fn split_from_i32(joined_i32: i32) -> Self {
joined_i32
}
fn split_from_i64(joined_i64: i64) -> Self {
joined_i64
.try_into()
.expect("Invalid `i32` stored in `i64`")
}
fn split_from_f32(_joined_f32: f32) -> Self {
unreachable!("`i32` is never joined into `f32`");
}
fn split_from_f64(_joined_f64: f64) -> Self {
unreachable!("`i32` is never joined into `f64`");
}
fn split_into<Target: FlatType>(self) -> Target {
Target::split_from_i32(self)
}
}
impl FlatType for i64 {
fn split_from_i32(_joined_i32: i32) -> Self {
unreachable!("`i64` is never joined into `i32`");
}
fn split_from_i64(joined_i64: i64) -> Self {
joined_i64
}
fn split_from_f32(_joined_f32: f32) -> Self {
unreachable!("`i64` is never joined into `f32`");
}
fn split_from_f64(_joined_f64: f64) -> Self {
unreachable!("`i64` is never joined into `f64`");
}
fn split_into<Target: FlatType>(self) -> Target {
Target::split_from_i64(self)
}
}
impl FlatType for f32 {
fn split_from_i32(joined_i32: i32) -> Self {
joined_i32 as f32
}
fn split_from_i64(joined_i64: i64) -> Self {
(joined_i64 as i32) as f32
}
fn split_from_f32(joined_f32: f32) -> Self {
joined_f32
}
fn split_from_f64(_joined_f64: f64) -> Self {
unreachable!("`f32` is never joined into `f64`");
}
fn split_into<Target: FlatType>(self) -> Target {
Target::split_from_f32(self)
}
}
impl FlatType for f64 {
fn split_from_i32(_joined_i32: i32) -> Self {
unreachable!("`f64` is never joined into `i32`");
}
fn split_from_i64(joined_i64: i64) -> Self {
joined_i64 as f64
}
fn split_from_f32(_joined_f32: f32) -> Self {
unreachable!("`f64` is never joined into `f32`");
}
fn split_from_f64(joined_f64: f64) -> Self {
joined_f64
}
fn split_into<Target: FlatType>(self) -> Target {
Target::split_from_f64(self)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/simple_type.rs | linera-witty/src/primitive_types/simple_type.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Fundamental types used by WIT defined by the [Component Model] that map directly to Rust
//! primitive types.
//!
//! These are primitive types that WIT defines how to store in memory.
//!
//! [Component Model]:
//! https://github.com/WebAssembly/component-model/blob/main/design/mvp/Explainer.md#type-definitions
use super::FlatType;
/// Marker trait to prevent [`SimpleType`] from being implemented for other types.
pub trait Sealed {}
/// Primitive fundamental WIT types.
pub trait SimpleType: Default + Sealed + Sized {
/// Alignment when storing in memory, according to the [canonical ABI].
///
/// [canonical ABI]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#alignment
const ALIGNMENT: u32;
/// The underlying WebAssembly type used when flattening this type.
type Flat: FlatType;
/// Flattens this type into a [`FlatType`] that's natively supported by WebAssembly.
fn flatten(self) -> Self::Flat;
/// Unflattens this type from its [`FlatType`] representation.
fn unflatten_from(flat: Self::Flat) -> Self;
}
macro_rules! simple_type {
($impl_type:ident -> $flat:ty, $alignment:expr) => {
simple_type!($impl_type -> $flat, $alignment, { |flat| flat as $impl_type });
};
($impl_type:ident -> $flat:ty, $alignment:expr, $unflatten:tt) => {
impl Sealed for $impl_type {}
impl SimpleType for $impl_type {
const ALIGNMENT: u32 = $alignment;
type Flat = $flat;
fn flatten(self) -> Self::Flat {
self as $flat
}
fn unflatten_from(flat: Self::Flat) -> Self {
let unflatten = $unflatten;
unflatten(flat)
}
}
};
}
simple_type!(bool -> i32, 1, { |flat| flat != 0 });
simple_type!(i8 -> i32, 1);
simple_type!(i16 -> i32, 2);
simple_type!(i32 -> i32, 4);
simple_type!(i64 -> i64, 8);
simple_type!(u8 -> i32, 1);
simple_type!(u16 -> i32, 2);
simple_type!(u32 -> i32, 4);
simple_type!(u64 -> i64, 8);
simple_type!(f32 -> f32, 4);
simple_type!(f64 -> f64, 8);
simple_type!(char -> i32, 4,
{ |flat| char::from_u32(flat as u32).expect("Attempt to unflatten an invalid `char`") }
);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/mod.rs | linera-witty/src/primitive_types/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Primitive WebAssembly and WIT types.
mod array;
mod flat_type;
mod join_flat_types;
mod maybe_flat_type;
mod simple_type;
pub use self::{
flat_type::FlatType, join_flat_types::JoinFlatTypes, maybe_flat_type::MaybeFlatType,
simple_type::SimpleType,
};
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/src/primitive_types/maybe_flat_type.rs | linera-witty/src/primitive_types/maybe_flat_type.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! A representation of either a [`FlatType`] or nothing, represented by the unit (`()`) type.
use frunk::HCons;
use super::flat_type::FlatType;
use crate::{memory_layout::FlatLayout, Layout};
/// A marker trait for [`FlatType`]s and the unit type, which uses no storage space.
pub trait MaybeFlatType: Default + Sized {
/// Result of flattening the layout made up of the current element followed by `Tail`.
type Flatten<Tail: Layout>: FlatLayout;
/// Flattens a layout that starts with this [`MaybeFlatType`] followed by a provided `Tail`.
fn flatten<Tail>(self, tail: Tail) -> Self::Flatten<Tail>
where
Tail: Layout;
}
impl MaybeFlatType for () {
type Flatten<Tail: Layout> = Tail::Flat;
fn flatten<Tail>(self, tail: Tail) -> Self::Flatten<Tail>
where
Tail: Layout,
{
tail.flatten()
}
}
impl<AnyFlatType> MaybeFlatType for AnyFlatType
where
AnyFlatType: FlatType,
{
type Flatten<Tail: Layout> = HCons<Self, Tail::Flat>;
fn flatten<Tail>(self, tail: Tail) -> Self::Flatten<Tail>
where
Tail: Layout,
{
HCons {
head: self.flatten(),
tail: tail.flatten(),
}
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/wit_type.rs | linera-witty/tests/wit_type.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `WitType` derive macro.
#[path = "common/types.rs"]
mod types;
use std::{collections::BTreeMap, rc::Rc, sync::Arc};
use linera_witty::{HList, Layout, RegisterWitTypes, WitType};
use self::types::{
Branch, Enum, Leaf, RecordWithDoublePadding, SimpleWrapper, SliceWrapper,
SpecializedGenericEnum, SpecializedGenericStruct, StructWithHeapFields, StructWithLists,
TupleWithPadding, TupleWithoutPadding,
};
/// Checks the memory size, layout and WIT type declaration derived for a wrapper type.
#[test]
fn test_simple_bool_wrapper() {
test_wit_type_implementation::<SimpleWrapper>(ExpectedMetadata {
size: 1,
alignment: 1,
flat_layout_length: 1,
declaration: concat!(
" record simple-wrapper {\n",
" inner0: bool,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for a type with multiple fields
/// ordered in a way that doesn't require any padding.
#[test]
fn test_tuple_struct_without_padding() {
test_wit_type_implementation::<TupleWithoutPadding>(ExpectedMetadata {
size: 16,
alignment: 8,
flat_layout_length: 3,
declaration: concat!(
" record tuple-without-padding {\n",
" inner0: u64,\n",
" inner1: s32,\n",
" inner2: s16,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for a type with multiple fields
/// ordered in a way that requires padding between all fields.
#[test]
fn test_tuple_struct_with_padding() {
test_wit_type_implementation::<TupleWithPadding>(ExpectedMetadata {
size: 16,
alignment: 8,
flat_layout_length: 3,
declaration: concat!(
" record tuple-with-padding {\n",
" inner0: u16,\n",
" inner1: u32,\n",
" inner2: s64,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for a type with multiple named
/// fields ordered in a way that requires padding before two fields.
#[test]
fn test_named_struct_with_double_padding() {
test_wit_type_implementation::<RecordWithDoublePadding>(ExpectedMetadata {
size: 24,
alignment: 8,
flat_layout_length: 4,
declaration: concat!(
" record record-with-double-padding {\n",
" first: u16,\n",
" second: u32,\n",
" third: s8,\n",
" fourth: s64,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT type declarations derived for a type that contains a
/// field with a type that also has `WitType` derived for it.
#[test]
fn test_nested_types() {
test_wit_type_implementation::<Leaf>(ExpectedMetadata {
size: 24,
alignment: 8,
flat_layout_length: 3,
declaration: concat!(
" record leaf {\n",
" first: bool,\n",
" second: u128,\n",
" }\n\n",
" type u128 = tuple<u64, u64>;\n"
),
});
test_wit_type_implementation::<Branch>(ExpectedMetadata {
size: 56,
alignment: 8,
flat_layout_length: 7,
declaration: concat!(
" record branch {\n",
" tag: u16,\n",
" first-leaf: leaf,\n",
" second-leaf: leaf,\n",
" }\n\n",
" record leaf {\n",
" first: bool,\n",
" second: u128,\n",
" }\n\n",
" type u128 = tuple<u64, u64>;\n"
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for an `enum` type.
#[test]
fn test_enum_type() {
test_wit_type_implementation::<Enum>(ExpectedMetadata {
size: 24,
alignment: 8,
flat_layout_length: 11,
declaration: concat!(
" variant enum {\n",
" empty,\n",
" large-variant-with-loose-alignment(\
tuple<s8, s8, s8, s8, s8, s8, s8, s8, s8, s8>\
),\n",
" smaller-variant-with-strict-alignment(u64),\n",
" }\n",
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for a specialized generic
/// `struct` type.
#[test]
fn test_specialized_generic_struct() {
test_wit_type_implementation::<SpecializedGenericStruct<u8, i16>>(ExpectedMetadata {
size: 12,
alignment: 4,
flat_layout_length: 4,
declaration: concat!(
" record specialized-generic-struct {\n",
" first: u8,\n",
" second: s16,\n",
" both: list<tuple<u8, s16>>,\n",
" }\n",
),
});
}
/// Checks the memory size, layout and WIT type declaration derived for a specialized generic `enum`
/// type.
#[test]
fn test_specialized_generic_enum_type() {
test_wit_type_implementation::<SpecializedGenericEnum<Option<bool>, u32>>(ExpectedMetadata {
size: 12,
alignment: 4,
flat_layout_length: 3,
declaration: concat!(
" variant specialized-generic-enum {\n",
" none,\n",
" first(option<bool>),\n",
" maybe-second(option<u32>),\n",
" }\n",
),
});
}
/// Checks the memory size, layout and WIT declaration derived for a complex type that has heap
/// allocated fields.
#[test]
fn test_heap_allocated_fields() {
test_wit_type_implementation::<StructWithHeapFields>(ExpectedMetadata {
size: 56,
alignment: 8,
flat_layout_length: 15,
declaration: concat!(
" variant enum {\n",
" empty,\n",
" large-variant-with-loose-alignment(\
tuple<s8, s8, s8, s8, s8, s8, s8, s8, s8, s8>\
),\n",
" smaller-variant-with-strict-alignment(u64),\n",
" }\n\n",
" record leaf {\n",
" first: bool,\n",
" second: u128,\n",
" }\n\n",
" record simple-wrapper {\n",
" inner0: bool,\n",
" }\n\n",
" record struct-with-heap-fields {\n",
" boxed: simple-wrapper,\n",
" rced: leaf,\n",
" arced: enum,\n",
" }\n\n",
" type u128 = tuple<u64, u64>;\n",
),
});
}
/// Checks the memory size, layout and WIT declaration derived for a slice type.
#[test]
fn test_slice() {
test_wit_type_implementation::<[SimpleWrapper]>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record simple-wrapper {\n",
" inner0: bool,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT declaration derived for a [`Vec`] type.
#[test]
fn test_vec() {
test_wit_type_implementation::<Vec<SimpleWrapper>>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record simple-wrapper {\n",
" inner0: bool,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT declaration derived for a boxed slice type.
#[test]
fn test_boxed_slice() {
test_wit_type_implementation::<Box<[TupleWithPadding]>>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record tuple-with-padding {\n",
" inner0: u16,\n",
" inner1: u32,\n",
" inner2: s64,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT declaration derived for an rc-ed slice type.
#[test]
fn test_rced_slice() {
test_wit_type_implementation::<Rc<[Leaf]>>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record leaf {\n",
" first: bool,\n",
" second: u128,\n",
" }\n\n",
" type u128 = tuple<u64, u64>;\n"
),
});
}
/// Checks the memory size, layout and WIT declaration derived for an arc-ed slice type.
#[test]
fn test_arced_slice() {
test_wit_type_implementation::<Arc<[RecordWithDoublePadding]>>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record record-with-double-padding {\n",
" first: u16,\n",
" second: u32,\n",
" third: s8,\n",
" fourth: s64,\n",
" }\n"
),
});
}
/// Check the memory size, layout and WIT declaration derived for a type that has a slice
/// field.
#[test]
fn test_slice_field() {
test_wit_type_implementation::<SliceWrapper>(ExpectedMetadata {
size: 8,
alignment: 4,
flat_layout_length: 2,
declaration: concat!(
" record slice-wrapper {\n",
" inner0: list<tuple-without-padding>,\n",
" }\n\n",
" record tuple-without-padding {\n",
" inner0: u64,\n",
" inner1: s32,\n",
" inner2: s16,\n",
" }\n"
),
});
}
/// Checks the memory size, layout and WIT declaration derived for a type that has list
/// fields.
#[test]
fn test_list_fields() {
test_wit_type_implementation::<StructWithLists>(ExpectedMetadata {
size: 32,
alignment: 4,
flat_layout_length: 8,
declaration: concat!(
" record leaf {\n",
" first: bool,\n",
" second: u128,\n",
" }\n\n",
" record record-with-double-padding {\n",
" first: u16,\n",
" second: u32,\n",
" third: s8,\n",
" fourth: s64,\n",
" }\n\n",
" record simple-wrapper {\n",
" inner0: bool,\n",
" }\n\n",
" record struct-with-lists {\n",
" vec: list<simple-wrapper>,\n",
" boxed-slice: list<tuple-with-padding>,\n",
" rced-slice: list<leaf>,\n",
" arced-slice: list<record-with-double-padding>,\n",
" }\n\n",
" record tuple-with-padding {\n",
" inner0: u16,\n",
" inner1: u32,\n",
" inner2: s64,\n",
" }\n\n",
" type u128 = tuple<u64, u64>;\n"
),
});
}
/// Helper type to make visible what each metadata value is.
#[derive(Clone, Copy, Debug)]
struct ExpectedMetadata {
size: u32,
alignment: u32,
flat_layout_length: usize,
declaration: &'static str,
}
/// Tests that a type `T` and wrapped versions of it have the `expected` [`WitType`] metadata in
/// their implementations.
fn test_wit_type_implementation<T>(expected: ExpectedMetadata)
where
T: WitType + ?Sized + 'static,
Box<T>: WitType,
Rc<T>: WitType,
Arc<T>: WitType,
{
test_single_wit_type_implementation::<&'static T>(expected);
test_single_wit_type_implementation::<Box<T>>(expected);
test_single_wit_type_implementation::<Rc<T>>(expected);
test_single_wit_type_implementation::<Arc<T>>(expected);
}
/// Tests that a type `T` has the `expected` [`WitType`] metadata in its implementation.
fn test_single_wit_type_implementation<T>(expected: ExpectedMetadata)
where
T: WitType,
{
assert_eq!(T::SIZE, expected.size);
assert_eq!(<T as WitType>::Layout::ALIGNMENT, expected.alignment);
assert_eq!(
<<T as WitType>::Layout as Layout>::Flat::LEN,
expected.flat_layout_length
);
assert_eq!(wit_type_declaration_of::<T>(), expected.declaration);
}
/// Returns the WIT snippet with the type declarations for `T`.
fn wit_type_declaration_of<T>() -> String
where
T: WitType,
{
let mut wit_types = BTreeMap::new();
<HList![T] as RegisterWitTypes>::register_wit_types(&mut wit_types);
wit_types
.into_values()
.filter(|declaration| !declaration.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/wit_load.rs | linera-witty/tests/wit_load.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `WitLoad` derive macro.
#[path = "common/types.rs"]
mod types;
use std::{fmt::Debug, iter, rc::Rc, sync::Arc};
use assert_matches::assert_matches;
use linera_witty::{hlist, InstanceWithMemory, Layout, MockInstance, RuntimeError, WitLoad};
use self::types::{
Branch, Enum, Leaf, RecordWithDoublePadding, SimpleWrapper, SpecializedGenericEnum,
SpecializedGenericStruct, StructWithHeapFields, StructWithLists, TupleWithPadding,
TupleWithoutPadding,
};
/// Checks that a wrapper type is properly loaded from memory and lifted from its flat layout.
#[test]
fn test_simple_bool_wrapper() {
test_load_from_memory(&[1], SimpleWrapper(true));
test_load_from_memory(&[0], SimpleWrapper(false));
test_lift_from_flat_layout(hlist![1], SimpleWrapper(true), &[]);
test_lift_from_flat_layout(hlist![0], SimpleWrapper(false), &[]);
}
/// Checks that a type with multiple fields ordered in a way that doesn't require any padding is
/// properly loaded from memory and lifted from its flat layout.
#[test]
fn test_tuple_struct_without_padding() {
let expected = TupleWithoutPadding(0x0807_0605_0403_0201_u64, 0x0c0b_0a09_i32, 0x0e0d_i16);
test_load_from_memory(
&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
expected,
);
test_lift_from_flat_layout(
hlist![0x0807_0605_0403_0201_i64, 0x0c0b_0a09_i32, 0x0000_0e0d_i32],
expected,
&[],
);
}
/// Checks that a type with multiple fields ordered in a way that requires padding between two of its
/// fields is properly loaded from memory and lifted from its flat layout.
#[test]
fn test_tuple_struct_with_padding() {
let expected = TupleWithPadding(0x0201_u16, 0x0807_0605_u32, 0x100f_0e0d_0c0b_0a09_i64);
test_load_from_memory(
&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
expected,
);
test_lift_from_flat_layout(
hlist![0x0000_0201_i32, 0x0807_0605_i32, 0x100f_0e0d_0c0b_0a09_i64],
expected,
&[],
);
}
/// Checks that a type with multiple named fields ordered in a way that requires padding before two
/// fields is properly loaded from memory and lifted from its flat layout.
#[test]
fn test_named_struct_with_double_padding() {
let expected = RecordWithDoublePadding {
first: 0x0201_u16,
second: 0x0807_0605_u32,
third: 0x09_i8,
fourth: 0x1817_1615_1413_1211_i64,
};
test_load_from_memory(
&[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
],
expected,
);
test_lift_from_flat_layout(
hlist![
0x0000_0201_i32,
0x0807_0605_i32,
0x0000_0009_i32,
0x1817_1615_1413_1211_i64,
],
expected,
&[],
);
}
/// Checks that a type that contains a field with a type that also has `WitStore` derived for it is
/// properly loaded from memory and lifted from its flat layout.
#[test]
fn test_nested_types() {
let expected = Branch {
tag: 0x0201_u16,
first_leaf: Leaf {
first: true,
second: 0x201f_1e1d_1c1b_1a19_1817_1615_1413_1211_u128,
},
second_leaf: Leaf {
first: true,
second: 0x3837_3635_3433_3231_302f_2e2d_2c2b_2a29_u128,
},
};
test_load_from_memory(
&[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
],
expected,
);
test_lift_from_flat_layout(
hlist![
0x0000_0201_i32,
0x0000_0009_i32,
0x1817_1615_1413_1211_i64,
0x201f_1e1d_1c1b_1a19_i64,
0x0000_0021_i32,
0x302f_2e2d_2c2b_2a29_i64,
0x3837_3635_3433_3231_i64,
],
expected,
&[],
);
}
/// Checks that an enum type's variants are properly loaded from memory and lifted from its flat
/// layout.
#[test]
fn test_enum_type() {
let expected = Enum::Empty;
test_load_from_memory(
&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
expected,
);
test_lift_from_flat_layout(
hlist![0_i32, 0_i64, 0_i32, 0_i32, 0_i32, 0_i32, 0_i32, 0_i32, 0_i32, 0_i32, 0_i32],
expected,
&[],
);
let expected = Enum::LargeVariantWithLooseAlignment(7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
test_load_from_memory(
&[1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
expected,
);
test_lift_from_flat_layout(
hlist![1_i32, 7_i64, 8_i32, 9_i32, 10_i32, 11_i32, 12_i32, 13_i32, 14_i32, 15_i32, 16_i32],
expected,
&[],
);
let expected = Enum::SmallerVariantWithStrictAlignment {
inner: 0x0e0d_0c0b_0a09_0807_u64,
};
test_load_from_memory(
&[2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
expected,
);
test_lift_from_flat_layout(
hlist![
2_i32,
0x0e0d_0c0b_0a09_0807_i64,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32
],
expected,
&[],
);
}
/// Checks that a generic type with a specialization request is properly loaded from memory and
/// lifted from its flat layout.
#[test]
fn test_specialized_generic_struct() {
let expected = SpecializedGenericStruct {
first: 254_u8,
second: -10_i16,
both: vec![(1, -1), (2, -2)],
};
test_load_from_memory(
&[
254, 0, 246, 255, 12, 0, 0, 0, 2, 0, 0, 0, 1, 0, 255, 255, 2, 0, 254, 255,
],
expected.clone(),
);
test_lift_from_flat_layout(
hlist![0x0000_00fe_i32, -10_i32, 0_i32, 2_i32,],
expected,
&[1, 0, 255, 255, 2, 0, 254, 255],
);
}
/// Checks that a generic enum with a specialization request type's variants are properly loaded
/// from memory and lifted from its flat layout.
#[test]
fn test_specialized_generic_enum_type() {
let expected = SpecializedGenericEnum::None;
test_load_from_memory(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], expected);
test_lift_from_flat_layout(hlist![0_i32, 0_i32, 0_i32], expected, &[]);
let expected = SpecializedGenericEnum::First(None);
test_load_from_memory(&[1, 2, 3, 4, 0, 5, 6, 7, 8, 9, 10, 11], expected);
test_lift_from_flat_layout(hlist![1_i32, 0_i32, 0_i32], expected, &[]);
let expected = SpecializedGenericEnum::First(Some(false));
test_load_from_memory(&[1, 2, 3, 4, 1, 0, 6, 7, 8, 9, 10, 11], expected);
test_lift_from_flat_layout(hlist![1_i32, 1_i32, 0_i32], expected, &[]);
let expected = SpecializedGenericEnum::First(Some(true));
test_load_from_memory(&[1, 2, 3, 4, 1, 1, 6, 7, 8, 9, 10, 11], expected);
test_lift_from_flat_layout(hlist![1_i32, 1_i32, 1_i32], expected, &[]);
let expected = SpecializedGenericEnum::MaybeSecond { maybe: None };
test_load_from_memory(&[2, 3, 4, 5, 0, 6, 7, 8, 9, 10, 11, 12], expected);
test_lift_from_flat_layout(hlist![2_i32, 0_i32, 0_i32], expected, &[]);
let expected = SpecializedGenericEnum::MaybeSecond {
maybe: Some(0x0c0b_0a09),
};
test_load_from_memory(&[2, 3, 4, 5, 1, 6, 7, 8, 9, 10, 11, 12], expected);
test_lift_from_flat_layout(hlist![2_i32, 1_i32, 0x0c0b_0a09_i32], expected, &[]);
}
/// Checks that an invalid discriminant reports a useful error.
#[test]
fn test_invalid_discriminant() {
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let invalid_discriminant = 119_i8;
let memory_bytes = [
invalid_discriminant as u8,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
];
let address = memory.allocate(memory_bytes.len() as u32, 1).unwrap();
memory.write(address, &memory_bytes).unwrap();
assert_matches!(
&Enum::load(&memory, address),
Err(RuntimeError::InvalidVariant {
type_name: "wit_load::types::Enum",
discriminant,
}) if *discriminant == invalid_discriminant as i64
);
let flat_layout = hlist![
invalid_discriminant as i32,
0_i64,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32
];
assert_matches!(
&Enum::lift_from(flat_layout, &memory),
Err(RuntimeError::InvalidVariant {
type_name: "wit_load::types::Enum",
discriminant,
}) if *discriminant == invalid_discriminant as i64
);
}
/// Checks that a type with fields stored in the heap is properly loaded from memory and lifted from
/// its flat layout.
#[test]
fn test_heap_allocated_fields() {
let expected = StructWithHeapFields {
boxed: Box::new(SimpleWrapper(true)),
rced: Rc::new(Leaf {
first: false,
second: 0x201f_1e1d_1c1b_1a19_1817_1615_1413_1211_u128,
}),
arced: Arc::new(Enum::SmallerVariantWithStrictAlignment {
inner: 0x2f2e_2d2c_2b2a_2928,
}),
};
test_load_from_memory(
&[
1, 2, 3, 4, 5, 6, 7, 8, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 2, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48,
],
expected.clone(),
);
test_lift_from_flat_layout(
hlist![
1_i32,
0_i32,
0x1817_1615_1413_1211_i64,
0x201f_1e1d_1c1b_1a19_i64,
2_i32,
0x2f2e_2d2c_2b2a_2928_i64,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
0_i32,
],
expected,
&[],
);
}
/// Checks that a [`Vec`] type is properly loaded from memory and lifted from its flat
/// layout.
#[test]
fn test_vec() {
let expected = vec![SimpleWrapper(false), SimpleWrapper(true)];
test_load_from_memory(&[8, 0, 0, 0, 2, 0, 0, 0, 0, 1], expected.clone());
test_lift_from_flat_layout(hlist![0_i32, 2_i32], expected, &[0, 1]);
}
/// Checks that a boxed slice type is properly loaded from memory and lifted from its flat
/// layout.
#[test]
fn test_boxed_slice() {
let expected: Box<[Enum]> = Box::new([
Enum::Empty,
Enum::SmallerVariantWithStrictAlignment {
inner: 0x2726_2524_2322_2120,
},
]);
let memory = iter::empty()
.chain([8, 0, 0, 0, 2, 0, 0, 0])
.chain(iter::empty().chain([0]).chain(1..8).chain(8..24))
.chain(
iter::empty()
.chain([2])
.chain(25..32)
.chain([0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27])
.chain(40..48),
)
.collect::<Vec<u8>>();
test_load_from_memory(&memory, expected.clone());
test_lift_from_flat_layout(hlist![0_i32, 2_i32], expected, &memory[8..]);
}
/// Checks that an rc-ed slice type is properly loaded from memory and lifted from its flat
/// layout.
#[test]
fn test_rced_slice() {
let expected: Rc<[Leaf]> = Rc::new([
Leaf {
first: false,
second: 0x1716_1514_1312_1110_0f0e_0d0c_0b0a_0908,
},
Leaf {
first: true,
second: 0x2f2e_2d2c_2b2a_2928_2726_2524_2322_2120,
},
Leaf {
first: false,
second: 0x4746_4544_4342_4140_3f3e_3d3c_3b3a_3938,
},
]);
let memory = iter::empty()
.chain([8, 0, 0, 0, 3, 0, 0, 0])
.chain(iter::empty().chain([0]).chain(1..8).chain([
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17,
]))
.chain(iter::empty().chain([1]).chain(25..32).chain([
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
0x2e, 0x2f,
]))
.chain(iter::empty().chain([0]).chain(49..56).chain([
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
0x46, 0x47,
]))
.collect::<Vec<u8>>();
test_load_from_memory(&memory, expected.clone());
test_lift_from_flat_layout(hlist![0_i32, 3_i32], expected, &memory[8..]);
}
/// Checks that an arc-ed slice type is properly loaded from memory and lifted from its flat
/// layout.
#[test]
fn test_arced_slice() {
let expected: Arc<[RecordWithDoublePadding]> = Arc::new([
RecordWithDoublePadding {
first: 0x0908,
second: 0x0f0e_0d0c,
third: 0x10,
fourth: 0x1f1e_1d1c_1b1a_1918,
},
RecordWithDoublePadding {
first: 0x2120,
second: 0x2726_2524,
third: 0x28,
fourth: 0x3736_3534_3332_3130,
},
]);
let memory = iter::empty()
.chain([8, 0, 0, 0, 2, 0, 0, 0])
.chain(
iter::empty()
.chain([0x08, 0x09])
.chain(10..12)
.chain([0x0c, 0x0d, 0x0e, 0x0f])
.chain([0x10])
.chain(17..24)
.chain([0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]),
)
.chain(
iter::empty()
.chain([0x20, 0x21])
.chain(34..36)
.chain([0x24, 0x25, 0x26, 0x27])
.chain([0x28])
.chain(41..48)
.chain([0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37]),
)
.collect::<Vec<u8>>();
test_load_from_memory(&memory, expected.clone());
test_lift_from_flat_layout(hlist![0_i32, 2_i32], expected, &memory[8..]);
}
/// Checks that a type with list fields is properly loaded from memory and lifted from its
/// flat layout.
#[test]
fn test_list_fields() {
let expected = StructWithLists {
vec: vec![
SimpleWrapper(true),
SimpleWrapper(true),
SimpleWrapper(false),
],
boxed_slice: Box::new([
TupleWithPadding(0x2928, 0x2f2e_2d2c, 0x3736_3534_3332_3130),
TupleWithPadding(0x3938, 0x3f3e_3d3c, 0x4746_4544_4342_4140),
]),
rced_slice: Rc::new([
Leaf {
first: true,
second: 0x5f5e_5d5c_5b5a_5958_5756_5554_5352_5150,
},
Leaf {
first: true,
second: 0x7776_7574_7372_7170_6f6e_6d6c_6b6a_6968,
},
Leaf {
first: false,
second: 0x8f8e_8d8c_8b8a_8988_8786_8584_8382_8180,
},
Leaf {
first: false,
second: 0xa7a6_a5a4_a3a2_a1a0_9f9e_9d9c_9b9a_9998,
},
]),
arced_slice: Arc::new([
RecordWithDoublePadding {
first: 0xa9a8,
second: 0xafae_adac,
third: 0xb0_u8 as i8,
fourth: 0xbfbe_bdbc_bbba_b9b8_u64 as i64,
},
RecordWithDoublePadding {
first: 0xc1c0,
second: 0xc7c6_c5c4,
third: 0xc8_u8 as i8,
fourth: 0xd7d6_d5d4_d3d2_d1d0_u64 as i64,
},
]),
};
let vec_metadata = [32, 0, 0, 0, 3, 0, 0, 0];
let vec_contents = [1, 1, 0];
let boxed_metadata = [40, 0, 0, 0, 2, 0, 0, 0];
let boxed_contents = iter::empty()
.chain(
iter::empty()
.chain([0x28, 0x29])
.chain(42..44)
.chain([0x2c, 0x2d, 0x2e, 0x2f])
.chain([0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37]),
)
.chain(
iter::empty()
.chain([0x38, 0x39])
.chain(58..60)
.chain([0x3c, 0x3d, 0x3e, 0x3f])
.chain([0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47]),
);
let rced_metadata = [72, 0, 0, 0, 4, 0, 0, 0];
let rced_contents = iter::empty()
.chain(iter::empty().chain([1]).chain(73..80).chain([
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d,
0x5e, 0x5f,
]))
.chain(iter::empty().chain([1]).chain(97..104).chain([
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
0x76, 0x77,
]))
.chain(iter::empty().chain([0]).chain(121..128).chain([
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
0x8e, 0x8f,
]))
.chain(iter::empty().chain([0]).chain(145..152).chain([
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7,
]));
let arced_metadata = [168, 0, 0, 0, 2, 0, 0, 0];
let arced_contents = iter::empty()
.chain(
iter::empty()
.chain([0xa8, 0xa9])
.chain(170..172)
.chain([0xac, 0xad, 0xae, 0xaf])
.chain([0xb0])
.chain(177..184)
.chain([0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf]),
)
.chain(
iter::empty()
.chain([0xc0, 0xc1])
.chain(194..196)
.chain([0xc4, 0xc5, 0xc6, 0xc7])
.chain([0xc8])
.chain(201..208)
.chain([0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7]),
);
let memory = iter::empty()
.chain(vec_metadata)
.chain(boxed_metadata)
.chain(rced_metadata)
.chain(arced_metadata)
.chain(vec_contents)
.chain(35..40)
.chain(boxed_contents)
.chain(rced_contents)
.chain(arced_contents)
.collect::<Vec<u8>>();
test_load_from_memory(&memory, expected.clone());
test_lift_from_flat_layout(
hlist![0_i32, 3_i32, 8_i32, 2_i32, 40_i32, 4_i32, 136_i32, 2_i32],
expected,
&memory[32..],
);
}
/// Tests that the type `T` and wrapped versions of it can be loaded from an `input` sequence of
/// bytes in memory and that it matches the `expected` value.
fn test_load_from_memory<T>(input: &[u8], expected: T)
where
T: Clone + Debug + Eq + WitLoad,
{
test_single_load_from_memory(input, &expected);
test_single_load_from_memory(input, &Box::new(expected.clone()));
test_single_load_from_memory(input, &Rc::new(expected.clone()));
test_single_load_from_memory(input, &Arc::new(expected));
}
/// Tests that the type `T` can be loaded from an `input` sequence of bytes in memory and that it
/// matches the `expected` value.
fn test_single_load_from_memory<T>(input: &[u8], expected: &T)
where
T: Debug + Eq + WitLoad,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let address = memory.allocate(input.len() as u32, 1).unwrap();
memory.write(address, input).unwrap();
assert_eq!(&T::load(&memory, address).unwrap(), expected);
}
/// Tests that the type `T` and wrapped versions of it can be lifted from an `input` flat layout and
/// that they match the `expected` value.
fn test_lift_from_flat_layout<T>(
input: <T::Layout as Layout>::Flat,
expected: T,
initial_memory: &[u8],
) where
T: Clone + Debug + Eq + WitLoad,
<T::Layout as Layout>::Flat: Copy,
{
test_single_lift_from_flat_layout(input, &expected, initial_memory);
test_single_lift_from_flat_layout(input, &Box::new(expected.clone()), initial_memory);
test_single_lift_from_flat_layout(input, &Rc::new(expected.clone()), initial_memory);
test_single_lift_from_flat_layout(input, &Arc::new(expected), initial_memory);
}
/// Tests that the type `T` can be lifted from an `input` flat layout and that they match the
/// `expected` value.
fn test_single_lift_from_flat_layout<T>(
input: <T::Layout as Layout>::Flat,
expected: &T,
initial_memory: &[u8],
) where
T: Debug + Eq + WitLoad,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let start_address = memory.allocate(initial_memory.len() as u32, 1).unwrap();
memory.write(start_address, initial_memory).unwrap();
assert_eq!(&T::lift_from(input, &memory).unwrap(), expected);
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/wit_store.rs | linera-witty/tests/wit_store.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `WitStore` derive macro.
#[path = "common/types.rs"]
mod types;
use std::{fmt::Debug, iter, rc::Rc, sync::Arc};
use linera_witty::{hlist, InstanceWithMemory, Layout, MockInstance, WitStore};
use self::types::{
Branch, Enum, Leaf, RecordWithDoublePadding, SimpleWrapper, SliceWrapper,
SpecializedGenericEnum, SpecializedGenericStruct, StructWithHeapFields, StructWithLists,
TupleWithPadding, TupleWithoutPadding,
};
/// Checks that a wrapper type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_simple_bool_wrapper() {
test_store_in_memory(SimpleWrapper(true), &[1], &[]);
test_store_in_memory(SimpleWrapper(false), &[0], &[]);
test_lower_to_flat_layout(SimpleWrapper(true), hlist![1], &[]);
test_lower_to_flat_layout(SimpleWrapper(false), hlist![0], &[]);
}
/// Checks that a type with multiple fields ordered in a way that doesn't require any padding is
/// properly stored in memory and lowered into its flat layout.
#[test]
fn test_tuple_struct_without_padding() {
let data = TupleWithoutPadding(0x0123_4567_89ab_cdef_u64, 0x0011_2233_i32, 0x4455_i16);
test_store_in_memory(
data,
&[
0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, 0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0,
0,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0123_4567_89ab_cdef_i64, 0x0011_2233_i32, 0x0000_4455_i32],
&[],
);
}
/// Checks that a type with multiple fields ordered in a way that requires padding between two of its
/// fields is properly stored in memory and lowered into its flat layout.
#[test]
fn test_tuple_struct_with_padding() {
let data = TupleWithPadding(0x0123_u16, 0x4567_89ab_u32, 0x0011_2233_4455_6677_i64);
test_store_in_memory(
data,
&[
0x23, 0x01, 0, 0, 0xab, 0x89, 0x67, 0x45, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11,
0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0123_i32, 0x4567_89ab_i32, 0x0011_2233_4455_6677_i64],
&[],
);
}
/// Checks that a type with multiple named fields ordered in a way that requires padding before two
/// fields is properly stored in memory and lowered into its flat layout.
#[test]
fn test_named_struct_with_double_padding() {
let data = RecordWithDoublePadding {
first: 0x0123_u16,
second: 0x0011_2233_u32,
third: 0x45_i8,
fourth: 0x6789_abcd_ef44_5566_i64,
};
test_store_in_memory(
data,
&[
0x23, 0x01, 0, 0, 0x33, 0x22, 0x11, 0x00, 0x45, 0, 0, 0, 0, 0, 0, 0, 0x66, 0x55, 0x44,
0xef, 0xcd, 0xab, 0x89, 0x67,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0x0000_0123_i32,
0x0011_2233_i32,
0x0000_0045_i32,
0x6789_abcd_ef44_5566_i64,
],
&[],
);
}
/// Checks that a type that contains a field with a type that also has `WitStore` derived for it is
/// properly stored in memory and lowered into its flat layout.
#[test]
fn test_nested_types() {
let data = Branch {
tag: 0x0123_u16,
first_leaf: Leaf {
first: false,
second: 0x4567_89ab_cdef_0011_2233_4455_6677_8899_u128,
},
second_leaf: Leaf {
first: true,
second: 0xaabb_ccdd_eeff_0f1e_2d3c_4b5a_6978_8796_u128,
},
};
test_store_in_memory(
data,
&[
0x23, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0, 0, 0, 0, 0, 0, 0, 0x99, 0x88, 0x77, 0x66, 0x55,
0x44, 0x33, 0x22, 0x11, 0x00, 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x01, 0, 0, 0, 0, 0,
0, 0, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, 0xff, 0xee, 0xdd,
0xcc, 0xbb, 0xaa,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0x0000_0123_i32,
0x0000_0000_i32,
0x2233_4455_6677_8899_i64,
0x4567_89ab_cdef_0011_i64,
0x0000_0001_i32,
0x2d3c_4b5a_6978_8796_i64,
0xaabb_ccdd_eeff_0f1e_u64 as i64,
],
&[],
);
}
/// Checks that an enum type's variants are properly stored in memory and lowered into its flat
/// layout.
#[test]
fn test_enum_type() {
let data = Enum::Empty;
test_store_in_memory(
data,
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0x0000_0000_i32,
0x0000_0000_0000_0000_i64,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
],
&[],
);
let data = Enum::LargeVariantWithLooseAlignment(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
test_store_in_memory(
data,
&[
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0, 0, 0, 0, 0, 0,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0x0000_0001_i32,
0x0000_0000_0000_0000_i64,
0x0000_0001_i32,
0x0000_0002_i32,
0x0000_0003_i32,
0x0000_0004_i32,
0x0000_0005_i32,
0x0000_0006_i32,
0x0000_0007_i32,
0x0000_0008_i32,
0x0000_0009_i32,
],
&[],
);
let data = Enum::SmallerVariantWithStrictAlignment {
inner: 0x0102_0304_0506_0708_u64,
};
test_store_in_memory(
data,
&[
0x02, 0, 0, 0, 0, 0, 0, 0, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0, 0, 0, 0,
0, 0, 0, 0,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0x0000_0002_i32,
0x0102_0304_0506_0708_i64,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
0x0000_0000_i32,
],
&[],
);
}
/// Checks that a generic type with a specialization request is properly stored in memory and
/// lowered into its flat layout.
#[test]
fn test_specialized_generic_struct() {
let data = SpecializedGenericStruct {
first: 200_u8,
second: -200_i16,
both: vec![(4, -4), (3, -3), (2, -2), (1, -1)],
};
let expected_heap = [
0x04, 0, 0xfc, 0xff, 0x03, 0, 0xfd, 0xff, 0x02, 0, 0xfe, 0xff, 0x01, 0, 0xff, 0xff,
];
test_store_in_memory(
data.clone(),
&[
0xc8, 0, 0x38, 0xff, 0x0c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
],
&expected_heap,
);
test_lower_to_flat_layout(
data,
hlist![0x0000_00c8_i32, -200_i32, 0x0000_0000_i32, 0x0000_0004_i32],
&expected_heap,
);
}
/// Checks that a generic enum with a specialization request type's variants are properly stored in
/// memory and lowered into its flat layout.
#[test]
fn test_specialized_generic_enum_type() {
let data = SpecializedGenericEnum::None;
test_store_in_memory(
data,
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0000_i32, 0x0000_0000_i32, 0x0000_0000_i32],
&[],
);
let data = SpecializedGenericEnum::First(None);
test_store_in_memory(
data,
&[
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0001_i32, 0x0000_0000_i32, 0x0000_0000_i32],
&[],
);
let data = SpecializedGenericEnum::First(Some(false));
test_store_in_memory(
data,
&[
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0001_i32, 0x0000_0001_i32, 0x0000_0000_i32],
&[],
);
let data = SpecializedGenericEnum::First(Some(true));
test_store_in_memory(
data,
&[
0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0001_i32, 0x0000_0001_i32, 0x0000_0001_i32],
&[],
);
let data = SpecializedGenericEnum::MaybeSecond { maybe: None };
test_store_in_memory(
data,
&[
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0002_i32, 0x0000_0000_i32, 0x0000_0000_i32],
&[],
);
let data = SpecializedGenericEnum::MaybeSecond { maybe: Some(9) };
test_store_in_memory(
data,
&[
0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![0x0000_0002_i32, 0x0000_0001_i32, 0x0000_0009_i32],
&[],
);
}
/// Checks that a type with fields stored in the heap is properly stored in memory and lowered into
/// its flat layout.
#[test]
fn test_heap_allocated_fields() {
let data = StructWithHeapFields {
boxed: Box::new(SimpleWrapper(false)),
rced: Rc::new(Leaf {
first: true,
second: 0x7071_7273_7475_7677_7879_7a7b_7c7d_7e7f_u128,
}),
arced: Arc::new(Enum::SmallerVariantWithStrictAlignment {
inner: 0x4041_4243_4445_4647_u64,
}),
};
test_store_in_memory(
data.clone(),
&[
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a,
0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 2, 0, 0, 0, 0, 0, 0, 0,
0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0, 0, 0, 0, 0, 0, 0, 0,
],
&[],
);
test_lower_to_flat_layout(
data,
hlist![
0_i32,
1_i32,
0x7879_7a7b_7c7d_7e7f_i64,
0x7071_7273_7475_7677_i64,
2_i32,
0x4041_4243_4445_4647_i64,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
&[],
);
}
/// Check that a slice type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_slice() {
let data = [
SimpleWrapper(false),
SimpleWrapper(false),
SimpleWrapper(true),
SimpleWrapper(true),
];
test_store_in_memory(data.as_slice(), &[8, 0, 0, 0, 4, 0, 0, 0], &[0, 0, 1, 1]);
test_lower_to_flat_layout(data.as_slice(), hlist![0_i32, 4_i32,], &[0, 0, 1, 1]);
}
/// Checks that a [`Vec`] type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_vec() {
let data = vec![
SimpleWrapper(true),
SimpleWrapper(false),
SimpleWrapper(true),
];
test_store_in_memory(data.clone(), &[8, 0, 0, 0, 3, 0, 0, 0], &[1, 0, 1]);
test_lower_to_flat_layout(data, hlist![0_i32, 3_i32,], &[1, 0, 1]);
}
/// Check that a boxed slice type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_boxed_slice() {
let data: Box<[Enum]> = Box::new([
Enum::LargeVariantWithLooseAlignment(10, 20, 30, 40, 50, 60, 70, 80, 90, 100),
Enum::Empty,
Enum::Empty,
Enum::SmallerVariantWithStrictAlignment { inner: 0xFFFF_FFFF },
]);
let heap_memory = iter::empty()
.chain(
iter::empty()
.chain([1])
.chain([0; 7])
.chain([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
.chain([0; 6]),
)
.chain(iter::empty().chain([0]).chain([0; 23]))
.chain(iter::empty().chain([0]).chain([0; 23]))
.chain(
iter::empty()
.chain([2])
.chain([0; 7])
.chain([0xff, 0xff, 0xff, 0xff])
.chain([0; 12]),
)
.collect::<Vec<u8>>();
test_store_in_memory(data.clone(), &[8, 0, 0, 0, 4, 0, 0, 0], &heap_memory);
test_lower_to_flat_layout(data, hlist![0_i32, 4_i32,], &heap_memory);
}
/// Check that a rc-ed slice type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_rced_slice() {
let data: Rc<[Leaf]> = Rc::new([
Leaf {
first: true,
second: 0x0011_2233_4455_6677_8899_aabb_ccdd_eeff,
},
Leaf {
first: false,
second: 0xffee_ddcc_bbaa_9988_7766_5544_3322_1100,
},
]);
let heap_memory = iter::empty()
.chain(iter::empty().chain([1]).chain([0; 7]).chain([
0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22,
0x11, 0x00,
]))
.chain(iter::empty().chain([0]).chain([0; 7]).chain([
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
0xee, 0xff,
]))
.collect::<Vec<u8>>();
test_store_in_memory(data.clone(), &[8, 0, 0, 0, 2, 0, 0, 0], &heap_memory);
test_lower_to_flat_layout(data, hlist![0_i32, 2_i32,], &heap_memory);
}
/// Check that a rc-ed slice type is properly stored in memory and lowered into its flat layout.
#[test]
fn test_arced_slice() {
let data: Arc<[RecordWithDoublePadding]> = Arc::new([
RecordWithDoublePadding {
first: 0x0300,
second: 0x4422_1100,
third: -2,
fourth: -3,
},
RecordWithDoublePadding {
first: 32_767,
second: 9,
third: 127,
fourth: -32_768,
},
]);
let heap_memory = iter::empty()
.chain(
iter::empty()
.chain([0x00, 0x03])
.chain([0; 2])
.chain([0x00, 0x11, 0x22, 0x44])
.chain([0xfe])
.chain([0; 7])
.chain([0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
)
.chain(
iter::empty()
.chain([0xff, 0x7f])
.chain([0; 2])
.chain([9, 0, 0, 0])
.chain([0x7f])
.chain([0; 7])
.chain([0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
)
.collect::<Vec<u8>>();
test_store_in_memory(data.clone(), &[8, 0, 0, 0, 2, 0, 0, 0], &heap_memory);
test_lower_to_flat_layout(data, hlist![0_i32, 2_i32,], &heap_memory);
}
/// Check that a type with a slice field is properly stored in memory and lowered into its
/// flat layout.
#[test]
fn test_slice_field() {
let slice = [
TupleWithoutPadding(0, 1, 2),
TupleWithoutPadding(3, 4, 5),
TupleWithoutPadding(6, 7, 8),
];
let data = SliceWrapper(&slice);
let expected_memory = iter::empty()
.chain(
iter::empty()
.chain([0, 0, 0, 0, 0, 0, 0, 0])
.chain([1, 0, 0, 0])
.chain([2, 0])
.chain([0; 2]),
)
.chain(
iter::empty()
.chain([3, 0, 0, 0, 0, 0, 0, 0])
.chain([4, 0, 0, 0])
.chain([5, 0])
.chain([0; 2]),
)
.chain(
iter::empty()
.chain([6, 0, 0, 0, 0, 0, 0, 0])
.chain([7, 0, 0, 0])
.chain([8, 0])
.chain([0; 2]),
)
.collect::<Vec<u8>>();
test_store_in_memory(data, &[8, 0, 0, 0, 3, 0, 0, 0], &expected_memory);
test_lower_to_flat_layout(data, hlist![0_i32, 3_i32], &expected_memory);
}
/// Checks that a type with list fields is properly stored in memory and lowered into its
/// flat layout.
#[test]
fn test_list_fields() {
let data = StructWithLists {
vec: vec![
SimpleWrapper(false),
SimpleWrapper(true),
SimpleWrapper(false),
SimpleWrapper(true),
],
boxed_slice: Box::new([TupleWithPadding(1, 0, -1), TupleWithPadding(10, 11, 12)]),
rced_slice: Rc::new([
Leaf {
first: true,
second: 0x0011_2233_4455_6677_8899_aabb_ccdd_eeff,
},
Leaf {
first: false,
second: 0xffee_ddcc_bbaa_9988_7766_5544_3322_1100,
},
Leaf {
first: false,
second: 0xf0e1_d2c3_b4a5_9687_7869_5a4b_3c2d_1e0f,
},
]),
arced_slice: Arc::new([
RecordWithDoublePadding {
first: 0x1020,
second: 0x0a0b_0c0d,
third: 0x7a,
fourth: -0x0abb_ccdd_eeff_0011,
},
RecordWithDoublePadding {
first: 0x1525,
second: 0x8191_a1b1,
third: -0x7a,
fourth: 0x0abb_ccdd_eeff_0011,
},
]),
};
let vec_contents = [0, 1, 0, 1];
let boxed_contents = iter::empty()
.chain(
iter::empty()
.chain([1, 0])
.chain([0; 2])
.chain([0, 0, 0, 0])
.chain([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
)
.chain(
iter::empty()
.chain([10, 0])
.chain([0; 2])
.chain([11, 0, 0, 0])
.chain([12, 0, 0, 0, 0, 0, 0, 0]),
);
let rced_contents = iter::empty()
.chain(iter::empty().chain([1]).chain([0; 7]).chain([
0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22,
0x11, 0x00,
]))
.chain(iter::empty().chain([0]).chain([0; 7]).chain([
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
0xee, 0xff,
]))
.chain(iter::empty().chain([0]).chain([0; 7]).chain([
0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78, 0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2,
0xe1, 0xf0,
]));
let arced_contents = iter::empty()
.chain(
iter::empty()
.chain([0x20, 0x10])
.chain([0; 2])
.chain([0x0d, 0x0c, 0x0b, 0x0a])
.chain([0x7a])
.chain([0; 7])
.chain([0xef, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0xf5]),
)
.chain(
iter::empty()
.chain([0x25, 0x15])
.chain([0; 2])
.chain([0xb1, 0xa1, 0x91, 0x81])
.chain([0x86])
.chain([0; 7])
.chain([0x11, 0x00, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0x0a]),
);
let expected_heap = iter::empty()
.chain(vec_contents)
.chain([0; 4])
.chain(boxed_contents)
.chain(rced_contents)
.chain(arced_contents)
.collect::<Vec<_>>();
test_store_in_memory(
data.clone(),
&[
32, 0, 0, 0, 4, 0, 0, 0, 40, 0, 0, 0, 2, 0, 0, 0, 72, 0, 0, 0, 3, 0, 0, 0, 144, 0, 0,
0, 2, 0, 0, 0,
],
&expected_heap,
);
test_lower_to_flat_layout(
data,
hlist![0_i32, 4_i32, 8_i32, 2_i32, 40_i32, 3_i32, 112_i32, 2_i32],
&expected_heap,
);
}
/// Tests that the `data` of type `T` and wrapped versions of it can be stored as a sequence of
/// bytes in memory and that they match the `expected` bytes.
fn test_store_in_memory<T>(
data: T,
expected_without_allocation: &[u8],
expected_additionally_allocated: &[u8],
) where
T: Clone + WitStore,
{
test_single_store_in_memory(
&data,
expected_without_allocation,
expected_additionally_allocated,
);
test_single_store_in_memory(
&Box::new(data.clone()),
expected_without_allocation,
expected_additionally_allocated,
);
test_single_store_in_memory(
&Rc::new(data),
expected_without_allocation,
expected_additionally_allocated,
);
}
/// Tests that the `data` of type `T` can be stored as a sequence of bytes in memory and that it
/// matches the `expected` bytes.
fn test_single_store_in_memory<T>(
data: &T,
expected_without_allocation: &[u8],
expected_additionally_allocated: &[u8],
) where
T: WitStore,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
let length = expected_without_allocation.len() as u32;
let address = memory.allocate(length, 1).unwrap();
data.store(&mut memory, address).unwrap();
let additional_allocations_address = address.after::<T>();
let additional_allocations_length = expected_additionally_allocated.len() as u32;
assert_eq!(
memory.read(address, length).unwrap(),
expected_without_allocation
);
assert_eq!(
memory
.read(
additional_allocations_address,
additional_allocations_length
)
.unwrap(),
expected_additionally_allocated
);
}
/// Tests that the `data` of type `T` and wrapped versions of it can be lowered to their flat layout
/// and that they match the `expected` value.
fn test_lower_to_flat_layout<T>(
data: T,
expected: <T::Layout as Layout>::Flat,
expected_memory: &[u8],
) where
T: Clone + WitStore,
<T::Layout as Layout>::Flat: Copy + Debug + Eq,
{
test_single_lower_to_flat_layout(&data, expected, expected_memory);
test_single_lower_to_flat_layout(&Box::new(data.clone()), expected, expected_memory);
test_single_lower_to_flat_layout(&Rc::new(data.clone()), expected, expected_memory);
test_single_lower_to_flat_layout(&Arc::new(data), expected, expected_memory);
}
/// Tests that the `data` of type `T` can be lowered to its flat layout and that it matches the
/// `expected` value.
fn test_single_lower_to_flat_layout<T>(
data: &T,
expected: <T::Layout as Layout>::Flat,
expected_memory: &[u8],
) where
T: WitStore,
<T::Layout as Layout>::Flat: Debug + Eq,
{
let mut instance = MockInstance::<()>::default();
let mut memory = instance.memory().unwrap();
assert_eq!(data.lower(&mut memory).unwrap(), expected);
assert_eq!(&instance.memory_contents(), expected_memory);
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/wit_export.rs | linera-witty/tests/wit_export.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `wit_export` attribute macro.
#[path = "common/test_instance.rs"]
mod test_instance;
#[path = "common/wit_interface_test.rs"]
mod wit_interface_test;
use std::marker::PhantomData;
use insta::assert_snapshot;
use linera_witty::{
wit_export,
wit_generation::{FileContentGenerator as _, WitInterface, WitInterfaceWriter, WitWorldWriter},
wit_import, ExportTo, Instance, MockInstance, Runtime, RuntimeMemory,
};
use test_case::test_case;
#[cfg(with_wasmer)]
use self::test_instance::WasmerInstanceFactory;
#[cfg(with_wasmtime)]
use self::test_instance::WasmtimeInstanceFactory;
use self::{
test_instance::{MockInstanceFactory, TestInstanceFactory},
wit_interface_test::{ENTRYPOINT, GETTERS, OPERATIONS, SETTERS, SIMPLE_FUNCTION},
};
/// An interface to call into the test modules.
#[wit_import(package = "witty-macros:test-modules")]
pub trait Entrypoint {
fn entrypoint();
}
/// Type to export a simple function without parameters or a return value.
pub struct SimpleFunction;
#[wit_export(package = "witty-macros:test-modules")]
impl SimpleFunction {
fn simple() {
println!("In simple");
}
}
/// Test exporting a simple function without parameters or return values.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_simple_function<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
SimpleFunction: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<SimpleFunction>("import", "simple-function");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `simple` function");
}
/// Type to export functions with return values.
pub struct Getters;
#[wit_export(package = "witty-macros:test-modules")]
impl Getters {
fn get_true() -> bool {
true
}
fn get_false() -> bool {
false
}
fn get_s8() -> i8 {
-125
}
fn get_u8() -> u8 {
200
}
fn get_s16() -> i16 {
-410
}
fn get_u16() -> u16 {
60_000
}
fn get_s32() -> i32 {
-100_000
}
fn get_u32() -> u32 {
3_000_111
}
fn get_s64() -> i64 {
-5_000_000
}
fn get_u64() -> u64 {
10_000_000_000
}
fn get_float32() -> f32 {
-0.125
}
fn get_float64() -> f64 {
128.25
}
}
/// Test exporting functions with return values.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_getters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
Getters: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<Getters>("import", "getters");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to execute test of imported getters");
}
/// Type to export functions with parameters.
pub struct Setters;
#[wit_export(package = "witty-macros:test-modules")]
impl Setters {
#[expect(clippy::bool_assert_comparison)]
fn set_bool(value: bool) {
assert_eq!(value, false);
}
fn set_s8(value: i8) {
assert_eq!(value, -100);
}
fn set_u8(value: u8) {
assert_eq!(value, 201);
}
fn set_s16(value: i16) {
assert_eq!(value, -20_000);
}
fn set_u16(value: u16) {
assert_eq!(value, 50_000);
}
fn set_s32(value: i32) {
assert_eq!(value, -2_000_000);
}
fn set_u32(value: u32) {
assert_eq!(value, 4_000_000);
}
fn set_s64(value: i64) {
assert_eq!(value, -25_000_000_000);
}
fn set_u64(value: u64) {
assert_eq!(value, 7_000_000_000);
}
fn set_float32(value: f32) {
assert_eq!(value, 10.4);
}
fn set_float64(value: f64) {
assert_eq!(value, -0.000_08);
}
}
/// Test exporting functions with parameters.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_setters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
Setters: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<Setters>("import", "setters");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to execute test of imported setters");
}
/// Type to export functions with multiple parameters and return values.
pub struct Operations;
#[wit_export(package = "witty-macros:test-modules")]
impl Operations {
fn and_bool(first: bool, second: bool) -> bool {
first && second
}
fn add_s8(first: i8, second: i8) -> i8 {
first + second
}
fn add_u8(first: u8, second: u8) -> u8 {
first + second
}
fn add_s16(first: i16, second: i16) -> i16 {
first + second
}
fn add_u16(first: u16, second: u16) -> u16 {
first + second
}
fn add_s32(first: i32, second: i32) -> i32 {
first + second
}
fn add_u32(first: u32, second: u32) -> u32 {
first + second
}
fn add_s64(first: i64, second: i64) -> i64 {
first + second
}
fn add_u64(first: u64, second: u64) -> u64 {
first + second
}
fn add_float32(first: f32, second: f32) -> f32 {
first + second
}
fn add_float64(first: f64, second: f64) -> f64 {
first + second
}
}
/// Test exporting functions with multiple parameters and return values.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_operations<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
Operations: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<Operations>("import", "operations");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to execute test of imported operations");
}
/// Test the generated [`WitInterface`] implementations for the types used in this test.
#[test_case(PhantomData::<Entrypoint<MockInstance<()>>>, ENTRYPOINT; "of_entrypoint")]
#[test_case(PhantomData::<SimpleFunction>, SIMPLE_FUNCTION; "of_simple_function")]
#[test_case(PhantomData::<Getters>, GETTERS; "of_getters")]
#[test_case(PhantomData::<Setters>, SETTERS; "of_setters")]
#[test_case(PhantomData::<Operations>, OPERATIONS; "of_operations")]
fn test_wit_interface<Interface>(
_: PhantomData<Interface>,
expected_snippets: (&str, &[&str], &[(&str, &str)]),
) where
Interface: WitInterface,
{
wit_interface_test::test_wit_interface::<Interface>(expected_snippets);
}
/// Tests the generated file contents for the [`WitInterface`] implementations for the types used
/// in this test.
#[test_case(PhantomData::<Entrypoint<MockInstance<()>>>, "entrypoint"; "of_entrypoint")]
#[test_case(PhantomData::<SimpleFunction>, "simple-function"; "of_simple_function")]
#[test_case(PhantomData::<Getters>, "getters"; "of_getters")]
#[test_case(PhantomData::<Setters>, "setters"; "of_setters")]
#[test_case(PhantomData::<Operations>, "operations"; "of_operations")]
fn test_wit_interface_file<Interface>(_: PhantomData<Interface>, name: &str)
where
Interface: WitInterface,
{
let mut buffer = Vec::new();
WitInterfaceWriter::new::<Interface>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(name, String::from_utf8(buffer).unwrap());
}
/// Tests the generated file contents for a WIT world containing all the interfaces used in this
/// test.
#[test]
fn test_wit_world_file() {
let mut buffer = Vec::new();
WitWorldWriter::new("witty-macros:test-modules", "test-world")
.export::<Entrypoint<MockInstance<()>>>()
.import::<SimpleFunction>()
.import::<Getters>()
.import::<Setters>()
.import::<Operations>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(String::from_utf8(buffer).unwrap());
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/reentrancy.rs | linera-witty/tests/reentrancy.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `wit_import` and `wit_export` attribute macro using reentrant host functions.
#[path = "common/test_instance.rs"]
mod test_instance;
#[path = "common/wit_interface_test.rs"]
mod wit_interface_test;
use std::{
marker::PhantomData,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use insta::assert_snapshot;
use linera_witty::{
wit_export,
wit_generation::{FileContentGenerator as _, WitInterface, WitInterfaceWriter, WitWorldWriter},
wit_import, ExportTo, Instance, MockInstance, Runtime, RuntimeError, RuntimeMemory,
};
use test_case::test_case;
#[cfg(with_wasmer)]
use self::test_instance::WasmerInstanceFactory;
#[cfg(with_wasmtime)]
use self::test_instance::WasmtimeInstanceFactory;
use self::{
test_instance::{MockInstanceFactory, TestInstanceFactory},
wit_interface_test::{ENTRYPOINT, GETTERS, OPERATIONS, SETTERS, SIMPLE_FUNCTION},
};
/// An interface to call into the test modules.
#[wit_import(package = "witty-macros:test-modules")]
pub trait Entrypoint {
fn entrypoint();
}
/// An interface to import a single function without parameters or return values.
#[wit_import(package = "witty-macros:test-modules", interface = "simple-function")]
trait ImportedSimpleFunction {
fn simple();
}
/// Type to export a simple reentrant function without parameters or return values.
pub struct ExportedSimpleFunction;
#[wit_export(package = "witty-macros:test-modules", interface = "simple-function")]
impl ExportedSimpleFunction {
fn simple<Caller>(caller: &mut Caller) -> Result<(), RuntimeError>
where
Caller: InstanceForImportedSimpleFunction,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
tracing::debug!("Before reentrant call");
ImportedSimpleFunction::new(caller).simple()?;
tracing::debug!("After reentrant call");
Ok(())
}
}
/// Test a simple reentrant function without parameters or return values.
///
/// The host function is called from the guest, and calls the guest back through a function with
/// the same name.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_simple_function<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedSimpleFunction: ExportTo<InstanceFactory::Builder>,
{
let instance =
factory.load_test_module::<ExportedSimpleFunction>("reentrancy", "simple-function");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `entrypoint` function");
}
/// An interface to import functions with return values.
#[wit_import(package = "witty-macros:test-modules", interface = "getters")]
trait ImportedGetters {
fn get_true() -> bool;
fn get_false() -> bool;
fn get_s8() -> i8;
fn get_u8() -> u8;
fn get_s16() -> i16;
fn get_u16() -> u16;
fn get_s32() -> i32;
fn get_u32() -> u32;
fn get_s64() -> i64;
fn get_u64() -> u64;
fn get_float32() -> f32;
fn get_float64() -> f64;
}
/// Type to export reentrant functions with return values.
pub struct ExportedGetters<Caller>(PhantomData<Caller>);
#[wit_export(package = "witty-macros:test-modules", interface = "getters")]
impl<Caller> ExportedGetters<Caller>
where
Caller: InstanceForImportedGetters,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
fn get_true(caller: &mut Caller) -> Result<bool, RuntimeError> {
ImportedGetters::new(caller).get_true()
}
fn get_false(caller: &mut Caller) -> Result<bool, RuntimeError> {
ImportedGetters::new(caller).get_false()
}
fn get_s8(caller: &mut Caller) -> Result<i8, RuntimeError> {
ImportedGetters::new(caller).get_s8()
}
fn get_u8(caller: &mut Caller) -> Result<u8, RuntimeError> {
ImportedGetters::new(caller).get_u8()
}
fn get_s16(caller: &mut Caller) -> Result<i16, RuntimeError> {
ImportedGetters::new(caller).get_s16()
}
fn get_u16(caller: &mut Caller) -> Result<u16, RuntimeError> {
ImportedGetters::new(caller).get_u16()
}
fn get_s32(caller: &mut Caller) -> Result<i32, RuntimeError> {
ImportedGetters::new(caller).get_s32()
}
fn get_u32(caller: &mut Caller) -> Result<u32, RuntimeError> {
ImportedGetters::new(caller).get_u32()
}
fn get_s64(caller: &mut Caller) -> Result<i64, RuntimeError> {
ImportedGetters::new(caller).get_s64()
}
fn get_u64(caller: &mut Caller) -> Result<u64, RuntimeError> {
ImportedGetters::new(caller).get_u64()
}
fn get_float32(caller: &mut Caller) -> Result<f32, RuntimeError> {
ImportedGetters::new(caller).get_float32()
}
fn get_float64(caller: &mut Caller) -> Result<f64, RuntimeError> {
ImportedGetters::new(caller).get_float64()
}
}
/// Test reentrant functions with return values.
///
/// The host functions are called from the guest, and they return values obtained by calling back
/// the guest through functions with the same names.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_getters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedGetters<InstanceFactory::Caller<'static>>: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<ExportedGetters<_>>("reentrancy", "getters");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `entrypoint` function");
}
/// An interface to import functions with parameters.
#[wit_import(package = "witty-macros:test-modules", interface = "setters")]
trait ImportedSetters {
fn set_bool(value: bool);
fn set_s8(value: i8);
fn set_u8(value: u8);
fn set_s16(value: i16);
fn set_u16(value: u16);
fn set_s32(value: i32);
fn set_u32(value: u32);
fn set_s64(value: i64);
fn set_u64(value: u64);
fn set_float32(value: f32);
fn set_float64(value: f64);
}
/// Type to export reentrant functions with parameters.
pub struct ExportedSetters<Caller>(PhantomData<Caller>);
#[wit_export(package = "witty-macros:test-modules", interface = "setters")]
impl<Caller> ExportedSetters<Caller>
where
Caller: InstanceForImportedSetters,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
fn set_bool(caller: &mut Caller, value: bool) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_bool(value)
}
fn set_s8(caller: &mut Caller, value: i8) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_s8(value)
}
fn set_u8(caller: &mut Caller, value: u8) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_u8(value)
}
fn set_s16(caller: &mut Caller, value: i16) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_s16(value)
}
fn set_u16(caller: &mut Caller, value: u16) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_u16(value)
}
fn set_s32(caller: &mut Caller, value: i32) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_s32(value)
}
fn set_u32(caller: &mut Caller, value: u32) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_u32(value)
}
fn set_s64(caller: &mut Caller, value: i64) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_s64(value)
}
fn set_u64(caller: &mut Caller, value: u64) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_u64(value)
}
fn set_float32(caller: &mut Caller, value: f32) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_float32(value)
}
fn set_float64(caller: &mut Caller, value: f64) -> Result<(), RuntimeError> {
ImportedSetters::new(caller).set_float64(value)
}
}
/// Test reentrant functions with parameters.
///
/// The host functions are called from the guest, and they forward the arguments back to the guest
/// by calling guest functions with the same names.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_setters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedSetters<InstanceFactory::Caller<'static>>: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<ExportedSetters<_>>("reentrancy", "setters");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `entrypoint` function");
}
/// An interface to import functions with multiple parameters and return values.
#[wit_import(package = "witty-macros:test-modules", interface = "operations")]
trait ImportedOperations {
fn and_bool(first: bool, second: bool) -> bool;
fn add_s8(first: i8, second: i8) -> i8;
fn add_u8(first: u8, second: u8) -> u8;
fn add_s16(first: i16, second: i16) -> i16;
fn add_u16(first: u16, second: u16) -> u16;
fn add_s32(first: i32, second: i32) -> i32;
fn add_u32(first: u32, second: u32) -> u32;
fn add_s64(first: i64, second: i64) -> i64;
fn add_u64(first: u64, second: u64) -> u64;
fn add_float32(first: f32, second: f32) -> f32;
fn add_float64(first: f64, second: f64) -> f64;
}
/// Type to export reentrant functions with multiple parameters and return values.
pub struct ExportedOperations<Caller>(PhantomData<Caller>);
#[wit_export(package = "witty-macros:test-modules", interface = "operations")]
impl<Caller> ExportedOperations<Caller>
where
Caller: InstanceForImportedOperations,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
fn and_bool(caller: &mut Caller, first: bool, second: bool) -> Result<bool, RuntimeError> {
ImportedOperations::new(caller).and_bool(first, second)
}
fn add_s8(caller: &mut Caller, first: i8, second: i8) -> Result<i8, RuntimeError> {
ImportedOperations::new(caller).add_s8(first, second)
}
fn add_u8(caller: &mut Caller, first: u8, second: u8) -> Result<u8, RuntimeError> {
ImportedOperations::new(caller).add_u8(first, second)
}
fn add_s16(caller: &mut Caller, first: i16, second: i16) -> Result<i16, RuntimeError> {
ImportedOperations::new(caller).add_s16(first, second)
}
fn add_u16(caller: &mut Caller, first: u16, second: u16) -> Result<u16, RuntimeError> {
ImportedOperations::new(caller).add_u16(first, second)
}
fn add_s32(caller: &mut Caller, first: i32, second: i32) -> Result<i32, RuntimeError> {
ImportedOperations::new(caller).add_s32(first, second)
}
fn add_u32(caller: &mut Caller, first: u32, second: u32) -> Result<u32, RuntimeError> {
ImportedOperations::new(caller).add_u32(first, second)
}
fn add_s64(caller: &mut Caller, first: i64, second: i64) -> Result<i64, RuntimeError> {
ImportedOperations::new(caller).add_s64(first, second)
}
fn add_u64(caller: &mut Caller, first: u64, second: u64) -> Result<u64, RuntimeError> {
ImportedOperations::new(caller).add_u64(first, second)
}
fn add_float32(caller: &mut Caller, first: f32, second: f32) -> Result<f32, RuntimeError> {
ImportedOperations::new(caller).add_float32(first, second)
}
fn add_float64(caller: &mut Caller, first: f64, second: f64) -> Result<f64, RuntimeError> {
ImportedOperations::new(caller).add_float64(first, second)
}
}
/// Test reentrant functions with multiple parameters and with return values.
///
/// The host functions are called from the guest, and they call the guest back through functions
/// with the same names, forwarding the arguments and retrieving the final results.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_operations<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedOperations<InstanceFactory::Caller<'static>>: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<ExportedOperations<_>>("reentrancy", "operations");
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `entrypoint` function");
}
/// An interface to import functions to use with a reentrancy global state test.
#[wit_import(package = "witty-macros:test-modules", interface = "global-state")]
trait ImportedGlobalState {
fn entrypoint(value: u32) -> u32;
fn get_global_state() -> u32;
}
/// Type to export reentrant functions to use with a global state test.
pub struct ExportedGlobalState;
#[wit_export(package = "witty-macros:test-modules", interface = "get-host-value")]
impl ExportedGlobalState {
fn get_host_value<Caller>(caller: &mut Caller) -> Result<u32, RuntimeError>
where
Caller: InstanceForImportedGlobalState,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
ImportedGlobalState::new(caller).get_global_state()
}
}
/// Test global state inside a Wasm guest accessed through reentrant functions.
///
/// The host calls the entrypoint passing an integer argument which the guest stores in its global
/// state. Before returning, the guest calls the host's `get-host-value` function in order to
/// obtain the value to return. The host function calls the guest back to obtain the return value
/// from the guest's global state.
///
/// The final value returned from the guest must match the initial value the host sent in.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_global_state<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForImportedGlobalState,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedGlobalState: ExportTo<InstanceFactory::Builder>,
{
let instance = factory.load_test_module::<ExportedGlobalState>("reentrancy", "global-state");
let value = 100;
let result = ImportedGlobalState::new(instance)
.entrypoint(value)
.expect("Failed to call guest's `entrypoint` function");
assert_eq!(result, value);
}
/// Type to export a simple reentrant function while using custom user data
pub struct ExportedSimpleFunctionWithUserData<Caller>(PhantomData<Caller>);
#[wit_export(package = "witty-macros:test-modules", interface = "simple-function")]
impl<Caller> ExportedSimpleFunctionWithUserData<Caller>
where
Caller: Instance<UserData = Arc<AtomicBool>> + InstanceForImportedSimpleFunction,
<Caller::Runtime as Runtime>::Memory: RuntimeMemory<Caller>,
{
fn simple(caller: &mut Caller) -> Result<(), RuntimeError> {
tracing::debug!("Before reentrant call");
ImportedSimpleFunction::new(&mut *caller).simple()?;
tracing::debug!("After reentrant call");
caller.user_data().store(true, Ordering::Relaxed);
Ok(())
}
}
/// Test global state inside a Wasm guest accessed through reentrant functions.
///
/// The host calls the entrypoint passing an integer argument which the guest stores in its global
/// state. Before returning, the guest calls the host's `get-host-value` function in order to
/// obtain the value to return. The host function calls the guest back to obtain the return value
/// from the guest's global state.
///
/// The final value returned from the guest must match the initial value the host sent in.
#[test_case(MockInstanceFactory::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::default(); "with Wasmtime"))]
#[allow(clippy::bool_assert_comparison)]
fn test_user_data<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: Instance<UserData = Arc<AtomicBool>> + InstanceForEntrypoint,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
ExportedSimpleFunctionWithUserData<InstanceFactory::Caller<'static>>:
ExportTo<InstanceFactory::Builder>,
{
let instance = factory
.load_test_module::<ExportedSimpleFunctionWithUserData<_>>("reentrancy", "simple-function");
let user_data = instance.user_data().clone();
assert_eq!(user_data.load(Ordering::Relaxed), false);
Entrypoint::new(instance)
.entrypoint()
.expect("Failed to call guest's `entrypoint` function");
assert_eq!(user_data.load(Ordering::Relaxed), true);
}
/// Test the generated [`WitInterface`] implementations for the types used in this test.
#[test_case(PhantomData::<Entrypoint<MockInstance<()>>>, ENTRYPOINT; "of_entrypoint")]
#[test_case(
PhantomData::<ImportedSimpleFunction<MockInstance<()>>>, SIMPLE_FUNCTION;
"of_imported_simple_function"
)]
#[test_case(PhantomData::<ImportedGetters<MockInstance<()>>>, GETTERS; "of_imported_getters")]
#[test_case(PhantomData::<ImportedSetters<MockInstance<()>>>, SETTERS; "of_imported_setters")]
#[test_case(
PhantomData::<ImportedOperations<MockInstance<()>>>, OPERATIONS;
"of_imported_operations"
)]
#[test_case(PhantomData::<ExportedSimpleFunction>, SIMPLE_FUNCTION; "of_exported_simple_function")]
#[test_case(PhantomData::<ExportedGetters<MockInstance<()>>>, GETTERS; "of_exported_getters")]
#[test_case(PhantomData::<ExportedSetters<MockInstance<()>>>, SETTERS; "of_exported_setters")]
#[test_case(
PhantomData::<ExportedOperations<MockInstance<()>>>, OPERATIONS;
"of_exported_operations"
)]
fn test_wit_interface<Interface>(
_: PhantomData<Interface>,
expected_snippets: (&str, &[&str], &[(&str, &str)]),
) where
Interface: WitInterface,
{
wit_interface_test::test_wit_interface::<Interface>(expected_snippets);
}
#[test_case(PhantomData::<Entrypoint<MockInstance<()>>>, "entrypoint"; "of_entrypoint")]
#[test_case(
PhantomData::<ImportedSimpleFunction<MockInstance<()>>>, "simple_function";
"of_imported_simple_function"
)]
#[test_case(PhantomData::<ImportedGetters<MockInstance<()>>>, "getters"; "of_imported_getters")]
#[test_case(PhantomData::<ImportedSetters<MockInstance<()>>>, "setters"; "of_imported_setters")]
#[test_case(
PhantomData::<ImportedOperations<MockInstance<()>>>, "operations";
"of_imported_operations"
)]
#[test_case(PhantomData::<ExportedSimpleFunction>, "simple_function"; "of_exported_simple_function")]
#[test_case(PhantomData::<ExportedGetters<MockInstance<()>>>, "getters"; "of_exported_getters")]
#[test_case(PhantomData::<ExportedSetters<MockInstance<()>>>, "setters"; "of_exported_setters")]
#[test_case(
PhantomData::<ExportedOperations<MockInstance<()>>>, "operations";
"of_exported_operations"
)]
fn test_wit_interface_file<Interface>(_: PhantomData<Interface>, name: &str)
where
Interface: WitInterface,
{
let mut buffer = Vec::new();
WitInterfaceWriter::new::<Interface>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(name, String::from_utf8(buffer).unwrap());
}
/// Tests the generated file contents for a WIT world containing all the interfaces used in this
/// test.
#[test]
fn test_wit_world_file() {
let mut buffer = Vec::new();
WitWorldWriter::new("witty-macros:test-modules", "test-world")
.export::<Entrypoint<MockInstance<()>>>()
.export::<ImportedSimpleFunction<MockInstance<()>>>()
.export::<ImportedGetters<MockInstance<()>>>()
.export::<ImportedSetters<MockInstance<()>>>()
.export::<ImportedOperations<MockInstance<()>>>()
.import::<ExportedSimpleFunction>()
.import::<ExportedGetters<MockInstance<()>>>()
.import::<ExportedSetters<MockInstance<()>>>()
.import::<ExportedOperations<MockInstance<()>>>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(String::from_utf8(buffer).unwrap());
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/wit_import.rs | linera-witty/tests/wit_import.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Tests for the `wit_import` attribute macro.
#![allow(clippy::bool_assert_comparison)]
#[path = "common/test_instance.rs"]
mod test_instance;
#[path = "common/wit_interface_test.rs"]
mod wit_interface_test;
use std::marker::PhantomData;
use insta::assert_snapshot;
use linera_witty::{
wit_generation::{FileContentGenerator as _, WitInterface, WitInterfaceWriter, WitWorldWriter},
wit_import, Instance, MockInstance, Runtime, RuntimeMemory,
};
use test_case::test_case;
#[cfg(with_wasmer)]
use self::test_instance::WasmerInstanceFactory;
#[cfg(with_wasmtime)]
use self::test_instance::WasmtimeInstanceFactory;
use self::{
test_instance::{MockInstanceFactory, TestInstanceFactory, WithoutExports},
wit_interface_test::{GETTERS, OPERATIONS, SETTERS, SIMPLE_FUNCTION},
};
/// An interface to import a single function without parameters or return values.
#[wit_import(package = "witty-macros:test-modules")]
trait SimpleFunction {
fn simple();
}
/// Test importing a simple function without parameters or return values.
#[test_case(MockInstanceFactory::<()>::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_simple_function<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForSimpleFunction,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
{
let instance = factory.load_test_module::<WithoutExports>("export", "simple-function");
SimpleFunction::new(instance)
.simple()
.expect("Failed to call guest's `simple` function");
}
/// An interface to import functions with return values.
#[wit_import(package = "witty-macros:test-modules")]
trait Getters {
fn get_true() -> bool;
fn get_false() -> bool;
fn get_s8() -> i8;
fn get_u8() -> u8;
fn get_s16() -> i16;
fn get_u16() -> u16;
fn get_s32() -> i32;
fn get_u32() -> u32;
fn get_s64() -> i64;
fn get_u64() -> u64;
fn get_float32() -> f32;
fn get_float64() -> f64;
}
/// Test importing functions with return values.
#[test_case(MockInstanceFactory::<()>::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_getters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForGetters,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
{
let instance = factory.load_test_module::<WithoutExports>("export", "getters");
let mut getters = Getters::new(instance);
assert_eq!(
getters
.get_true()
.expect("Failed to run guest's `get-true` function"),
true
);
assert_eq!(
getters
.get_false()
.expect("Failed to run guest's `get-false` function"),
false
);
assert_eq!(
getters
.get_s8()
.expect("Failed to run guest's `get-s8` function"),
-125
);
assert_eq!(
getters
.get_u8()
.expect("Failed to run guest's `get-u8` function"),
200
);
assert_eq!(
getters
.get_s16()
.expect("Failed to run guest's `get-s16` function"),
-410
);
assert_eq!(
getters
.get_u16()
.expect("Failed to run guest's `get-u16` function"),
60_000
);
assert_eq!(
getters
.get_s32()
.expect("Failed to run guest's `get-s32` function"),
-100_000
);
assert_eq!(
getters
.get_u32()
.expect("Failed to run guest's `get-u32` function"),
3_000_111
);
assert_eq!(
getters
.get_s64()
.expect("Failed to run guest's `get-s64` function"),
-5_000_000
);
assert_eq!(
getters
.get_u64()
.expect("Failed to run guest's `get-u64` function"),
10_000_000_000
);
assert_eq!(
getters
.get_float32()
.expect("Failed to run guest's `get-f32` function"),
-0.125
);
assert_eq!(
getters
.get_float64()
.expect("Failed to run guest's `get-f64` function"),
128.25
);
}
/// An interface to import functions with parameters.
#[wit_import(package = "witty-macros:test-modules")]
trait Setters {
fn set_bool(value: bool);
fn set_s8(value: i8);
fn set_u8(value: u8);
fn set_s16(value: i16);
fn set_u16(value: u16);
fn set_s32(value: i32);
fn set_u32(value: u32);
fn set_s64(value: i64);
fn set_u64(value: u64);
fn set_float32(value: f32);
fn set_float64(value: f64);
}
/// Test importing functions with parameters.
#[test_case(MockInstanceFactory::<()>::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_setters<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForSetters,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
{
let instance = factory.load_test_module::<WithoutExports>("export", "setters");
let mut setters = Setters::new(instance);
setters
.set_bool(false)
.expect("Failed to run guest's `set-bool` function");
setters
.set_s8(-100)
.expect("Failed to run guest's `set-s8` function");
setters
.set_u8(201)
.expect("Failed to run guest's `set-u8` function");
setters
.set_s16(-20_000)
.expect("Failed to run guest's `set-s16` function");
setters
.set_u16(50_000)
.expect("Failed to run guest's `set-u16` function");
setters
.set_s32(-2_000_000)
.expect("Failed to run guest's `set-s32` function");
setters
.set_u32(4_000_000)
.expect("Failed to run guest's `set-u32` function");
setters
.set_s64(-25_000_000_000)
.expect("Failed to run guest's `set-s64` function");
setters
.set_u64(7_000_000_000)
.expect("Failed to run guest's `set-u64` function");
setters
.set_float32(10.4)
.expect("Failed to run guest's `set-f32` function");
setters
.set_float64(-0.000_08)
.expect("Failed to run guest's `set-f64` function");
}
/// An interface to import functions with multiple parameters and return values.
#[wit_import(package = "witty-macros:test-modules")]
trait Operations {
fn and_bool(first: bool, second: bool) -> bool;
fn add_s8(first: i8, second: i8) -> i8;
fn add_u8(first: u8, second: u8) -> u8;
fn add_s16(first: i16, second: i16) -> i16;
fn add_u16(first: u16, second: u16) -> u16;
fn add_s32(first: i32, second: i32) -> i32;
fn add_u32(first: u32, second: u32) -> u32;
fn add_s64(first: i64, second: i64) -> i64;
fn add_u64(first: u64, second: u64) -> u64;
fn add_float32(first: f32, second: f32) -> f32;
fn add_float64(first: f64, second: f64) -> f64;
}
/// Test importing functions with multiple parameters and return values.
#[test_case(MockInstanceFactory::<()>::default(); "with a mock instance")]
#[cfg_attr(with_wasmer, test_case(WasmerInstanceFactory::<()>::default(); "with Wasmer"))]
#[cfg_attr(with_wasmtime, test_case(WasmtimeInstanceFactory::<()>::default(); "with Wasmtime"))]
fn test_operations<InstanceFactory>(mut factory: InstanceFactory)
where
InstanceFactory: TestInstanceFactory,
InstanceFactory::Instance: InstanceForOperations,
<<InstanceFactory::Instance as Instance>::Runtime as Runtime>::Memory:
RuntimeMemory<InstanceFactory::Instance>,
{
let instance = factory.load_test_module::<WithoutExports>("export", "operations");
let mut operations = Operations::new(instance);
assert_eq!(
operations
.and_bool(false, true)
.expect("Failed to run guest's `and-bool` function"),
false
);
assert_eq!(
operations
.and_bool(true, true)
.expect("Failed to run guest's `and-bool` function"),
true
);
assert_eq!(
operations
.add_s8(-126, 1)
.expect("Failed to run guest's `add-s8` function"),
-125
);
assert_eq!(
operations
.add_u8(189, 11)
.expect("Failed to run guest's `add-u8` function"),
200
);
assert_eq!(
operations
.add_s16(-400, -10)
.expect("Failed to run guest's `add-s16` function"),
-410
);
assert_eq!(
operations
.add_u16(32_000, 28_000)
.expect("Failed to run guest's `add-u16` function"),
60_000
);
assert_eq!(
operations
.add_s32(-2_000_000, 1_900_000)
.expect("Failed to run guest's `add-s32` function"),
-100_000
);
assert_eq!(
operations
.add_u32(3_000_000, 111)
.expect("Failed to run guest's `add-u32` function"),
3_000_111
);
assert_eq!(
operations
.add_s64(-2_000_000_001, 5_000_000_000)
.expect("Failed to run guest's `add-s64` function"),
2_999_999_999
);
assert_eq!(
operations
.add_u64(1_000_000_000, 1_000_000_000_000)
.expect("Failed to run guest's `add-u64` function"),
1_001_000_000_000
);
assert_eq!(
operations
.add_float32(0.0, -0.125)
.expect("Failed to run guest's `add-f32` function"),
-0.125
);
assert_eq!(
operations
.add_float64(128.0, 0.25)
.expect("Failed to run guest's `add-f64` function"),
128.25
);
}
/// Tests the generated [`WitInterface`] implementations for the types used in this test.
#[test_case(PhantomData::<SimpleFunction<MockInstance<()>>>, SIMPLE_FUNCTION; "of_simple_function")]
#[test_case(PhantomData::<Getters<MockInstance<()>>>, GETTERS; "of_getters")]
#[test_case(PhantomData::<Setters<MockInstance<()>>>, SETTERS; "of_setters")]
#[test_case(PhantomData::<Operations<MockInstance<()>>>, OPERATIONS; "of_operations")]
fn test_wit_interface<Interface>(
_: PhantomData<Interface>,
expected_snippets: (&str, &[&str], &[(&str, &str)]),
) where
Interface: WitInterface,
{
wit_interface_test::test_wit_interface::<Interface>(expected_snippets);
}
/// Tests the generated file contents for the [`WitInterface`] implementations for the types used
/// in this test.
#[test_case(PhantomData::<SimpleFunction<MockInstance<()>>>, "simple-function"; "of_simple_function")]
#[test_case(PhantomData::<Getters<MockInstance<()>>>, "getters"; "of_getters")]
#[test_case(PhantomData::<Setters<MockInstance<()>>>, "setters"; "of_setters")]
#[test_case(PhantomData::<Operations<MockInstance<()>>>, "operations"; "of_operations")]
fn test_wit_interface_file<Interface>(_: PhantomData<Interface>, name: &str)
where
Interface: WitInterface,
{
let mut buffer = Vec::new();
WitInterfaceWriter::new::<Interface>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(name, String::from_utf8(buffer).unwrap());
}
/// Tests the generated file contents for a WIT world containing all the interfaces used in this
/// test.
#[test]
fn test_wit_world_file() {
let mut buffer = Vec::new();
WitWorldWriter::new("witty-macros:test-modules", "test-world")
.export::<SimpleFunction<MockInstance<()>>>()
.export::<Getters<MockInstance<()>>>()
.export::<Setters<MockInstance<()>>>()
.export::<Operations<MockInstance<()>>>()
.generate_file_contents(&mut buffer)
.unwrap();
assert_snapshot!(String::from_utf8(buffer).unwrap());
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/common/test_instance.rs | linera-witty/tests/common/test_instance.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Helper code for testing using different runtimes.
use std::{
any::Any,
fmt::Debug,
marker::PhantomData,
ops::Add,
sync::{
atomic::{AtomicU32, Ordering},
Arc,
},
};
use frunk::{hlist, hlist_pat, HList};
#[cfg(with_wasmer)]
use linera_witty::wasmer;
#[cfg(with_wasmtime)]
use linera_witty::wasmtime;
use linera_witty::{
ExportTo, InstanceWithMemory, Layout, MockExportedFunction, MockInstance, RuntimeError,
WitLoad, WitStore,
};
/// Trait representing a type that can create instances for tests.
pub trait TestInstanceFactory {
/// The type used to build a guest Wasm instance, which supports registration of exported host
/// functions.
type Builder;
/// The type representing a guest Wasm instance.
type Instance: InstanceWithMemory;
/// The type received by host functions to use for reentrant calls.
type Caller<'caller>;
/// Loads a test module with the provided `module_name` from the named `group`
fn load_test_module<ExportedFunctions>(
&mut self,
group: &str,
module_name: &str,
) -> Self::Instance
where
ExportedFunctions: ExportTo<Self::Builder>;
}
/// A factory of [`wasmtime::Entrypoint`] instances.
#[cfg(with_wasmtime)]
#[derive(Default)]
pub struct WasmtimeInstanceFactory<UserData>(PhantomData<UserData>);
#[cfg(with_wasmtime)]
impl<UserData> TestInstanceFactory for WasmtimeInstanceFactory<UserData>
where
UserData: Default + 'static,
{
type Builder = ::wasmtime::Linker<UserData>;
type Instance = wasmtime::EntrypointInstance<UserData>;
type Caller<'caller> = ::wasmtime::Caller<'caller, UserData>;
fn load_test_module<ExportedFunctions>(&mut self, group: &str, module: &str) -> Self::Instance
where
ExportedFunctions: ExportTo<Self::Builder>,
{
let engine = ::wasmtime::Engine::default();
let module = ::wasmtime::Module::from_file(
&engine,
format!("../target/wasm32-unknown-unknown/debug/{group}-{module}.wasm"),
)
.expect("Failed to load module");
let mut linker = wasmtime::Linker::new(&engine);
ExportedFunctions::export_to(&mut linker)
.expect("Failed to export functions to Wasmtime linker");
let mut store = ::wasmtime::Store::new(&engine, UserData::default());
let instance = linker
.instantiate(&mut store, &module)
.expect("Failed to instantiate module");
wasmtime::EntrypointInstance::new(instance, store)
}
}
/// A factory of [`wasmer::EntrypointInstance`]s.
#[cfg(with_wasmer)]
#[derive(Default)]
pub struct WasmerInstanceFactory<UserData>(PhantomData<UserData>);
#[cfg(with_wasmer)]
impl<UserData> TestInstanceFactory for WasmerInstanceFactory<UserData>
where
UserData: Default + Send + 'static,
{
type Builder = wasmer::InstanceBuilder<UserData>;
type Instance = wasmer::EntrypointInstance<UserData>;
type Caller<'caller> = ::wasmer::FunctionEnvMut<'caller, wasmer::Environment<UserData>>;
fn load_test_module<ExportedFunctions>(&mut self, group: &str, module: &str) -> Self::Instance
where
ExportedFunctions: ExportTo<Self::Builder>,
{
let engine = ::wasmer::sys::EngineBuilder::new(::wasmer::Singlepass::default())
.engine()
.into();
let module = ::wasmer::Module::from_file(
&engine,
format!("../target/wasm32-unknown-unknown/debug/{group}-{module}.wasm"),
)
.expect("Failed to load module");
let mut builder = wasmer::InstanceBuilder::new(engine, UserData::default());
ExportedFunctions::export_to(&mut builder)
.expect("Failed to export functions to Wasmer instance builder");
builder
.instantiate(&module)
.expect("Failed to instantiate module")
}
}
/// A factory of [`MockInstance`]s.
#[derive(Default)]
pub struct MockInstanceFactory<UserData = ()> {
deferred_assertions: Vec<Box<dyn Any>>,
user_data: PhantomData<UserData>,
}
impl<UserData> TestInstanceFactory for MockInstanceFactory<UserData>
where
UserData: Default + 'static,
{
type Builder = MockInstance<UserData>;
type Instance = MockInstance<UserData>;
type Caller<'caller> = MockInstance<UserData>;
fn load_test_module<ExportedFunctions>(&mut self, group: &str, module: &str) -> Self::Instance
where
ExportedFunctions: ExportTo<Self::Builder>,
{
let mut instance = MockInstance::default();
match (group, module) {
("export", "simple-function") => self.export_simple_function(&mut instance),
("export", "getters") => self.export_getters(&mut instance),
("export", "setters") => self.export_setters(&mut instance),
("export", "operations") => self.export_operations(&mut instance),
("import", "simple-function") => self.import_simple_function(&mut instance),
("import", "getters") => self.import_getters(&mut instance),
("import", "setters") => self.import_setters(&mut instance),
("import", "operations") => self.import_operations(&mut instance),
("reentrancy", "simple-function") => self.reentrancy_simple_function(&mut instance),
("reentrancy", "getters") => self.reentrancy_getters(&mut instance),
("reentrancy", "setters") => self.reentrancy_setters(&mut instance),
("reentrancy", "operations") => self.reentrancy_operations(&mut instance),
("reentrancy", "global-state") => self.reentrancy_global_state(&mut instance),
_ => panic!(
"Attempt to load module \"{group}-{module}\" which has no mock configuration"
),
}
ExportedFunctions::export_to(&mut instance)
.expect("Failed to export functions to mock instance");
instance
}
}
impl<UserData> MockInstanceFactory<UserData>
where
UserData: 'static,
{
/// Mock the exported functions from the "export-simple-function" module.
fn export_simple_function(&mut self, instance: &mut MockInstance<UserData>) {
self.mock_exported_function(
instance,
"witty-macros:test-modules/simple-function#simple",
|_, _: HList![]| Ok(hlist![]),
1,
);
}
/// Mock the exported functions from the "export-getters" module.
fn export_getters(&mut self, instance: &mut MockInstance<UserData>) {
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-true",
|_, _: HList![]| Ok(hlist![1_i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-false",
|_, _: HList![]| Ok(hlist![0_i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-s8",
|_, _: HList![]| Ok(hlist![-125_i8 as u8 as i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-u8",
|_, _: HList![]| Ok(hlist![200_u8 as i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-s16",
|_, _: HList![]| Ok(hlist![-410_i16 as u16 as i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-u16",
|_, _: HList![]| Ok(hlist![60_000_u16 as i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-s32",
|_, _: HList![]| Ok(hlist![-100_000_i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-u32",
|_, _: HList![]| Ok(hlist![3_000_111_i32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-s64",
|_, _: HList![]| Ok(hlist![-5_000_000_i64]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-u64",
|_, _: HList![]| Ok(hlist![10_000_000_000_i64]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-float32",
|_, _: HList![]| Ok(hlist![-0.125_f32]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/getters#get-float64",
|_, _: HList![]| Ok(hlist![128.25_f64]),
1,
);
}
/// Mock the exported functions from the "export-setters" module.
fn export_setters(&mut self, instance: &mut MockInstance<UserData>) {
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-bool",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, 0);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-s8",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, -100_i8 as i32);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-u8",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, 201);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-s16",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, -20_000_i16 as i32);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-u16",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, 50_000);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-s32",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, -2_000_000);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-u32",
|_, hlist_pat![parameter]: HList![i32]| {
assert_eq!(parameter, 4_000_000_u32 as i32);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-s64",
|_, hlist_pat![parameter]: HList![i64]| {
assert_eq!(parameter, -25_000_000_000);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-u64",
|_, hlist_pat![parameter]: HList![i64]| {
assert_eq!(parameter, 7_000_000_000);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-float32",
|_, hlist_pat![parameter]: HList![f32]| {
assert_eq!(parameter, 10.4);
Ok(hlist![])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/setters#set-float64",
|_, hlist_pat![parameter]: HList![f64]| {
assert_eq!(parameter, -0.000_08);
Ok(hlist![])
},
1,
);
}
/// Mock the exported functions from the "operations" module.
fn export_operations(&mut self, instance: &mut MockInstance<UserData>) {
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#and-bool",
|_, hlist_pat![first, second]: HList![i32, i32]| {
Ok(hlist![if first != 0 && second != 0 { 1 } else { 0 }])
},
2,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-s8",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-u8",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-s16",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-u16",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-s32",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-u32",
|_, hlist_pat![first, second]: HList![i32, i32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-s64",
|_, hlist_pat![first, second]: HList![i64, i64]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-u64",
|_, hlist_pat![first, second]: HList![i64, i64]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-float32",
|_, hlist_pat![first, second]: HList![f32, f32]| Ok(hlist![first + second]),
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/operations#add-float64",
|_, hlist_pat![first, second]: HList![f64, f64]| Ok(hlist![first + second]),
1,
);
}
/// Mock calling the imported function in the "import-simple-function" module.
fn import_simple_function(&mut self, instance: &mut MockInstance<UserData>) {
self.mock_exported_function(
instance,
"witty-macros:test-modules/entrypoint#entrypoint",
|caller, _: HList![]| {
let hlist_pat![] = caller.call_imported_function(
"witty-macros:test-modules/simple-function#simple",
hlist![],
)?;
Ok(hlist![])
},
1,
);
}
/// Mock calling the imported functions in the "import-getters" module.
fn import_getters(&mut self, instance: &mut MockInstance<UserData>) {
fn check_getter<Value, UserData>(
caller: &MockInstance<UserData>,
name: &str,
expected_value: Value,
) where
Value: Debug + PartialEq + WitLoad + 'static,
{
let value: Value = caller
.call_imported_function(
&format!("witty-macros:test-modules/getters#{name}"),
hlist![],
)
.unwrap_or_else(|error| panic!("Failed to call getter function {name:?}: {error}"));
assert_eq!(value, expected_value);
}
self.mock_exported_function(
instance,
"witty-macros:test-modules/entrypoint#entrypoint",
|caller, _: HList![]| {
check_getter(&caller, "get-true", true);
check_getter(&caller, "get-false", false);
check_getter(&caller, "get-s8", -125_i8);
check_getter(&caller, "get-u8", 200_u8);
check_getter(&caller, "get-s16", -410_i16);
check_getter(&caller, "get-u16", 60_000_u16);
check_getter(&caller, "get-s32", -100_000_i32);
check_getter(&caller, "get-u32", 3_000_111_u32);
check_getter(&caller, "get-s64", -5_000_000_i64);
check_getter(&caller, "get-u64", 10_000_000_000_u64);
check_getter(&caller, "get-float32", -0.125_f32);
check_getter(&caller, "get-float64", 128.25_f64);
Ok(hlist![])
},
1,
);
}
/// Mock calling the imported functions in the "import-setters" module.
fn import_setters(&mut self, instance: &mut MockInstance<UserData>) {
fn send_to_setter<Value, UserData>(
caller: &MockInstance<UserData>,
name: &str,
value: Value,
) where
Value: WitStore + 'static,
Value::Layout: Add<HList![]>,
<Value::Layout as Add<HList![]>>::Output:
Layout<Flat = <<Value::Layout as Layout>::Flat as Add<HList![]>>::Output>,
<Value::Layout as Layout>::Flat: Add<HList![]>,
{
let () = caller
.call_imported_function(
&format!("witty-macros:test-modules/setters#{name}"),
hlist![value],
)
.unwrap_or_else(|error| panic!("Failed to call setter function {name:?}: {error}"));
}
self.mock_exported_function(
instance,
"witty-macros:test-modules/entrypoint#entrypoint",
|caller, _: HList![]| {
send_to_setter(&caller, "set-bool", false);
send_to_setter(&caller, "set-s8", -100_i8);
send_to_setter(&caller, "set-u8", 201_u8);
send_to_setter(&caller, "set-s16", -20_000_i16);
send_to_setter(&caller, "set-u16", 50_000_u16);
send_to_setter(&caller, "set-s32", -2_000_000_i32);
send_to_setter(&caller, "set-u32", 4_000_000_u32);
send_to_setter(&caller, "set-s64", -25_000_000_000_i64);
send_to_setter(&caller, "set-u64", 7_000_000_000_u64);
send_to_setter(&caller, "set-float32", 10.4_f32);
send_to_setter(&caller, "set-float64", -0.000_08_f64);
Ok(hlist![])
},
1,
);
}
/// Mock calling the imported functions in the "import-operations".
fn import_operations(&mut self, instance: &mut MockInstance<UserData>) {
fn check_operation<Value, UserData>(
caller: &MockInstance<UserData>,
name: &str,
operands: impl WitStore + 'static,
expected_result: Value,
) where
Value: Debug + PartialEq + WitLoad + 'static,
{
let result: Value = caller
.call_imported_function(
&format!("witty-macros:test-modules/operations#{name}"),
operands,
)
.unwrap_or_else(|error| panic!("Failed to call setter function {name:?}: {error}"));
assert_eq!(result, expected_result);
}
self.mock_exported_function(
instance,
"witty-macros:test-modules/entrypoint#entrypoint",
|caller, _: HList![]| {
check_operation(&caller, "and-bool", (true, true), true);
check_operation(&caller, "and-bool", (true, false), false);
check_operation(&caller, "add-s8", (-100_i8, 40_i8), -60_i8);
check_operation(&caller, "add-u8", (201_u8, 32_u8), 233_u8);
check_operation(&caller, "add-s16", (-20_000_i16, 30_000_i16), 10_000_i16);
check_operation(&caller, "add-u16", (50_000_u16, 256_u16), 50_256_u16);
check_operation(&caller, "add-s32", (-2_000_000_i32, -1_i32), -2_000_001_i32);
check_operation(&caller, "add-u32", (4_000_000_u32, 1_u32), 4_000_001_u32);
check_operation(
&caller,
"add-s64",
(-16_000_000_i64, 32_000_000_i64),
16_000_000_i64,
);
check_operation(
&caller,
"add-u64",
(3_000_000_000_u64, 9_345_678_999_u64),
12_345_678_999_u64,
);
check_operation(&caller, "add-float32", (10.5_f32, 120.25_f32), 130.75_f32);
check_operation(
&caller,
"add-float64",
(-0.000_08_f64, 1.0_f64),
0.999_92_f64,
);
Ok(hlist![])
},
1,
);
}
/// Mock the behavior of the "reentrancy-simple-function" module.
fn reentrancy_simple_function(&mut self, instance: &mut MockInstance<UserData>) {
self.import_simple_function(instance);
self.export_simple_function(instance);
}
/// Mock the behavior of the "reentrancy-getters" module.
fn reentrancy_getters(&mut self, instance: &mut MockInstance<UserData>) {
self.import_getters(instance);
self.export_getters(instance);
}
/// Mock the behavior of the "reentrancy-setters" module.
fn reentrancy_setters(&mut self, instance: &mut MockInstance<UserData>) {
self.import_setters(instance);
self.export_setters(instance);
}
/// Mock the behavior of the "reentrancy-operations" module.
fn reentrancy_operations(&mut self, instance: &mut MockInstance<UserData>) {
self.import_operations(instance);
self.export_operations(instance);
}
/// Mock the behavior of the "reentrancy-global-state" module.
fn reentrancy_global_state(&mut self, instance: &mut MockInstance<UserData>) {
let global_state_for_entrypoint = Arc::new(AtomicU32::new(0));
let global_state_for_getter = global_state_for_entrypoint.clone();
self.mock_exported_function(
instance,
"witty-macros:test-modules/global-state#entrypoint",
move |caller, hlist_pat![value]: HList![i32]| {
global_state_for_entrypoint.store(value as u32, Ordering::Release);
caller
.call_imported_function(
"witty-macros:test-modules/get-host-value#get-host-value",
(),
)
.map(|value: u32| hlist![value as i32])
},
1,
);
self.mock_exported_function(
instance,
"witty-macros:test-modules/global-state#get-global-state",
move |_, _: HList![]| {
Ok(hlist![
global_state_for_getter.load(Ordering::Acquire) as i32
])
},
1,
);
}
/// Mocks an exported function with the provided `name`.
///
/// The `handler` is used when the exported function is called, which expected to happen
/// `expected_calls` times.
///
/// The created [`MockExportedFunction`] is automatically registered in the `instance` and
/// added to the current list of deferred assertions, to be checked when the test finishes.
fn mock_exported_function<Parameters, Results>(
&mut self,
instance: &mut MockInstance<UserData>,
name: &str,
handler: impl Fn(MockInstance<UserData>, Parameters) -> Result<Results, RuntimeError> + 'static,
expected_calls: usize,
) where
Parameters: 'static,
Results: 'static,
{
let mock_exported_function = MockExportedFunction::new(name, handler, expected_calls);
mock_exported_function.register(instance);
self.deferred_assertions
.push(Box::new(mock_exported_function));
}
}
/// Marker type to indicate no extra functions should be exported to the Wasm instance.
#[allow(dead_code)]
pub struct WithoutExports;
impl<T> ExportTo<T> for WithoutExports {
fn export_to(_target: &mut T) -> Result<(), RuntimeError> {
Ok(())
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/common/wit_interface_test.rs | linera-witty/tests/common/wit_interface_test.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Shared code to test generated [`WitInterface`] implementations for the interfaces used
//! in the tests.
use linera_witty::{
test::{assert_interface_dependencies, assert_interface_functions},
wit_generation::WitInterface,
};
/// Expected snippets for the `entrypoint` interface.
// The `wit_import` integration test does not use an `Entrypoint` interface
#[allow(dead_code)]
pub const ENTRYPOINT: (&str, &[&str], &[(&str, &str)]) =
("entrypoint", &[" entrypoint: func();"], &[]);
/// Expected snippets for the `simple-function` interface.
pub const SIMPLE_FUNCTION: (&str, &[&str], &[(&str, &str)]) =
("simple-function", &[" simple: func();"], &[]);
/// Expected snippets for the `getters` interface.
pub const GETTERS: (&str, &[&str], &[(&str, &str)]) = (
"getters",
&[
" get-true: func() -> bool;",
" get-false: func() -> bool;",
" get-s8: func() -> s8;",
" get-u8: func() -> u8;",
" get-s16: func() -> s16;",
" get-u16: func() -> u16;",
" get-s32: func() -> s32;",
" get-u32: func() -> u32;",
" get-s64: func() -> s64;",
" get-u64: func() -> u64;",
" get-float32: func() -> float32;",
" get-float64: func() -> float64;",
],
&[
("bool", ""),
("float32", ""),
("float64", ""),
("s16", ""),
("s32", ""),
("s64", ""),
("s8", ""),
("u16", ""),
("u32", ""),
("u64", ""),
("u8", ""),
],
);
/// Expected snippets for the `setters` interface.
pub const SETTERS: (&str, &[&str], &[(&str, &str)]) = (
"setters",
&[
" set-bool: func(value: bool);",
" set-s8: func(value: s8);",
" set-u8: func(value: u8);",
" set-s16: func(value: s16);",
" set-u16: func(value: u16);",
" set-s32: func(value: s32);",
" set-u32: func(value: u32);",
" set-s64: func(value: s64);",
" set-u64: func(value: u64);",
" set-float32: func(value: float32);",
" set-float64: func(value: float64);",
],
&[
("bool", ""),
("float32", ""),
("float64", ""),
("s16", ""),
("s32", ""),
("s64", ""),
("s8", ""),
("u16", ""),
("u32", ""),
("u64", ""),
("u8", ""),
],
);
/// Expected snippets for the `operations` interface.
pub const OPERATIONS: (&str, &[&str], &[(&str, &str)]) = (
"operations",
&[
" and-bool: func(first: bool, second: bool) -> bool;",
" add-s8: func(first: s8, second: s8) -> s8;",
" add-u8: func(first: u8, second: u8) -> u8;",
" add-s16: func(first: s16, second: s16) -> s16;",
" add-u16: func(first: u16, second: u16) -> u16;",
" add-s32: func(first: s32, second: s32) -> s32;",
" add-u32: func(first: u32, second: u32) -> u32;",
" add-s64: func(first: s64, second: s64) -> s64;",
" add-u64: func(first: u64, second: u64) -> u64;",
" add-float32: func(first: float32, second: float32) -> float32;",
" add-float64: func(first: float64, second: float64) -> float64;",
],
&[
("bool", ""),
("float32", ""),
("float64", ""),
("s16", ""),
("s32", ""),
("s64", ""),
("s8", ""),
("u16", ""),
("u32", ""),
("u64", ""),
("u8", ""),
],
);
/// Tests the [`WitInterface`] of a specified type, checking that its WIT snippets match
/// the `expected_snippets`.
pub fn test_wit_interface<Interface>(expected_snippets: (&str, &[&str], &[(&str, &str)]))
where
Interface: WitInterface,
{
let (expected_name, expected_functions, expected_dependencies) = expected_snippets;
assert_eq!(Interface::wit_package(), "witty-macros:test-modules");
assert_eq!(Interface::wit_name(), expected_name);
assert_interface_functions::<Interface>(expected_functions);
assert_interface_dependencies::<Interface>(expected_dependencies.iter().copied());
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/tests/common/types.rs | linera-witty/tests/common/types.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! Dummy types used in tests.
use std::{rc::Rc, sync::Arc};
use linera_witty::{WitLoad, WitStore, WitType};
/// A type that wraps a simple type.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct SimpleWrapper(pub bool);
/// A tuple struct that doesn't need any internal padding in its memory layout.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct TupleWithoutPadding(pub u64, pub i32, pub i16);
/// A tuple struct that requires internal padding in its memory layout between two of its fields.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct TupleWithPadding(pub u16, pub u32, pub i64);
/// A struct with named fields that requires padding in two locations in its memory layout.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct RecordWithDoublePadding {
pub first: u16,
pub second: u32,
pub third: i8,
pub fourth: i64,
}
/// A simple struct with named fields to be used inside a more complex struct.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct Leaf {
pub first: bool,
pub second: u128,
}
/// A struct that contains fields with custom types that also have derived trait implementations.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct Branch {
pub tag: u16,
pub first_leaf: Leaf,
pub second_leaf: Leaf,
}
/// An enum that has its alignment obtained from one variant and its size from another.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub enum Enum {
Empty,
LargeVariantWithLooseAlignment(i8, i8, i8, i8, i8, i8, i8, i8, i8, i8),
SmallerVariantWithStrictAlignment { inner: u64 },
}
/// A generic struct with some specialized fields.
#[derive(Clone, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
#[witty_specialize_with(A = u8, B = i16)]
pub struct SpecializedGenericStruct<A, B> {
pub first: A,
pub second: B,
pub both: Vec<(A, B)>,
}
/// A generic enum with some specialized fields.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
#[witty_specialize_with(A = Option<bool>)]
#[witty_specialize_with(B = u32)]
pub enum SpecializedGenericEnum<A, B> {
None,
First(A),
MaybeSecond { maybe: Option<B> },
}
/// A struct that contains fields that are wrapped in smart pointer types.
#[derive(Clone, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct StructWithHeapFields {
pub boxed: Box<SimpleWrapper>,
pub rced: Rc<Leaf>,
pub arced: Arc<Enum>,
}
/// A struct that contains fields that should all be represented as lists.
#[derive(Clone, Debug, Eq, PartialEq, WitType, WitLoad, WitStore)]
pub struct StructWithLists {
pub vec: Vec<SimpleWrapper>,
pub boxed_slice: Box<[TupleWithPadding]>,
pub rced_slice: Rc<[Leaf]>,
pub arced_slice: Arc<[RecordWithDoublePadding]>,
}
/// A type that wraps a slice.
#[derive(Clone, Copy, Debug, Eq, PartialEq, WitType, WitStore)]
pub struct SliceWrapper<'slice>(pub &'slice [TupleWithoutPadding]);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/build.rs | linera-ethereum/build.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
fn main() {
cfg_aliases::cfg_aliases! {
with_testing: { any(test, feature = "test") },
};
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/src/lib.rs | linera-ethereum/src/lib.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! This module provides functionalities for accessing an Ethereum blockchain node.
//! Enabling the `ethereum` allows to make the tests work. This requires installing
//! the `anvil` from [FOUNDRY] and the [SOLC] compiler version 0.8.25
//!
//! [FOUNDRY]: https://book.getfoundry.sh/
//! [SOLC]: https://soliditylang.org/
pub mod client;
pub mod common;
#[cfg(not(target_arch = "wasm32"))]
pub mod provider;
/// Helper types for tests and similar purposes.
#[cfg(not(target_arch = "wasm32"))]
pub mod test_utils;
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/src/client.rs | linera-ethereum/src/client.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Debug;
use alloy::rpc::types::eth::{
request::{TransactionInput, TransactionRequest},
BlockId, BlockNumberOrTag, Filter, Log,
};
use alloy_primitives::{Address, Bytes, U256, U64};
use async_trait::async_trait;
use linera_base::ensure;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::value::RawValue;
use crate::common::{
event_name_from_expanded, parse_log, EthereumEvent, EthereumQueryError, EthereumServiceError,
};
/// A basic RPC client for making JSON queries
#[async_trait]
pub trait JsonRpcClient {
type Error: From<serde_json::Error> + From<EthereumQueryError>;
/// The inner function that has to be implemented and access the client
async fn request_inner(&self, payload: Vec<u8>) -> Result<Vec<u8>, Self::Error>;
/// Gets a new ID for the next message.
async fn get_id(&self) -> u64;
/// The function doing the parsing of the input and output.
async fn request<T, R>(&self, method: &str, params: T) -> Result<R, Self::Error>
where
T: Debug + Serialize + Send + Sync,
R: DeserializeOwned + Send,
{
let id = self.get_id().await;
let payload = JsonRpcRequest::new(id, method, params);
let payload = serde_json::to_vec(&payload)?;
let body = self.request_inner(payload).await?;
let result = serde_json::from_slice::<JsonRpcResponse>(&body)?;
let raw = result.result;
let res = serde_json::from_str(raw.get())?;
ensure!(id == result.id, EthereumQueryError::IdIsNotMatching);
ensure!(
"2.0" == result.jsonrpc,
EthereumQueryError::WrongJsonRpcVersion
);
Ok(res)
}
}
#[derive(Serialize, Deserialize, Debug)]
struct JsonRpcRequest<'a, T> {
id: u64,
jsonrpc: &'a str,
method: &'a str,
params: T,
}
impl<'a, T> JsonRpcRequest<'a, T> {
/// Creates a new JSON RPC request, the id does not matter
pub fn new(id: u64, method: &'a str, params: T) -> Self {
Self {
id,
jsonrpc: "2.0",
method,
params,
}
}
}
#[derive(Debug, Deserialize)]
pub struct JsonRpcResponse {
id: u64,
jsonrpc: String,
result: Box<RawValue>,
}
/// The basic Ethereum queries that can be used from a smart contract and do not require
/// gas to be executed.
#[async_trait]
pub trait EthereumQueries {
type Error;
/// Lists all the accounts of the Ethereum node.
async fn get_accounts(&self) -> Result<Vec<String>, Self::Error>;
/// Gets the latest block number of the Ethereum node.
async fn get_block_number(&self) -> Result<u64, Self::Error>;
/// Gets the balance of the specified address at the specified block number.
/// if no block number is specified then the balance of the latest block is
/// returned.
async fn get_balance(&self, address: &str, block_number: u64) -> Result<U256, Self::Error>;
/// Reads the events of the smart contract.
///
/// This is done from a specified `contract_address` and `event_name_expanded`.
/// That is one should have `MyEvent(type1 indexed,type2)` instead
/// of the usual `MyEvent(type1,type2)`
///
/// The `from_block` is inclusive.
/// The `to_block` is exclusive (contrary to Ethereum where it is inclusive)
async fn read_events(
&self,
contract_address: &str,
event_name_expanded: &str,
from_block: u64,
to_block: u64,
) -> Result<Vec<EthereumEvent>, Self::Error>;
/// The operation done with `eth_call` on Ethereum returns
/// a result but are not committed to the blockchain. This can be useful for example
/// for executing function that are const and allow to inspect
/// the contract without modifying it.
async fn non_executive_call(
&self,
contract_address: &str,
data: Bytes,
from: &str,
block: u64,
) -> Result<Bytes, Self::Error>;
}
pub(crate) fn get_block_id(block_number: u64) -> BlockId {
let number = BlockNumberOrTag::Number(block_number);
BlockId::Number(number)
}
#[async_trait]
impl<C> EthereumQueries for C
where
C: JsonRpcClient + Sync,
EthereumServiceError: From<<C as JsonRpcClient>::Error>,
{
type Error = EthereumServiceError;
async fn get_accounts(&self) -> Result<Vec<String>, Self::Error> {
let results: Vec<String> = self.request("eth_accounts", ()).await?;
Ok(results
.into_iter()
.map(|x| x.to_lowercase())
.collect::<Vec<_>>())
}
async fn get_block_number(&self) -> Result<u64, Self::Error> {
let result = self.request::<_, U64>("eth_blockNumber", ()).await?;
Ok(result.to::<u64>())
}
async fn get_balance(&self, address: &str, block_number: u64) -> Result<U256, Self::Error> {
let address = address.parse::<Address>()?;
let tag = get_block_id(block_number);
Ok(self.request("eth_getBalance", (address, tag)).await?)
}
async fn read_events(
&self,
contract_address: &str,
event_name_expanded: &str,
from_block: u64,
to_block: u64,
) -> Result<Vec<EthereumEvent>, Self::Error> {
let contract_address = contract_address.parse::<Address>()?;
let event_name = event_name_from_expanded(event_name_expanded);
let filter = Filter::new()
.address(contract_address)
.event(&event_name)
.from_block(from_block)
.to_block(to_block - 1);
let events = self
.request::<_, Vec<Log>>("eth_getLogs", (filter,))
.await?;
events
.into_iter()
.map(|x| parse_log(event_name_expanded, x))
.collect::<Result<_, _>>()
}
async fn non_executive_call(
&self,
contract_address: &str,
data: Bytes,
from: &str,
block: u64,
) -> Result<Bytes, Self::Error> {
let contract_address = contract_address.parse::<Address>()?;
let from = from.parse::<Address>()?;
let input = TransactionInput::new(data);
let tx = TransactionRequest::default()
.from(from)
.to(contract_address)
.input(input);
let tag = get_block_id(block);
Ok(self.request::<_, Bytes>("eth_call", (tx, tag)).await?)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/src/common.rs | linera-ethereum/src/common.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::num::ParseIntError;
#[cfg(not(target_arch = "wasm32"))]
use alloy::rpc::json_rpc;
use alloy::rpc::types::eth::Log;
use alloy_primitives::{Address, B256, U256};
use num_bigint::{BigInt, BigUint};
use num_traits::cast::ToPrimitive;
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum EthereumQueryError {
/// The ID should be matching
#[error("the ID should be matching")]
IdIsNotMatching,
/// wrong JSON-RPC version
#[error("wrong JSON-RPC version")]
WrongJsonRpcVersion,
}
#[derive(Debug, Error)]
pub enum EthereumServiceError {
/// The database is not coherent
#[error(transparent)]
EthereumQueryError(#[from] EthereumQueryError),
/// Parsing error
#[error(transparent)]
ParseIntError(#[from] ParseIntError),
#[error("Unsupported Ethereum type")]
UnsupportedEthereumTypeError,
#[error("Event parsing error")]
EventParsingError,
/// Parse big int error
#[error(transparent)]
ParseBigIntError(#[from] num_bigint::ParseBigIntError),
/// Ethereum parsing error
#[error("Ethereum parsing error")]
EthereumParsingError,
/// Parse bool error
#[error("Parse bool error")]
ParseBoolError,
/// Hex parsing error
#[error(transparent)]
FromHexError(#[from] alloy_primitives::hex::FromHexError),
/// `serde_json` error
#[error(transparent)]
JsonError(#[from] serde_json::Error),
/// RPC error
#[error(transparent)]
#[cfg(not(target_arch = "wasm32"))]
RpcError(#[from] json_rpc::RpcError<alloy::transports::TransportErrorKind>),
/// URL parsing error
#[error(transparent)]
#[cfg(not(target_arch = "wasm32"))]
UrlParseError(#[from] url::ParseError),
/// Alloy Reqwest error
#[error(transparent)]
#[cfg(not(target_arch = "wasm32"))]
AlloyReqwestError(#[from] alloy::transports::http::reqwest::Error),
}
/// A single primitive data type. This is used for example for the
/// entries of Ethereum events.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum EthereumDataType {
Address(String),
Uint256(U256),
Uint64(u64),
Int64(i64),
Uint32(u32),
Int32(i32),
Uint16(u16),
Int16(i16),
Uint8(u8),
Int8(i8),
Bool(bool),
}
/// Converts an entry named
/// `Event(type1 indexed,type2 indexed)` into `Event(type1,type2)`.
/// `event_name_expanded` is needed for parsing the obtained log.
pub fn event_name_from_expanded(event_name_expanded: &str) -> String {
event_name_expanded.replace(" indexed", "").to_string()
}
fn parse_entry(entry: B256, ethereum_type: &str) -> Result<EthereumDataType, EthereumServiceError> {
if ethereum_type == "address" {
let address = Address::from_word(entry);
let address = format!("{:?}", address);
return Ok(EthereumDataType::Address(address));
}
if ethereum_type == "uint256" {
let entry = U256::from_be_bytes(entry.0);
return Ok(EthereumDataType::Uint256(entry));
}
if ethereum_type == "uint64" {
let entry = BigUint::from_bytes_be(&entry.0);
let entry = entry.to_u64().unwrap();
return Ok(EthereumDataType::Uint64(entry));
}
if ethereum_type == "int64" {
let entry = BigInt::from_signed_bytes_be(&entry.0);
let entry = entry.to_i64().unwrap();
return Ok(EthereumDataType::Int64(entry));
}
if ethereum_type == "uint32" {
let entry = BigUint::from_bytes_be(&entry.0);
let entry = entry.to_u32().unwrap();
return Ok(EthereumDataType::Uint32(entry));
}
if ethereum_type == "int32" {
let entry = BigInt::from_signed_bytes_be(&entry.0);
let entry = entry.to_i32().unwrap();
return Ok(EthereumDataType::Int32(entry));
}
if ethereum_type == "uint16" {
let entry = BigUint::from_bytes_be(&entry.0);
let entry = entry.to_u16().unwrap();
return Ok(EthereumDataType::Uint16(entry));
}
if ethereum_type == "int16" {
let entry = BigInt::from_signed_bytes_be(&entry.0);
let entry = entry.to_i16().unwrap();
return Ok(EthereumDataType::Int16(entry));
}
if ethereum_type == "uint8" {
let entry = BigUint::from_bytes_be(&entry.0);
let entry = entry.to_u8().unwrap();
return Ok(EthereumDataType::Uint8(entry));
}
if ethereum_type == "int8" {
let entry = BigInt::from_signed_bytes_be(&entry.0);
let entry = entry.to_i8().unwrap();
return Ok(EthereumDataType::Int8(entry));
}
if ethereum_type == "bool" {
let entry = BigUint::from_bytes_be(&entry.0);
let entry = entry.to_u8().unwrap();
let entry = match entry {
1 => true,
0 => false,
_ => {
return Err(EthereumServiceError::ParseBoolError);
}
};
return Ok(EthereumDataType::Bool(entry));
}
Err(EthereumServiceError::UnsupportedEthereumTypeError)
}
/// The data type for an Ethereum event emitted by a smart contract
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EthereumEvent {
pub values: Vec<EthereumDataType>,
pub block_number: u64,
}
fn get_inner_event_type(event_name_expanded: &str) -> Result<String, EthereumServiceError> {
if let Some(opening_paren_index) = event_name_expanded.find('(') {
if let Some(closing_paren_index) = event_name_expanded.find(')') {
// Extract the substring between the parentheses
let inner_types = &event_name_expanded[opening_paren_index + 1..closing_paren_index];
return Ok(inner_types.to_string());
}
}
Err(EthereumServiceError::EventParsingError)
}
pub fn parse_log(
event_name_expanded: &str,
log: Log,
) -> Result<EthereumEvent, EthereumServiceError> {
let inner_types = get_inner_event_type(event_name_expanded)?;
let ethereum_types = inner_types
.split(',')
.map(str::to_string)
.collect::<Vec<_>>();
let mut values = Vec::new();
let mut topic_index = 0;
let mut data_index = 0;
let mut vec = [0_u8; 32];
let log_data = log.data();
let topics = log_data.topics();
for ethereum_type in ethereum_types {
values.push(match ethereum_type.strip_suffix(" indexed") {
None => {
for (i, val) in vec.iter_mut().enumerate() {
*val = log_data.data[data_index * 32 + i];
}
data_index += 1;
let entry = vec.into();
parse_entry(entry, ðereum_type)?
}
Some(ethereum_type) => {
topic_index += 1;
parse_entry(topics[topic_index], ethereum_type)?
}
});
}
let block_number = log.block_number.unwrap();
Ok(EthereumEvent {
values,
block_number,
})
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/src/provider.rs | linera-ethereum/src/provider.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use alloy::transports::http::reqwest::{header::CONTENT_TYPE, Client};
use async_lock::Mutex;
use async_trait::async_trait;
use crate::{client::JsonRpcClient, common::EthereumServiceError};
/// The Ethereum endpoint and its provider used for accessing the Ethereum node.
pub struct EthereumClientSimplified {
pub url: String,
pub id: Mutex<u64>,
}
#[async_trait]
impl JsonRpcClient for EthereumClientSimplified {
type Error = EthereumServiceError;
async fn get_id(&self) -> u64 {
let mut id = self.id.lock().await;
*id += 1;
*id
}
async fn request_inner(&self, payload: Vec<u8>) -> Result<Vec<u8>, Self::Error> {
let res = Client::new()
.post(self.url.clone())
.body(payload)
.header(CONTENT_TYPE, "application/json")
.send()
.await?;
let body = res.bytes().await?;
Ok(body.as_ref().to_vec())
}
}
impl EthereumClientSimplified {
/// Connects to an existing Ethereum node and creates an `EthereumClientSimplified`
/// if successful.
pub fn new(url: String) -> Self {
let id = Mutex::new(1);
Self { url, id }
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/src/test_utils/mod.rs | linera-ethereum/src/test_utils/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use alloy::{
network::{Ethereum, EthereumWallet},
node_bindings::{Anvil, AnvilInstance},
providers::{
fillers::{
BlobGasFiller, ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller,
WalletFiller,
},
ProviderBuilder, RootProvider,
},
signers::local::PrivateKeySigner,
sol,
};
use alloy_primitives::{Address, U256};
use linera_base::port::get_free_port;
use url::Url;
use crate::{
client::EthereumQueries, common::EthereumServiceError, provider::EthereumClientSimplified,
};
sol!(
#[allow(missing_docs)]
#[sol(rpc)]
SimpleTokenContract,
"./contracts/SimpleToken.json"
);
sol!(
#[allow(missing_docs)]
#[sol(rpc)]
EventNumericsContract,
"./contracts/EventNumerics.json"
);
#[allow(clippy::type_complexity)]
#[derive(Clone)]
pub struct EthereumClient {
pub provider: FillProvider<
JoinFill<
JoinFill<
alloy::providers::Identity,
JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>,
>,
WalletFiller<EthereumWallet>,
>,
RootProvider<Ethereum>,
>,
}
impl EthereumClient {
/// Connects to an existing Ethereum node and creates an `EthereumClient`
/// if successful.
pub fn new(url: String) -> Result<Self, EthereumServiceError> {
let rpc_url = Url::parse(&url)?;
// this address is in the anvil test.
let pk: PrivateKeySigner =
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
.parse()
.unwrap();
let wallet = EthereumWallet::from(pk);
let provider = ProviderBuilder::new()
.wallet(wallet.clone())
.connect_http(rpc_url);
let endpoint = Self { provider };
Ok(endpoint)
}
}
pub struct AnvilTest {
pub anvil_instance: AnvilInstance,
pub endpoint: String,
pub ethereum_client: EthereumClient,
pub rpc_url: Url,
}
pub async fn get_anvil() -> anyhow::Result<AnvilTest> {
let port = get_free_port().await?;
let anvil_instance = Anvil::new().port(port).try_spawn()?;
let endpoint = anvil_instance.endpoint();
let ethereum_client = EthereumClient::new(endpoint.clone())?;
let rpc_url = Url::parse(&endpoint)?;
Ok(AnvilTest {
anvil_instance,
endpoint,
ethereum_client,
rpc_url,
})
}
impl AnvilTest {
pub fn get_address(&self, index: usize) -> String {
let address = self.anvil_instance.addresses()[index];
format!("{:?}", address)
}
}
pub struct SimpleTokenContractFunction {
pub contract_address: String,
pub anvil_test: AnvilTest,
}
impl SimpleTokenContractFunction {
pub async fn new(anvil_test: AnvilTest) -> anyhow::Result<Self> {
// 2: initializing the contract
let initial_supply = U256::from(1000);
let simple_token =
SimpleTokenContract::deploy(&anvil_test.ethereum_client.provider, initial_supply)
.await?;
let contract_address = simple_token.address();
let contract_address = format!("{:?}", contract_address);
Ok(Self {
contract_address,
anvil_test,
})
}
// Only the balanceOf operation is of interest for this contract
pub async fn balance_of(&self, to: &str, block: u64) -> anyhow::Result<U256> {
// Getting the simple_token
let contract_address = self.contract_address.parse::<Address>()?;
let simple_token = SimpleTokenContract::new(
contract_address,
self.anvil_test.ethereum_client.provider.clone(),
);
// Creating the calldata
let to_address = to.parse::<Address>()?;
let data = simple_token.balanceOf(to_address).calldata().clone();
// Using the Ethereum client simplified.
let ethereum_client_simp = EthereumClientSimplified::new(self.anvil_test.endpoint.clone());
let answer = ethereum_client_simp
.non_executive_call(&self.contract_address, data, to, block)
.await?;
// Converting the output
let mut vec = [0_u8; 32];
for (i, val) in vec.iter_mut().enumerate() {
*val = answer.0[i];
}
let balance = U256::from_be_bytes(vec);
Ok(balance)
}
pub async fn transfer(&self, from: &str, to: &str, value: U256) -> anyhow::Result<()> {
// Getting the simple_token
let contract_address = self.contract_address.parse::<Address>()?;
let to_address = to.parse::<Address>()?;
let from_address = from.parse::<Address>()?;
let simple_token = SimpleTokenContract::new(
contract_address,
self.anvil_test.ethereum_client.provider.clone(),
);
// Doing the transfer
let builder = simple_token.transfer(to_address, value).from(from_address);
let _receipt = builder.send().await?.get_receipt().await?;
Ok(())
}
}
pub struct EventNumericsContractFunction {
pub contract_address: String,
pub anvil_test: AnvilTest,
}
impl EventNumericsContractFunction {
pub async fn new(anvil_test: AnvilTest) -> anyhow::Result<Self> {
// Deploying the event numerics contract
let initial_supply = U256::from(0);
let event_numerics =
EventNumericsContract::deploy(&anvil_test.ethereum_client.provider, initial_supply)
.await?;
// Getting the contract address
let contract_address = event_numerics.address();
let contract_address = format!("{:?}", contract_address);
Ok(Self {
contract_address,
anvil_test,
})
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-ethereum/tests/ethereum_test.rs | linera-ethereum/tests/ethereum_test.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
#[cfg(feature = "ethereum")]
use {
alloy_primitives::U256,
linera_ethereum::{
client::EthereumQueries,
common::{EthereumDataType, EthereumEvent},
provider::EthereumClientSimplified,
test_utils::{get_anvil, EventNumericsContractFunction, SimpleTokenContractFunction},
},
std::{collections::BTreeSet, str::FromStr},
};
#[cfg(feature = "ethereum")]
#[tokio::test]
async fn test_get_accounts_balance() -> anyhow::Result<()> {
let anvil_test = get_anvil().await?;
let ethereum_client_simp = EthereumClientSimplified::new(anvil_test.endpoint);
let addresses = ethereum_client_simp
.get_accounts()
.await?
.into_iter()
.collect::<BTreeSet<_>>();
let block_number = ethereum_client_simp.get_block_number().await?;
let target_balance = U256::from_str("10000000000000000000000")?;
for address in addresses {
let balance = ethereum_client_simp
.get_balance(&address, block_number)
.await?;
assert_eq!(balance, target_balance);
}
Ok(())
}
#[cfg(feature = "ethereum")]
#[tokio::test]
async fn test_event_numerics() -> anyhow::Result<()> {
let anvil_test = get_anvil().await?;
let ethereum_client_simp = EthereumClientSimplified::new(anvil_test.endpoint.clone());
let event_numerics = EventNumericsContractFunction::new(anvil_test).await?;
let contract_address = event_numerics.contract_address;
// Test the conversion of the types
let event_name_expanded = "Types(address indexed,address,uint256,uint64,int64,uint32,int32,uint16,int16,uint8,int8,bool)";
let from_block = 0;
let to_block = 2;
let events = ethereum_client_simp
.read_events(&contract_address, event_name_expanded, from_block, to_block)
.await?;
let addr0 = event_numerics.anvil_test.get_address(0);
let big_value = U256::from_str("239675476885367459284564394732743434463843674346373355625")?;
let target_event = EthereumEvent {
values: vec![
EthereumDataType::Address(addr0.clone()),
EthereumDataType::Address(addr0.clone()),
EthereumDataType::Uint256(big_value),
EthereumDataType::Uint64(4611686018427387904),
EthereumDataType::Int64(-1152921504606846976),
EthereumDataType::Uint32(1073726139),
EthereumDataType::Int32(-1072173379),
EthereumDataType::Uint16(16261),
EthereumDataType::Int16(-16249),
EthereumDataType::Uint8(135),
EthereumDataType::Int8(-120),
EthereumDataType::Bool(true),
],
block_number: 1,
};
assert_eq!(*events, [target_event.clone()]);
let events = ethereum_client_simp
.read_events(&contract_address, event_name_expanded, from_block, to_block)
.await?;
assert_eq!(*events, [target_event]);
Ok(())
}
#[cfg(feature = "ethereum")]
#[tokio::test]
async fn test_simple_token_events() -> anyhow::Result<()> {
let anvil_test = get_anvil().await?;
let ethereum_client_simp = EthereumClientSimplified::new(anvil_test.endpoint.clone());
let simple_token = SimpleTokenContractFunction::new(anvil_test).await?;
let contract_address = simple_token.contract_address.clone();
let addr0 = simple_token.anvil_test.get_address(0);
let addr1 = simple_token.anvil_test.get_address(1);
// Doing the transfer
// We have to use a direct call since only non-executive operation
// are done in the client. So, we use a direct call.
// First await returns a PendingTransaction and the second does the
// mining.
let value = U256::from(10);
simple_token.transfer(&addr0, &addr1, value).await?;
let from_block = 0;
let to_block = 3;
// Test the Transfer entries
let event_name_expanded = "Transfer(address indexed,address indexed,uint256)";
let events = ethereum_client_simp
.read_events(&contract_address, event_name_expanded, from_block, to_block)
.await?;
let value = U256::from(10);
let target_event = EthereumEvent {
values: vec![
EthereumDataType::Address(addr0),
EthereumDataType::Address(addr1),
EthereumDataType::Uint256(value),
],
block_number: 2,
};
assert_eq!(*events, [target_event.clone()]);
// Using the simplified client
let events = ethereum_client_simp
.read_events(&contract_address, event_name_expanded, from_block, to_block)
.await?;
assert_eq!(*events, [target_event]);
Ok(())
}
#[cfg(feature = "ethereum")]
#[tokio::test]
async fn test_simple_token_queries() -> anyhow::Result<()> {
let anvil_test = get_anvil().await?;
let simple_token = SimpleTokenContractFunction::new(anvil_test).await?;
let contract_address = simple_token.contract_address.clone();
let addr0 = simple_token.anvil_test.get_address(0);
let addr1 = simple_token.anvil_test.get_address(1);
// Doing the transfer
// We have to use a direct call since only non-executive operation
// are done in the client. So, we use a direct call.
// First await returns a PendingTransaction and the second does the
// mining.
let value = U256::from(10);
simple_token.transfer(&addr0, &addr1, value).await?;
// Checking the balances
let block1 = 1;
let balance0 = simple_token.balance_of(&addr0, block1).await?;
assert_eq!(balance0, U256::from(1000));
let balance1 = simple_token.balance_of(&addr1, block1).await?;
assert_eq!(balance1, U256::from(0));
// Checking the balances
let block2 = 2;
let balance0 = simple_token.balance_of(&addr0, block2).await?;
assert_eq!(balance0, U256::from(990));
let balance1 = simple_token.balance_of(&addr1, block2).await?;
assert_eq!(balance1, U256::from(10));
let balance_contract = simple_token.balance_of(&contract_address, block2).await?;
assert_eq!(balance_contract, U256::from(0));
Ok(())
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/lib.rs | web/@linera/client/src/lib.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
/*!
# `linera-web`
This module defines the JavaScript bindings to the client API.
It is compiled to Wasm, with a JavaScript wrapper to inject its imports, and published on
NPM as `@linera/client`.
The `signer` subdirectory contains a TypeScript interface specifying the types of objects
that can be passed as signers — cryptographic integrations used to sign transactions, as
well as a demo implementation (not recommended for production use) that stores a private
key directly in memory and uses it to sign.
*/
// We sometimes need functions in this module to be async in order to
// ensure the generated code will return a `Promise`.
#![allow(clippy::unused_async)]
#![recursion_limit = "256"]
use std::{rc::Rc, sync::Arc};
use futures::{future::FutureExt as _, lock::Mutex as AsyncMutex};
use linera_base::identifiers::ChainId;
use linera_client::chain_listener::{ChainListener, ClientContext as _};
use wasm_bindgen::prelude::*;
use web_sys::wasm_bindgen;
pub mod chain;
pub use chain::Chain;
pub mod faucet;
pub mod signer;
pub use signer::Signer;
pub mod storage;
pub use storage::Storage;
pub mod wallet;
pub use wallet::Wallet;
pub type Network = linera_rpc::node_provider::NodeProvider;
pub type Environment =
linera_core::environment::Impl<Storage, Network, Signer, Rc<linera_core::wallet::Memory>>;
type JsResult<T> = Result<T, JsError>;
/// The full client API, exposed to the wallet implementation. Calls
/// to this API can be trusted to have originated from the user's
/// request.
#[wasm_bindgen]
#[derive(Clone)]
pub struct Client(
// This use of `futures::lock::Mutex` is safe because we only
// expose concurrency to the browser, which must always run all
// futures on the global task queue.
// It does nothing here in this single-threaded context, but is
// hard-coded by `ChainListener`.
Arc<AsyncMutex<linera_client::ClientContext<Environment>>>,
);
#[wasm_bindgen]
impl Client {
/// Creates a new client and connects to the network.
///
/// # Errors
/// On transport or protocol error, if persistent storage is
/// unavailable, or if `options` is incorrectly structured.
#[wasm_bindgen(constructor)]
pub async fn new(
wallet: &Wallet,
signer: Signer,
options: Option<linera_client::Options>,
) -> Result<Client, JsError> {
const BLOCK_CACHE_SIZE: usize = 5000;
const EXECUTION_STATE_CACHE_SIZE: usize = 10000;
let options = options.unwrap_or_default();
let mut storage = storage::get_storage().await?;
wallet
.genesis_config
.initialize_storage(&mut storage)
.await?;
let client = linera_client::ClientContext::new(
storage.clone(),
wallet.chains.clone(),
signer,
&options,
wallet.default,
wallet.genesis_config.clone(),
BLOCK_CACHE_SIZE,
EXECUTION_STATE_CACHE_SIZE,
)
.await?;
// The `Arc` here is useless, but it is required by the `ChainListener` API.
#[expect(clippy::arc_with_non_send_sync)]
let client = Arc::new(AsyncMutex::new(client));
let client_clone = client.clone();
let chain_listener = ChainListener::new(
options.chain_listener_config,
client_clone,
storage,
tokio_util::sync::CancellationToken::new(),
tokio::sync::mpsc::unbounded_channel().1,
)
.run(true) // Enable background sync
.boxed_local()
.await?
.boxed_local();
wasm_bindgen_futures::spawn_local(
async move {
if let Err(error) = chain_listener.await {
tracing::error!("ChainListener error: {error:?}");
}
}
.boxed_local(),
);
log::info!("Linera Web client successfully initialized");
Ok(Self(client))
}
/// Connect to a chain on the Linera network.
///
/// # Errors
///
/// If the wallet could not be read or chain synchronization fails.
#[wasm_bindgen]
pub async fn chain(&self, chain: ChainId) -> JsResult<Chain> {
Ok(Chain {
chain_client: self.0.lock().await.make_chain_client(chain).await?,
client: self.clone(),
})
}
}
#[wasm_bindgen(start)]
pub fn main() {
use tracing_subscriber::{
prelude::__tracing_subscriber_SubscriberExt as _, util::SubscriberInitExt as _,
};
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.without_time()
.with_writer(tracing_web::MakeWebConsoleWriter::new()),
)
.with(
tracing_web::performance_layer()
.with_details_from_fields(tracing_subscriber::fmt::format::Pretty::default()),
)
.init();
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/storage.rs | web/@linera/client/src/storage.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
// TODO(#4637): convert to IndexedDbStore once we refactor Context
pub type Storage =
linera_storage::DbStorage<linera_views::memory::MemoryDatabase, linera_storage::WallClock>;
/// Create and return the storage implementation.
///
/// # Errors
/// If the storage can't be initialized.
pub async fn get_storage() -> Result<Storage, linera_views::memory::MemoryStoreError> {
Ok(linera_storage::DbStorage::maybe_create_and_connect(
&linera_views::memory::MemoryStoreConfig {
max_stream_queries: 1,
kill_on_drop: false,
},
"linera",
Some(linera_execution::WasmRuntime::Wasmer),
)
.await?
.with_allow_application_logs(true))
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/wallet.rs | web/@linera/client/src/wallet.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::rc::Rc;
use linera_base::identifiers::ChainId;
use linera_client::config::GenesisConfig;
use linera_core::wallet;
use wasm_bindgen::prelude::*;
use web_sys::wasm_bindgen;
use super::JsResult;
/// A wallet that stores the user's chains and keys in memory.
#[wasm_bindgen]
#[derive(Clone)]
pub struct Wallet {
pub(crate) chains: Rc<wallet::Memory>,
pub(crate) default: Option<ChainId>,
pub(crate) genesis_config: GenesisConfig,
}
#[wasm_bindgen]
impl Wallet {
/// Set the owner of a chain (the account used to sign blocks on this chain).
///
/// # Errors
///
/// If the provided `ChainId` or `AccountOwner` are in the wrong format.
#[wasm_bindgen(js_name = setOwner)]
pub async fn set_owner(&self, chain_id: JsValue, owner: JsValue) -> JsResult<()> {
let chain_id = serde_wasm_bindgen::from_value(chain_id)?;
let owner = serde_wasm_bindgen::from_value(owner)?;
self.chains
.mutate(chain_id, |chain| chain.owner = Some(owner))
.ok_or(JsError::new(&format!(
"chain {chain_id} doesn't exist in wallet"
)))
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/faucet.rs | web/@linera/client/src/faucet.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use linera_base::identifiers::AccountOwner;
use linera_core::wallet;
use wasm_bindgen::prelude::*;
use web_sys::wasm_bindgen;
use super::{JsResult, Wallet};
#[wasm_bindgen]
pub struct Faucet(linera_faucet_client::Faucet);
#[wasm_bindgen]
impl Faucet {
#[wasm_bindgen(constructor)]
#[must_use]
pub fn new(url: String) -> Faucet {
Faucet(linera_faucet_client::Faucet::new(url))
}
/// Creates a new wallet from the faucet.
///
/// # Errors
/// If we couldn't retrieve the genesis config from the faucet.
#[wasm_bindgen(js_name = createWallet)]
pub async fn create_wallet(&self) -> JsResult<Wallet> {
Ok(Wallet {
chains: std::rc::Rc::new(wallet::Memory::default()),
default: None,
genesis_config: self.0.genesis_config().await?,
})
}
/// Claims a new chain from the faucet, with a new keypair and some tokens.
///
/// # Errors
/// - if we fail to get the list of current validators from the faucet
/// - if we fail to claim the chain from the faucet
/// - if we fail to persist the new chain or keypair to the wallet
///
/// # Panics
/// If an error occurs in the chain listener task.
#[wasm_bindgen(js_name = claimChain)]
pub async fn claim_chain(&self, wallet: &mut Wallet, owner: AccountOwner) -> JsResult<String> {
tracing::info!(
"Requesting a new chain for owner {} using the faucet at address {}",
owner,
self.0.url(),
);
let description = self.0.claim(&owner).await?;
let chain_id = description.id();
wallet.chains.insert(
chain_id,
wallet::Chain {
owner: Some(owner),
..description.into()
},
);
if wallet.default.is_none() {
wallet.default = Some(chain_id);
}
Ok(chain_id.to_string())
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/chain/application.rs | web/@linera/client/src/chain/application.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use linera_base::identifiers::{AccountOwner, ApplicationId};
use linera_core::client::ChainClient;
use wasm_bindgen::prelude::*;
use web_sys::wasm_bindgen;
use crate::{Client, Environment, JsResult};
#[wasm_bindgen]
pub struct Application {
pub(crate) client: Client,
pub(crate) chain_client: ChainClient<Environment>,
pub(crate) id: ApplicationId,
}
#[derive(Default, serde::Deserialize, tsify::Tsify)]
#[serde(rename_all = "camelCase")]
#[tsify(from_wasm_abi)]
pub struct QueryOptions {
#[serde(default)]
pub block_hash: Option<String>,
#[serde(default)]
pub owner: Option<AccountOwner>,
}
#[wasm_bindgen]
impl Application {
/// Performs a query against an application's service.
///
/// If `block_hash` is non-empty, it specifies the block at which to
/// perform the query; otherwise, the latest block is used.
///
/// # Errors
/// If the application ID is invalid, the query is incorrect, or
/// the response isn't valid UTF-8.
///
/// # Panics
/// On internal protocol errors.
#[wasm_bindgen]
// TODO(#5253) allow passing bytes here rather than just strings
// TODO(#5152) a lot of this logic is shared with `linera_service::node_service`
pub async fn query(&self, query: &str, options: Option<QueryOptions>) -> JsResult<String> {
tracing::debug!("querying application: {query}");
let QueryOptions { block_hash, owner } = options.unwrap_or_default();
let mut chain_client = self.chain_client.clone();
if let Some(owner) = owner {
chain_client.set_preferred_owner(owner);
}
let block_hash = if let Some(hash) = block_hash {
Some(hash.as_str().parse()?)
} else {
None
};
let linera_execution::QueryOutcome {
response: linera_execution::QueryResponse::User(response),
operations,
} = chain_client
.query_application(
linera_execution::Query::User {
application_id: self.id,
bytes: query.as_bytes().to_vec(),
},
block_hash,
)
.await?
else {
panic!("system response to user query")
};
if !operations.is_empty() {
let _hash = self
.client
.0
.lock()
.await
.apply_client_command(&chain_client, |_chain_client| {
chain_client.execute_operations(operations.clone(), vec![])
})
.await?;
}
Ok(String::from_utf8(response)?)
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/chain/mod.rs | web/@linera/client/src/chain/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::collections::HashMap;
use futures::stream::StreamExt;
use linera_base::identifiers::AccountOwner;
use linera_client::chain_listener::ClientContext as _;
use linera_core::{
client::ChainClient,
node::{ValidatorNode as _, ValidatorNodeProvider as _},
};
use serde::ser::Serialize as _;
use wasm_bindgen::prelude::*;
use web_sys::{js_sys, wasm_bindgen};
use crate::{Client, Environment, JsResult};
pub mod application;
pub use application::Application;
#[wasm_bindgen]
pub struct Chain {
pub(crate) client: Client,
pub(crate) chain_client: ChainClient<Environment>,
}
#[derive(serde::Deserialize, tsify::Tsify)]
#[tsify(from_wasm_abi)]
pub struct TransferParams {
#[serde(default)]
pub donor: Option<AccountOwner>,
pub amount: u64,
pub recipient: linera_base::identifiers::Account,
}
#[derive(Default, serde::Deserialize, tsify::Tsify)]
#[tsify(from_wasm_abi)]
pub struct AddOwnerOptions {
#[serde(default)]
pub weight: u64,
}
#[wasm_bindgen]
impl Chain {
/// Sets a callback to be called when a notification is received
/// from the network.
///
/// # Errors
/// If we fail to subscribe to the notification stream.
///
/// # Panics
/// If the handler function fails.
#[wasm_bindgen(js_name = onNotification)]
pub fn on_notification(&self, handler: js_sys::Function) -> JsResult<()> {
let mut notifications = self.chain_client.subscribe()?;
wasm_bindgen_futures::spawn_local(async move {
while let Some(notification) = notifications.next().await {
tracing::debug!("received notification: {notification:?}");
handler
.call1(
&JsValue::null(),
&serde_wasm_bindgen::to_value(¬ification).unwrap(),
)
.unwrap_throw();
}
});
Ok(())
}
/// Transfers funds from one account to another.
///
/// `options` should be an options object of the form `{ donor,
/// recipient, amount }`; omitting `donor` will cause the funds to
/// come from the chain balance.
///
/// # Errors
/// - if the options object is of the wrong form
/// - if the transfer fails
#[wasm_bindgen]
pub async fn transfer(&self, params: TransferParams) -> JsResult<()> {
let _hash = self
.client
.0
.lock()
.await
.apply_client_command(&self.chain_client, |_chain_client| {
self.chain_client.transfer(
params.donor.unwrap_or(AccountOwner::CHAIN),
linera_base::data_types::Amount::from_tokens(params.amount.into()),
params.recipient,
)
})
.await?;
Ok(())
}
/// Gets the balance of the default chain.
///
/// # Errors
/// If the chain couldn't be established.
pub async fn balance(&self) -> JsResult<String> {
Ok(self.chain_client.query_balance().await?.to_string())
}
/// Gets the identity of the default chain.
///
/// # Errors
/// If the chain couldn't be established.
pub async fn identity(&self) -> JsResult<AccountOwner> {
Ok(self.chain_client.identity().await?)
}
/// Adds a new owner to the default chain.
///
/// # Errors
///
/// If the owner is in the wrong format, or the chain client can't be instantiated.
#[wasm_bindgen(js_name = addOwner)]
pub async fn add_owner(
&self,
owner: AccountOwner,
options: Option<AddOwnerOptions>,
) -> JsResult<()> {
let AddOwnerOptions { weight } = options.unwrap_or_default();
self.client
.0
.lock()
.await
.apply_client_command(&self.chain_client, |_chain_client| {
self.chain_client.share_ownership(owner, weight)
})
.await?;
Ok(())
}
/// Gets the version information of the validators of the current network.
///
/// # Errors
/// If a validator is unreachable.
#[wasm_bindgen(js_name = validatorVersionInfo)]
pub async fn validator_version_info(&self) -> JsResult<JsValue> {
self.chain_client.synchronize_from_validators().await?;
let result = self.chain_client.local_committee().await;
let mut client = self.client.0.lock().await;
client.update_wallet(&self.chain_client).await?;
let committee = result?;
let node_provider = client.make_node_provider();
let mut validator_versions = HashMap::new();
for (name, state) in committee.validators() {
match node_provider
.make_node(&state.network_address)?
.get_version_info()
.await
{
Ok(version_info) => {
if validator_versions
.insert(name, version_info.clone())
.is_some()
{
tracing::warn!("duplicate validator entry for validator {name:?}");
}
}
Err(e) => {
tracing::warn!(
"failed to get version information for validator {name:?}:\n{e:?}"
);
}
}
}
Ok(validator_versions.serialize(
&serde_wasm_bindgen::Serializer::new()
.serialize_large_number_types_as_bigints(true)
.serialize_maps_as_objects(true),
)?)
}
/// Retrieves an application for querying.
///
/// # Errors
/// If the application ID is invalid.
#[wasm_bindgen]
pub async fn application(&self, id: &str) -> JsResult<Application> {
web_sys::console::debug_1(&format!("connecting to Linera application {id}").into());
Ok(Application {
client: self.client.clone(),
chain_client: self.chain_client.clone(),
id: id.parse()?,
})
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/web/@linera/client/src/signer/mod.rs | web/@linera/client/src/signer/mod.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! This module contains various implementation of the [`Signer`] trait usable in the browser.
use std::fmt::Display;
use linera_base::{
crypto::{AccountSignature, CryptoHash},
identifiers::AccountOwner,
};
use wasm_bindgen::prelude::*;
use web_sys::wasm_bindgen;
// TODO(#5150) remove this in favour of passing up arbitrary `JsValue` errors
#[repr(u8)]
#[wasm_bindgen(js_name = "SignerError")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Error {
MissingKey = 0,
SigningError = 1,
PublicKeyParse = 2,
JsConversion = 3,
UnexpectedSignatureFormat = 4,
InvalidAccountOwnerType = 5,
Unknown = 9,
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::MissingKey => write!(f, "No key found for the given owner"),
Error::SigningError => write!(f, "Error signing the value"),
Error::PublicKeyParse => write!(f, "Error parsing the public key"),
Error::JsConversion => write!(f, "Error converting JS value"),
Error::UnexpectedSignatureFormat => {
write!(f, "Unexpected signature format received from JS")
}
Error::InvalidAccountOwnerType => {
write!(
f,
"Invalid account owner type provided. Expected AccountOwner::Address20"
)
}
Error::Unknown => write!(f, "An unknown error occurred"),
}
}
}
impl From<JsValue> for Error {
fn from(value: JsValue) -> Self {
match value.as_f64().and_then(num_traits::cast) {
Some(0u8) => Error::MissingKey,
Some(1) => Error::SigningError,
Some(2) => Error::PublicKeyParse,
Some(3) => Error::JsConversion,
Some(4) => Error::UnexpectedSignatureFormat,
Some(5) => Error::InvalidAccountOwnerType,
_ => Error::Unknown,
}
}
}
impl std::error::Error for Error {}
#[wasm_bindgen(typescript_custom_section)]
const _: &str = r#"import type { Signer } from '../signer/index.js';"#;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "Signer")]
pub type Signer;
#[wasm_bindgen(catch, method)]
async fn sign(
this: &Signer,
owner: AccountOwner,
value: Vec<u8>,
) -> Result<js_sys::JsString, JsValue>;
#[wasm_bindgen(catch, method, js_name = "containsKey")]
async fn contains_key(this: &Signer, owner: AccountOwner) -> Result<JsValue, JsValue>;
}
impl linera_base::crypto::Signer for Signer {
type Error = Error;
async fn contains_key(&self, owner: &AccountOwner) -> Result<bool, Self::Error> {
Ok(self.contains_key(*owner).await?.is_truthy())
}
async fn sign(
&self,
owner: &AccountOwner,
value: &CryptoHash,
) -> Result<AccountSignature, Self::Error> {
Ok(AccountSignature::EvmSecp256k1 {
signature: String::from(
self
// Pass CryptoHash without serializing as that adds bytes
// to the serialized value which we don't want for signing.
.sign(*owner, value.as_bytes().0.to_vec())
.await?,
)
.parse()
.map_err(|_| Error::UnexpectedSignatureFormat)?,
address: if let AccountOwner::Address20(address) = owner {
*address
} else {
return Err(Error::InvalidAccountOwnerType);
},
})
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/build.rs | linera-storage-service/build.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
fn main() -> Result<(), Box<dyn std::error::Error>> {
cfg_aliases::cfg_aliases! {
with_rocksdb: { all(feature = "rocksdb") },
with_testing: { any(test, feature = "test") },
with_metrics: { all(not(target_arch = "wasm32"), feature = "metrics") },
};
let no_includes: &[&str] = &[];
tonic_prost_build::configure()
.protoc_arg("--experimental_allow_proto3_optional")
.compile_protos(&["proto/key_value_store.proto"], no_includes)?;
Ok(())
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/src/lib.rs | linera-storage-service/src/lib.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! This module provides a shared key-value store server based on the RocksDB store and the in-memory store of `linera-views`.
//! The corresponding client implements the `KeyValueStore` and `KeyValueDatabase` traits.
pub mod key_value_store {
tonic::include_proto!("key_value_store.v1");
}
pub mod child;
pub mod client;
pub mod common;
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/src/client.rs | linera-storage-service/src/client.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::{
mem,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use async_lock::{Semaphore, SemaphoreGuard};
use futures::future::join_all;
use linera_base::{ensure, util::future::FutureSyncExt as _};
#[cfg(with_metrics)]
use linera_views::metering::MeteredDatabase;
#[cfg(with_testing)]
use linera_views::store::TestKeyValueDatabase;
use linera_views::{
batch::{Batch, WriteOperation},
lru_caching::LruCachingDatabase,
store::{KeyValueDatabase, ReadableKeyValueStore, WithError, WritableKeyValueStore},
};
use serde::de::DeserializeOwned;
use tonic::transport::{Channel, Endpoint};
#[cfg(with_testing)]
use crate::common::storage_service_test_endpoint;
use crate::{
common::{
KeyPrefix, StorageServiceStoreError, StorageServiceStoreInternalConfig, MAX_PAYLOAD_SIZE,
},
key_value_store::{
statement::Operation, storage_service_client::StorageServiceClient, KeyValue,
KeyValueAppend, ReplyContainsKey, ReplyContainsKeys, ReplyExistsNamespace,
ReplyFindKeyValuesByPrefix, ReplyFindKeysByPrefix, ReplyListAll, ReplyListRootKeys,
ReplyReadMultiValues, ReplyReadValue, ReplySpecificChunk, RequestContainsKey,
RequestContainsKeys, RequestCreateNamespace, RequestDeleteNamespace,
RequestExistsNamespace, RequestFindKeyValuesByPrefix, RequestFindKeysByPrefix,
RequestListRootKeys, RequestReadMultiValues, RequestReadValue, RequestSpecificChunk,
RequestWriteBatchExtended, Statement,
},
};
// The maximum key size is set to 1M rather arbitrarily.
const MAX_KEY_SIZE: usize = 1000000;
// The shared store client.
// * Interior mutability is required for the client because
// accessing requires mutability while the KeyValueStore
// does not allow it.
// * The semaphore and max_stream_queries work as other
// stores.
//
// The encoding of namespaces is done by taking their
// serialization. This works because the set of serialization
// of strings is prefix free.
// The data is stored in the following way.
// * A `key` in a `namespace` is stored as
// [`KeyPrefix::Key`] + namespace + key
// * An additional key with empty value is stored at
// [`KeyPrefix::Namespace`] + namespace
// is stored to indicate the existence of a namespace.
// * A key with empty value is stored at
// [`KeyPrefix::RootKey`] + namespace + root_key
// to indicate the existence of a root key.
#[derive(Clone)]
pub struct StorageServiceDatabaseInternal {
channel: Channel,
semaphore: Option<Arc<Semaphore>>,
max_stream_queries: usize,
namespace: Vec<u8>,
}
#[derive(Clone)]
pub struct StorageServiceStoreInternal {
channel: Channel,
semaphore: Option<Arc<Semaphore>>,
max_stream_queries: usize,
prefix_len: usize,
start_key: Vec<u8>,
root_key_written: Arc<AtomicBool>,
}
impl WithError for StorageServiceDatabaseInternal {
type Error = StorageServiceStoreError;
}
impl WithError for StorageServiceStoreInternal {
type Error = StorageServiceStoreError;
}
impl ReadableKeyValueStore for StorageServiceStoreInternal {
const MAX_KEY_SIZE: usize = MAX_KEY_SIZE;
fn max_stream_queries(&self) -> usize {
self.max_stream_queries
}
fn root_key(&self) -> Result<Vec<u8>, StorageServiceStoreError> {
let root_key = bcs::from_bytes(&self.start_key[self.prefix_len..])?;
Ok(root_key)
}
async fn read_value_bytes(
&self,
key: &[u8],
) -> Result<Option<Vec<u8>>, StorageServiceStoreError> {
ensure!(
key.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key = self.start_key.clone();
full_key.extend(key);
let query = RequestReadValue { key: full_key };
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client.process_read_value(request).make_sync().await?;
let response = response.into_inner();
let ReplyReadValue {
value,
message_index,
num_chunks,
} = response;
if num_chunks == 0 {
Ok(value)
} else {
self.read_entries(message_index, num_chunks).await
}
}
async fn contains_key(&self, key: &[u8]) -> Result<bool, StorageServiceStoreError> {
ensure!(
key.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key = self.start_key.clone();
full_key.extend(key);
let query = RequestContainsKey { key: full_key };
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client.process_contains_key(request).make_sync().await?;
let response = response.into_inner();
let ReplyContainsKey { test } = response;
Ok(test)
}
async fn contains_keys(&self, keys: &[Vec<u8>]) -> Result<Vec<bool>, StorageServiceStoreError> {
let mut full_keys = Vec::new();
for key in keys {
ensure!(
key.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key = self.start_key.clone();
full_key.extend(key);
full_keys.push(full_key);
}
let query = RequestContainsKeys { keys: full_keys };
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client.process_contains_keys(request).make_sync().await?;
let response = response.into_inner();
let ReplyContainsKeys { tests } = response;
Ok(tests)
}
async fn read_multi_values_bytes(
&self,
keys: &[Vec<u8>],
) -> Result<Vec<Option<Vec<u8>>>, StorageServiceStoreError> {
let mut full_keys = Vec::new();
for key in keys {
ensure!(
key.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key = self.start_key.clone();
full_key.extend(key);
full_keys.push(full_key);
}
let query = RequestReadMultiValues { keys: full_keys };
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client
.process_read_multi_values(request)
.make_sync()
.await?;
let response = response.into_inner();
let ReplyReadMultiValues {
values,
message_index,
num_chunks,
} = response;
if num_chunks == 0 {
let values = values.into_iter().map(|x| x.value).collect::<Vec<_>>();
Ok(values)
} else {
self.read_entries(message_index, num_chunks).await
}
}
async fn find_keys_by_prefix(
&self,
key_prefix: &[u8],
) -> Result<Vec<Vec<u8>>, StorageServiceStoreError> {
ensure!(
key_prefix.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key_prefix = self.start_key.clone();
full_key_prefix.extend(key_prefix);
let query = RequestFindKeysByPrefix {
key_prefix: full_key_prefix,
};
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client
.process_find_keys_by_prefix(request)
.make_sync()
.await?;
let response = response.into_inner();
let ReplyFindKeysByPrefix {
keys,
message_index,
num_chunks,
} = response;
if num_chunks == 0 {
Ok(keys)
} else {
self.read_entries(message_index, num_chunks).await
}
}
async fn find_key_values_by_prefix(
&self,
key_prefix: &[u8],
) -> Result<Vec<(Vec<u8>, Vec<u8>)>, StorageServiceStoreError> {
ensure!(
key_prefix.len() <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
let mut full_key_prefix = self.start_key.clone();
full_key_prefix.extend(key_prefix);
let query = RequestFindKeyValuesByPrefix {
key_prefix: full_key_prefix,
};
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let response = client
.process_find_key_values_by_prefix(request)
.make_sync()
.await?;
let response = response.into_inner();
let ReplyFindKeyValuesByPrefix {
key_values,
message_index,
num_chunks,
} = response;
if num_chunks == 0 {
let key_values = key_values
.into_iter()
.map(|x| (x.key, x.value))
.collect::<Vec<_>>();
Ok(key_values)
} else {
self.read_entries(message_index, num_chunks).await
}
}
}
impl WritableKeyValueStore for StorageServiceStoreInternal {
const MAX_VALUE_SIZE: usize = usize::MAX;
async fn write_batch(&self, batch: Batch) -> Result<(), StorageServiceStoreError> {
if batch.operations.is_empty() {
return Ok(());
}
let mut statements = Vec::new();
let mut chunk_size = 0;
if !self.root_key_written.fetch_or(true, Ordering::SeqCst) {
let mut full_key = self.start_key.clone();
full_key[0] = KeyPrefix::RootKey as u8;
let operation = Operation::Put(KeyValue {
key: full_key,
value: vec![],
});
let statement = Statement {
operation: Some(operation),
};
statements.push(statement);
chunk_size += self.start_key.len();
}
let bcs_root_key_len = self.start_key.len() - self.prefix_len;
for operation in batch.operations {
let (key_len, value_len) = match &operation {
WriteOperation::Delete { key } => (key.len(), 0),
WriteOperation::Put { key, value } => (key.len(), value.len()),
WriteOperation::DeletePrefix { key_prefix } => (key_prefix.len(), 0),
};
let operation_size = key_len + value_len + bcs_root_key_len;
ensure!(
key_len <= MAX_KEY_SIZE,
StorageServiceStoreError::KeyTooLong
);
if operation_size + chunk_size < MAX_PAYLOAD_SIZE {
let statement = self.get_statement(operation);
statements.push(statement);
chunk_size += operation_size;
} else {
self.submit_statements(mem::take(&mut statements)).await?;
chunk_size = 0;
if operation_size > MAX_PAYLOAD_SIZE {
// One single operation is especially big. So split it in chunks.
let WriteOperation::Put { key, value } = operation else {
// Only the put can go over the limit
unreachable!();
};
let mut full_key = self.start_key.clone();
full_key.extend(key);
let value_chunks = value
.chunks(MAX_PAYLOAD_SIZE)
.map(|x| x.to_vec())
.collect::<Vec<_>>();
let num_chunks = value_chunks.len();
for (i_chunk, value) in value_chunks.into_iter().enumerate() {
let last = i_chunk + 1 == num_chunks;
let operation = Operation::Append(KeyValueAppend {
key: full_key.clone(),
value,
last,
});
statements = vec![Statement {
operation: Some(operation),
}];
self.submit_statements(mem::take(&mut statements)).await?;
}
} else {
// The operation is small enough, it is just that we have many so we need to split.
let statement = self.get_statement(operation);
statements.push(statement);
chunk_size = operation_size;
}
}
}
self.submit_statements(mem::take(&mut statements)).await
}
async fn clear_journal(&self) -> Result<(), StorageServiceStoreError> {
Ok(())
}
}
impl StorageServiceStoreInternal {
/// Obtains the semaphore lock on the database if needed.
async fn acquire(&self) -> Option<SemaphoreGuard<'_>> {
match &self.semaphore {
None => None,
Some(count) => Some(count.acquire().await),
}
}
async fn submit_statements(
&self,
statements: Vec<Statement>,
) -> Result<(), StorageServiceStoreError> {
if !statements.is_empty() {
let query = RequestWriteBatchExtended { statements };
let request = tonic::Request::new(query);
let channel = self.channel.clone();
let mut client = StorageServiceClient::new(channel);
let _guard = self.acquire().await;
let _response = client
.process_write_batch_extended(request)
.make_sync()
.await?;
}
Ok(())
}
fn get_statement(&self, operation: WriteOperation) -> Statement {
let operation = match operation {
WriteOperation::Delete { key } => {
let mut full_key = self.start_key.clone();
full_key.extend(key);
Operation::Delete(full_key)
}
WriteOperation::Put { key, value } => {
let mut full_key = self.start_key.clone();
full_key.extend(key);
Operation::Put(KeyValue {
key: full_key,
value,
})
}
WriteOperation::DeletePrefix { key_prefix } => {
let mut full_key_prefix = self.start_key.clone();
full_key_prefix.extend(key_prefix);
Operation::DeletePrefix(full_key_prefix)
}
};
Statement {
operation: Some(operation),
}
}
async fn read_single_entry(
&self,
message_index: i64,
index: i32,
) -> Result<Vec<u8>, StorageServiceStoreError> {
let channel = self.channel.clone();
let query = RequestSpecificChunk {
message_index,
index,
};
let request = tonic::Request::new(query);
let mut client = StorageServiceClient::new(channel);
let response = client.process_specific_chunk(request).make_sync().await?;
let response = response.into_inner();
let ReplySpecificChunk { chunk } = response;
Ok(chunk)
}
async fn read_entries<S: DeserializeOwned>(
&self,
message_index: i64,
num_chunks: i32,
) -> Result<S, StorageServiceStoreError> {
let mut handles = Vec::new();
for index in 0..num_chunks {
let handle = self.read_single_entry(message_index, index);
handles.push(handle);
}
let mut value = Vec::new();
for chunk in join_all(handles).await {
let chunk = chunk?;
value.extend(chunk);
}
Ok(bcs::from_bytes(&value)?)
}
}
impl KeyValueDatabase for StorageServiceDatabaseInternal {
type Config = StorageServiceStoreInternalConfig;
type Store = StorageServiceStoreInternal;
fn get_name() -> String {
"service store".to_string()
}
async fn connect(
config: &Self::Config,
namespace: &str,
) -> Result<Self, StorageServiceStoreError> {
let semaphore = config
.max_concurrent_queries
.map(|n| Arc::new(Semaphore::new(n)));
let namespace = bcs::to_bytes(namespace)?;
let max_stream_queries = config.max_stream_queries;
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let channel = endpoint.connect_lazy();
Ok(Self {
channel,
semaphore,
max_stream_queries,
namespace,
})
}
fn open_shared(&self, root_key: &[u8]) -> Result<Self::Store, StorageServiceStoreError> {
let channel = self.channel.clone();
let semaphore = self.semaphore.clone();
let max_stream_queries = self.max_stream_queries;
let mut start_key = vec![KeyPrefix::Key as u8];
start_key.extend(&self.namespace);
start_key.extend(bcs::to_bytes(root_key)?);
let prefix_len = self.namespace.len() + 1;
Ok(StorageServiceStoreInternal {
channel,
semaphore,
max_stream_queries,
prefix_len,
start_key,
root_key_written: Arc::new(AtomicBool::new(false)),
})
}
fn open_exclusive(&self, root_key: &[u8]) -> Result<Self::Store, Self::Error> {
self.open_shared(root_key)
}
async fn list_all(config: &Self::Config) -> Result<Vec<String>, StorageServiceStoreError> {
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let mut client = StorageServiceClient::connect(endpoint).make_sync().await?;
let response = client.process_list_all(()).make_sync().await?;
let response = response.into_inner();
let ReplyListAll { namespaces } = response;
let namespaces = namespaces
.into_iter()
.map(|x| bcs::from_bytes(&x))
.collect::<Result<_, _>>()?;
Ok(namespaces)
}
async fn list_root_keys(&self) -> Result<Vec<Vec<u8>>, StorageServiceStoreError> {
let query = RequestListRootKeys {
namespace: self.namespace.clone(),
};
let request = tonic::Request::new(query);
let mut client = StorageServiceClient::new(self.channel.clone());
let response = client.process_list_root_keys(request).make_sync().await?;
let response = response.into_inner();
let ReplyListRootKeys { root_keys } = response;
Ok(root_keys)
}
async fn delete_all(config: &Self::Config) -> Result<(), StorageServiceStoreError> {
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let mut client = StorageServiceClient::connect(endpoint).make_sync().await?;
let _response = client.process_delete_all(()).make_sync().await?;
Ok(())
}
async fn exists(
config: &Self::Config,
namespace: &str,
) -> Result<bool, StorageServiceStoreError> {
let namespace = bcs::to_bytes(namespace)?;
let query = RequestExistsNamespace { namespace };
let request = tonic::Request::new(query);
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let mut client = StorageServiceClient::connect(endpoint).make_sync().await?;
let response = client.process_exists_namespace(request).make_sync().await?;
let response = response.into_inner();
let ReplyExistsNamespace { exists } = response;
Ok(exists)
}
async fn create(
config: &Self::Config,
namespace: &str,
) -> Result<(), StorageServiceStoreError> {
if StorageServiceDatabaseInternal::exists(config, namespace).await? {
return Err(StorageServiceStoreError::StoreAlreadyExists);
}
let namespace = bcs::to_bytes(namespace)?;
let query = RequestCreateNamespace { namespace };
let request = tonic::Request::new(query);
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let mut client = StorageServiceClient::connect(endpoint).make_sync().await?;
let _response = client.process_create_namespace(request).make_sync().await?;
Ok(())
}
async fn delete(
config: &Self::Config,
namespace: &str,
) -> Result<(), StorageServiceStoreError> {
let namespace = bcs::to_bytes(namespace)?;
let query = RequestDeleteNamespace { namespace };
let request = tonic::Request::new(query);
let endpoint = config.http_address();
let endpoint = Endpoint::from_shared(endpoint)?;
let mut client = StorageServiceClient::connect(endpoint).make_sync().await?;
let _response = client.process_delete_namespace(request).make_sync().await?;
Ok(())
}
}
#[cfg(with_testing)]
impl TestKeyValueDatabase for StorageServiceDatabaseInternal {
async fn new_test_config() -> Result<StorageServiceStoreInternalConfig, StorageServiceStoreError>
{
let endpoint = storage_service_test_endpoint()?;
service_config_from_endpoint(&endpoint)
}
}
/// Creates a `StorageServiceStoreConfig` from an endpoint.
pub fn service_config_from_endpoint(
endpoint: &str,
) -> Result<StorageServiceStoreInternalConfig, StorageServiceStoreError> {
Ok(StorageServiceStoreInternalConfig {
endpoint: endpoint.to_string(),
max_concurrent_queries: None,
max_stream_queries: 100,
})
}
/// Checks that endpoint is truly absent.
pub async fn storage_service_check_absence(
endpoint: &str,
) -> Result<bool, StorageServiceStoreError> {
let endpoint = Endpoint::from_shared(endpoint.to_string())?;
let result = StorageServiceClient::connect(endpoint).await;
Ok(result.is_err())
}
/// Checks whether an endpoint is valid or not.
pub async fn storage_service_check_validity(
endpoint: &str,
) -> Result<(), StorageServiceStoreError> {
let config = service_config_from_endpoint(endpoint).unwrap();
let namespace = "namespace";
let database = StorageServiceDatabaseInternal::connect(&config, namespace).await?;
let store = database.open_shared(&[])?;
let _value = store.read_value_bytes(&[42]).await?;
Ok(())
}
/// The service database client with metrics
#[cfg(with_metrics)]
pub type StorageServiceDatabase =
MeteredDatabase<LruCachingDatabase<MeteredDatabase<StorageServiceDatabaseInternal>>>;
/// The service database client without metrics
#[cfg(not(with_metrics))]
pub type StorageServiceDatabase = LruCachingDatabase<StorageServiceDatabaseInternal>;
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/src/child.rs | linera-storage-service/src/child.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use anyhow::{bail, Result};
use linera_base::{command::CommandExt, time::Duration};
use tokio::process::{Child, Command};
use crate::client::{storage_service_check_absence, storage_service_check_validity};
/// Configuration for a storage service running as a child process
pub struct StorageService {
endpoint: String,
binary: String,
}
/// A storage service running as a child process.
///
/// The guard preserves the child from destruction and destroys it when
/// it drops out of scope.
pub struct StorageServiceGuard {
_child: Child,
}
impl StorageService {
/// Creates a new `StorageServiceChild`
pub fn new(endpoint: &str, binary: String) -> Self {
Self {
endpoint: endpoint.to_string(),
binary,
}
}
fn command(&self) -> Command {
let mut command = Command::new(&self.binary);
command.args(["memory", "--endpoint", &self.endpoint]);
command.kill_on_drop(true);
command
}
/// Waits for the absence of the endpoint. If a child is terminated
/// then it might take time to wait for its absence.
async fn wait_for_absence(&self) -> Result<()> {
for i in 1..10 {
if storage_service_check_absence(&self.endpoint).await? {
return Ok(());
}
linera_base::time::timer::sleep(Duration::from_secs(i)).await;
}
bail!("Failed to start child server");
}
pub async fn run(&self) -> Result<StorageServiceGuard> {
self.wait_for_absence().await?;
let mut command = self.command();
let _child = command.spawn_into()?;
let guard = StorageServiceGuard { _child };
// We iterate until the child is spawned and can be accessed.
// We add an additional waiting period to avoid problems.
for i in 1..10 {
let result = storage_service_check_validity(&self.endpoint).await;
if result.is_ok() {
return Ok(guard);
}
linera_base::time::timer::sleep(Duration::from_secs(i)).await;
}
bail!("Failed to start child server");
}
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/src/server.rs | linera-storage-service/src/server.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::{collections::BTreeMap, sync::Arc};
use async_lock::RwLock;
use linera_storage_service::common::{KeyPrefix, MAX_PAYLOAD_SIZE};
use linera_views::{
batch::Batch,
memory::{MemoryDatabase, MemoryStoreConfig},
store::{KeyValueDatabase, ReadableKeyValueStore, WritableKeyValueStore},
};
#[cfg(with_rocksdb)]
use linera_views::{
lru_prefix_cache::StorageCacheConfig,
rocks_db::{
PathWithGuard, RocksDbDatabase, RocksDbSpawnMode, RocksDbStoreConfig,
RocksDbStoreInternalConfig,
},
};
use serde::Serialize;
use tonic::{transport::Server, Request, Response, Status};
use tracing::{info, instrument};
use tracing_subscriber::fmt::format::FmtSpan;
use crate::key_value_store::{
statement::Operation,
storage_service_server::{StorageService, StorageServiceServer},
KeyValue, OptValue, ReplyContainsKey, ReplyContainsKeys, ReplyExistsNamespace,
ReplyFindKeyValuesByPrefix, ReplyFindKeysByPrefix, ReplyListAll, ReplyListRootKeys,
ReplyReadMultiValues, ReplyReadValue, ReplySpecificChunk, RequestContainsKey,
RequestContainsKeys, RequestCreateNamespace, RequestDeleteNamespace, RequestExistsNamespace,
RequestFindKeyValuesByPrefix, RequestFindKeysByPrefix, RequestListRootKeys,
RequestReadMultiValues, RequestReadValue, RequestSpecificChunk, RequestWriteBatchExtended,
};
pub mod key_value_store {
tonic::include_proto!("key_value_store.v1");
}
enum LocalStore {
Memory(<MemoryDatabase as KeyValueDatabase>::Store),
/// The RocksDB key value store
#[cfg(with_rocksdb)]
RocksDb(<RocksDbDatabase as KeyValueDatabase>::Store),
}
#[derive(Default)]
struct BigRead {
num_processed_chunks: usize,
chunks: Vec<Vec<u8>>,
}
#[derive(Default)]
struct PendingBigReads {
index: i64,
big_reads: BTreeMap<i64, BigRead>,
}
struct StorageServer {
store: LocalStore,
pending_big_puts: Arc<RwLock<BTreeMap<Vec<u8>, Vec<u8>>>>,
pending_big_reads: Arc<RwLock<PendingBigReads>>,
}
impl StorageServer {
pub async fn read_value_bytes(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Status> {
match &self.store {
LocalStore::Memory(store) => store
.read_value_bytes(key)
.await
.map_err(|e| Status::unknown(format!("Memory error {:?} at read_value_bytes", e))),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store
.read_value_bytes(key)
.await
.map_err(|e| Status::unknown(format!("RocksDB error {:?} at read_value_bytes", e))),
}
}
pub async fn contains_key(&self, key: &[u8]) -> Result<bool, Status> {
match &self.store {
LocalStore::Memory(store) => store
.contains_key(key)
.await
.map_err(|e| Status::unknown(format!("Memory error {:?} at contains_key", e))),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store
.contains_key(key)
.await
.map_err(|e| Status::unknown(format!("RocksDB error {:?} at contains_key", e))),
}
}
pub async fn contains_keys(&self, keys: &[Vec<u8>]) -> Result<Vec<bool>, Status> {
match &self.store {
LocalStore::Memory(store) => store
.contains_keys(keys)
.await
.map_err(|e| Status::unknown(format!("Memory error {:?} at contains_keys", e))),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store
.contains_keys(keys)
.await
.map_err(|e| Status::unknown(format!("RocksDB error {:?} at contains_keys", e))),
}
}
pub async fn read_multi_values_bytes(
&self,
keys: &[Vec<u8>],
) -> Result<Vec<Option<Vec<u8>>>, Status> {
match &self.store {
LocalStore::Memory(store) => store.read_multi_values_bytes(keys).await.map_err(|e| {
Status::unknown(format!("Memory error {:?} at read_multi_values_bytes", e))
}),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store.read_multi_values_bytes(keys).await.map_err(|e| {
Status::unknown(format!("RocksDB error {:?} at read_multi_values_bytes", e))
}),
}
}
pub async fn find_keys_by_prefix(&self, key_prefix: &[u8]) -> Result<Vec<Vec<u8>>, Status> {
match &self.store {
LocalStore::Memory(store) => store.find_keys_by_prefix(key_prefix).await.map_err(|e| {
Status::unknown(format!("Memory error {:?} at find_keys_by_prefix", e))
}),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => {
store.find_keys_by_prefix(key_prefix).await.map_err(|e| {
Status::unknown(format!("RocksDB error {:?} at find_keys_by_prefix", e))
})
}
}
}
pub async fn find_key_values_by_prefix(
&self,
key_prefix: &[u8],
) -> Result<Vec<(Vec<u8>, Vec<u8>)>, Status> {
match &self.store {
LocalStore::Memory(store) => {
store
.find_key_values_by_prefix(key_prefix)
.await
.map_err(|e| {
Status::unknown(format!(
"Memory error {:?} at find_key_values_by_prefix",
e
))
})
}
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store
.find_key_values_by_prefix(key_prefix)
.await
.map_err(|e| {
Status::unknown(format!(
"RocksDB error {:?} at find_key_values_by_prefix",
e
))
}),
}
}
pub async fn write_batch(&self, batch: Batch) -> Result<(), Status> {
match &self.store {
LocalStore::Memory(store) => store
.write_batch(batch)
.await
.map_err(|e| Status::unknown(format!("Memory error {:?} at write_batch", e))),
#[cfg(with_rocksdb)]
LocalStore::RocksDb(store) => store
.write_batch(batch)
.await
.map_err(|e| Status::unknown(format!("RocksDB error {:?} at write_batch", e))),
}
}
pub async fn list_all(&self) -> Result<Vec<Vec<u8>>, Status> {
self.find_keys_by_prefix(&[KeyPrefix::Namespace as u8])
.await
}
pub async fn list_root_keys(&self, namespace: &[u8]) -> Result<Vec<Vec<u8>>, Status> {
let mut full_key = vec![KeyPrefix::RootKey as u8];
full_key.extend(namespace);
let bcs_root_keys = self.find_keys_by_prefix(&full_key).await?;
let mut root_keys = Vec::new();
for bcs_root_key in bcs_root_keys {
let root_key = bcs::from_bytes::<Vec<u8>>(&bcs_root_key)
.map_err(|e| Status::unknown(format!("Bcs error {e:?} at list_root_keys")))?;
root_keys.push(root_key);
}
Ok(root_keys)
}
pub async fn delete_all(&self) -> Result<(), Status> {
let mut batch = Batch::new();
batch.delete_key_prefix(vec![KeyPrefix::Key as u8]);
batch.delete_key_prefix(vec![KeyPrefix::Namespace as u8]);
batch.delete_key_prefix(vec![KeyPrefix::RootKey as u8]);
self.write_batch(batch).await
}
pub async fn exists_namespace(&self, namespace: &[u8]) -> Result<bool, Status> {
let mut full_key = vec![KeyPrefix::Namespace as u8];
full_key.extend(namespace);
self.contains_key(&full_key).await
}
pub async fn create_namespace(&self, namespace: &[u8]) -> Result<(), Status> {
let mut full_key = vec![KeyPrefix::Namespace as u8];
full_key.extend(namespace);
let mut batch = Batch::new();
batch.put_key_value_bytes(full_key, vec![]);
self.write_batch(batch).await
}
pub async fn delete_namespace(&self, namespace: &[u8]) -> Result<(), Status> {
let mut batch = Batch::new();
let mut full_key = vec![KeyPrefix::Namespace as u8];
full_key.extend(namespace);
batch.delete_key(full_key);
let mut key_prefix = vec![KeyPrefix::Key as u8];
key_prefix.extend(namespace);
batch.delete_key_prefix(key_prefix);
let mut key_prefix = vec![KeyPrefix::RootKey as u8];
key_prefix.extend(namespace);
batch.delete_key_prefix(key_prefix);
self.write_batch(batch).await
}
pub async fn insert_pending_read<S: Serialize>(&self, value: S) -> (i64, i32) {
let value = bcs::to_bytes(&value).unwrap();
let chunks = value
.chunks(MAX_PAYLOAD_SIZE)
.map(|x| x.to_vec())
.collect::<Vec<_>>();
let num_chunks = chunks.len() as i32;
let mut pending_big_reads = self.pending_big_reads.write().await;
let message_index = pending_big_reads.index;
pending_big_reads.index += 1;
let big_read = BigRead {
num_processed_chunks: 0,
chunks,
};
pending_big_reads.big_reads.insert(message_index, big_read);
(message_index, num_chunks)
}
}
#[derive(clap::Parser)]
#[command(
name = "linera-storage-server",
version = linera_version::VersionInfo::default_clap_str(),
about = "A server providing storage service",
)]
enum StorageServerOptions {
#[command(name = "memory")]
Memory {
/// The storage namespace.
#[arg(long, default_value = "linera_storage_service")]
namespace: String,
/// The storage service address.
#[arg(long)]
endpoint: String,
/// Preferred buffer size for async streams.
#[arg(long, default_value = "10")]
max_stream_queries: usize,
},
#[cfg(with_rocksdb)]
#[command(name = "rocksdb")]
RocksDb {
/// The storage namespace.
#[arg(long, default_value = "linera_storage_service")]
namespace: String,
/// The storage service address.
#[arg(long)]
endpoint: String,
/// Path to the rocksdb database.
#[arg(long)]
path: String,
/// Preferred buffer size for async streams.
#[arg(long, default_value = "10")]
max_stream_queries: usize,
/// The maximum size of the cache, in bytes (keys size + value sizes)
#[arg(long, default_value = "10000000")]
max_cache_size: usize,
/// The maximum size of a value entry, in bytes
#[arg(long, default_value = "1000000")]
max_value_entry_size: usize,
/// The maximum size of a find-keys entry, in bytes
#[arg(long, default_value = "1000000")]
max_find_keys_entry_size: usize,
/// The maximum size of a find-key-values entry, in bytes
#[arg(long, default_value = "1000000")]
max_find_key_values_entry_size: usize,
/// The maximum number of entries in the cache.
#[arg(long, default_value = "1000")]
max_cache_entries: usize,
/// The maximum value size of the cache, in bytes
#[arg(long, default_value = "10000000")]
max_cache_value_size: usize,
/// The maximum find_keys_by_prefix size of the cache, in bytes
#[arg(long, default_value = "10000000")]
max_cache_find_keys_size: usize,
/// The maximum find_key_values_by_prefix size of the cache, in bytes
#[arg(long, default_value = "10000000")]
max_cache_find_key_values_size: usize,
},
}
#[tonic::async_trait]
impl StorageService for StorageServer {
#[instrument(target = "store_server", skip_all, err, fields(key_len = ?request.get_ref().key.len()))]
async fn process_read_value(
&self,
request: Request<RequestReadValue>,
) -> Result<Response<ReplyReadValue>, Status> {
let request = request.into_inner();
let RequestReadValue { key } = request;
let value = self.read_value_bytes(&key).await?;
let size = match &value {
None => 0,
Some(value) => value.len(),
};
let response = if size < MAX_PAYLOAD_SIZE {
ReplyReadValue {
value,
message_index: 0,
num_chunks: 0,
}
} else {
let (message_index, num_chunks) = self.insert_pending_read(value).await;
ReplyReadValue {
value: None,
message_index,
num_chunks,
}
};
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(key_len = ?request.get_ref().key.len()))]
async fn process_contains_key(
&self,
request: Request<RequestContainsKey>,
) -> Result<Response<ReplyContainsKey>, Status> {
let request = request.into_inner();
let RequestContainsKey { key } = request;
let test = self.contains_key(&key).await?;
let response = ReplyContainsKey { test };
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(key_len = ?request.get_ref().keys.len()))]
async fn process_contains_keys(
&self,
request: Request<RequestContainsKeys>,
) -> Result<Response<ReplyContainsKeys>, Status> {
let request = request.into_inner();
let RequestContainsKeys { keys } = request;
let tests = self.contains_keys(&keys).await?;
let response = ReplyContainsKeys { tests };
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(n_keys = ?request.get_ref().keys.len()))]
async fn process_read_multi_values(
&self,
request: Request<RequestReadMultiValues>,
) -> Result<Response<ReplyReadMultiValues>, Status> {
let request = request.into_inner();
let RequestReadMultiValues { keys } = request;
let values = self.read_multi_values_bytes(&keys).await?;
let size = values
.iter()
.map(|x| match x {
None => 0,
Some(entry) => entry.len(),
})
.sum::<usize>();
let response = if size < MAX_PAYLOAD_SIZE {
let values = values
.into_iter()
.map(|value| OptValue { value })
.collect::<Vec<_>>();
ReplyReadMultiValues {
values,
message_index: 0,
num_chunks: 0,
}
} else {
let (message_index, num_chunks) = self.insert_pending_read(values).await;
ReplyReadMultiValues {
values: Vec::default(),
message_index,
num_chunks,
}
};
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(key_prefix_len = ?request.get_ref().key_prefix.len()))]
async fn process_find_keys_by_prefix(
&self,
request: Request<RequestFindKeysByPrefix>,
) -> Result<Response<ReplyFindKeysByPrefix>, Status> {
let request = request.into_inner();
let RequestFindKeysByPrefix { key_prefix } = request;
let keys = self.find_keys_by_prefix(&key_prefix).await?;
let size = keys.iter().map(|x| x.len()).sum::<usize>();
let response = if size < MAX_PAYLOAD_SIZE {
ReplyFindKeysByPrefix {
keys,
message_index: 0,
num_chunks: 0,
}
} else {
let (message_index, num_chunks) = self.insert_pending_read(keys).await;
ReplyFindKeysByPrefix {
keys: Vec::default(),
message_index,
num_chunks,
}
};
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(key_prefix_len = ?request.get_ref().key_prefix.len()))]
async fn process_find_key_values_by_prefix(
&self,
request: Request<RequestFindKeyValuesByPrefix>,
) -> Result<Response<ReplyFindKeyValuesByPrefix>, Status> {
let request = request.into_inner();
let RequestFindKeyValuesByPrefix { key_prefix } = request;
let key_values = self.find_key_values_by_prefix(&key_prefix).await?;
let size = key_values
.iter()
.map(|x| x.0.len() + x.1.len())
.sum::<usize>();
let response = if size < MAX_PAYLOAD_SIZE {
let key_values = key_values
.into_iter()
.map(|x| KeyValue {
key: x.0,
value: x.1,
})
.collect::<Vec<_>>();
ReplyFindKeyValuesByPrefix {
key_values,
message_index: 0,
num_chunks: 0,
}
} else {
let (message_index, num_chunks) = self.insert_pending_read(key_values).await;
ReplyFindKeyValuesByPrefix {
key_values: Vec::default(),
message_index,
num_chunks,
}
};
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(n_statements = ?request.get_ref().statements.len()))]
async fn process_write_batch_extended(
&self,
request: Request<RequestWriteBatchExtended>,
) -> Result<Response<()>, Status> {
let request = request.into_inner();
let RequestWriteBatchExtended { statements } = request;
let mut batch = Batch::default();
for statement in statements {
match statement.operation.unwrap() {
Operation::Delete(key) => {
batch.delete_key(key);
}
Operation::Put(key_value) => {
batch.put_key_value_bytes(key_value.key, key_value.value);
}
Operation::Append(key_value_append) => {
let mut pending_big_puts = self.pending_big_puts.write().await;
match pending_big_puts.get_mut(&key_value_append.key) {
None => {
pending_big_puts
.insert(key_value_append.key.clone(), key_value_append.value);
}
Some(value) => {
value.extend(key_value_append.value);
}
}
if key_value_append.last {
let value = pending_big_puts.remove(&key_value_append.key).unwrap();
batch.put_key_value_bytes(key_value_append.key, value);
}
}
Operation::DeletePrefix(key_prefix) => {
batch.delete_key_prefix(key_prefix);
}
}
}
if !batch.is_empty() {
self.write_batch(batch).await?;
}
Ok(Response::new(()))
}
#[instrument(target = "store_server", skip_all, err, fields(message_index = ?request.get_ref().message_index, index = ?request.get_ref().index))]
async fn process_specific_chunk(
&self,
request: Request<RequestSpecificChunk>,
) -> Result<Response<ReplySpecificChunk>, Status> {
let request = request.into_inner();
let RequestSpecificChunk {
message_index,
index,
} = request;
let mut pending_big_reads = self.pending_big_reads.write().await;
let Some(entry) = pending_big_reads.big_reads.get_mut(&message_index) else {
return Err(Status::not_found("process_specific_chunk"));
};
let index = index as usize;
let chunk = entry.chunks[index].clone();
entry.num_processed_chunks += 1;
if entry.chunks.len() == entry.num_processed_chunks {
pending_big_reads.big_reads.remove(&message_index);
}
let response = ReplySpecificChunk { chunk };
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(namespace = ?request.get_ref().namespace))]
async fn process_create_namespace(
&self,
request: Request<RequestCreateNamespace>,
) -> Result<Response<()>, Status> {
let request = request.into_inner();
let RequestCreateNamespace { namespace } = request;
self.create_namespace(&namespace).await?;
Ok(Response::new(()))
}
#[instrument(target = "store_server", skip_all, err, fields(namespace = ?request.get_ref().namespace))]
async fn process_exists_namespace(
&self,
request: Request<RequestExistsNamespace>,
) -> Result<Response<ReplyExistsNamespace>, Status> {
let request = request.into_inner();
let RequestExistsNamespace { namespace } = request;
let exists = self.exists_namespace(&namespace).await?;
let response = ReplyExistsNamespace { exists };
Ok(Response::new(response))
}
#[instrument(target = "store_server", skip_all, err, fields(namespace = ?request.get_ref().namespace))]
async fn process_delete_namespace(
&self,
request: Request<RequestDeleteNamespace>,
) -> Result<Response<()>, Status> {
let request = request.into_inner();
let RequestDeleteNamespace { namespace } = request;
self.delete_namespace(&namespace).await?;
Ok(Response::new(()))
}
#[instrument(target = "store_server", skip_all, err, fields(list_all = "list_all"))]
async fn process_list_all(
&self,
_request: Request<()>,
) -> Result<Response<ReplyListAll>, Status> {
let namespaces = self.list_all().await?;
let response = ReplyListAll { namespaces };
Ok(Response::new(response))
}
#[instrument(
target = "store_server",
skip_all,
err,
fields(list_all = "list_root_keys")
)]
async fn process_list_root_keys(
&self,
request: Request<RequestListRootKeys>,
) -> Result<Response<ReplyListRootKeys>, Status> {
let request = request.into_inner();
let RequestListRootKeys { namespace } = request;
let root_keys = self.list_root_keys(&namespace).await?;
let response = ReplyListRootKeys { root_keys };
Ok(Response::new(response))
}
#[instrument(
target = "store_server",
skip_all,
err,
fields(delete_all = "delete_all")
)]
async fn process_delete_all(&self, _request: Request<()>) -> Result<Response<()>, Status> {
self.delete_all().await?;
Ok(Response::new(()))
}
}
#[tokio::main]
async fn main() {
let env_filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing_subscriber::filter::LevelFilter::INFO.into())
.from_env_lossy();
let internal_event_filter = {
match std::env::var_os("RUST_LOG_SPAN_EVENTS") {
Some(mut value) => {
value.make_ascii_lowercase();
let value = value
.to_str()
.expect("test-log: RUST_LOG_SPAN_EVENTS must be valid UTF-8");
value
.split(',')
.map(|filter| match filter.trim() {
"new" => FmtSpan::NEW,
"enter" => FmtSpan::ENTER,
"exit" => FmtSpan::EXIT,
"close" => FmtSpan::CLOSE,
"active" => FmtSpan::ACTIVE,
"full" => FmtSpan::FULL,
_ => panic!("test-log: RUST_LOG_SPAN_EVENTS must contain filters separated by `,`.\n\t\
For example: `active` or `new,close`\n\t\
Supported filters: new, enter, exit, close, active, full\n\t\
Got: {}", value),
})
.fold(FmtSpan::NONE, |acc, filter| filter | acc)
}
None => FmtSpan::NONE,
}
};
tracing_subscriber::fmt()
.with_span_events(internal_event_filter)
.with_writer(std::io::stderr)
.with_env_filter(env_filter)
.init();
let options = <StorageServerOptions as clap::Parser>::parse();
let (store, endpoint) = match options {
StorageServerOptions::Memory {
namespace,
endpoint,
max_stream_queries,
} => {
let config = MemoryStoreConfig {
max_stream_queries,
kill_on_drop: false,
};
let database = MemoryDatabase::maybe_create_and_connect(&config, &namespace)
.await
.unwrap();
let store = database.open_shared(&[]).unwrap();
let store = LocalStore::Memory(store);
(store, endpoint)
}
#[cfg(with_rocksdb)]
StorageServerOptions::RocksDb {
namespace,
endpoint,
path,
max_stream_queries,
max_cache_size,
max_value_entry_size,
max_find_keys_entry_size,
max_find_key_values_entry_size,
max_cache_entries,
max_cache_value_size,
max_cache_find_keys_size,
max_cache_find_key_values_size,
} => {
let path_buf = path.into();
let path_with_guard = PathWithGuard::new(path_buf);
let spawn_mode = RocksDbSpawnMode::get_spawn_mode_from_runtime();
let inner_config = RocksDbStoreInternalConfig {
spawn_mode,
path_with_guard,
max_stream_queries,
};
let storage_cache_config = StorageCacheConfig {
max_cache_size,
max_value_entry_size,
max_find_keys_entry_size,
max_find_key_values_entry_size,
max_cache_entries,
max_cache_value_size,
max_cache_find_keys_size,
max_cache_find_key_values_size,
};
let config = RocksDbStoreConfig {
inner_config,
storage_cache_config,
};
let database = RocksDbDatabase::maybe_create_and_connect(&config, &namespace)
.await
.expect("store");
let store = database.open_shared(&[]).expect("Failed to open store");
let store = LocalStore::RocksDb(store);
(store, endpoint)
}
};
let pending_big_puts = Arc::new(RwLock::new(BTreeMap::default()));
let pending_big_reads = Arc::new(RwLock::new(PendingBigReads::default()));
let store = StorageServer {
store,
pending_big_puts,
pending_big_reads,
};
let endpoint = endpoint.parse().unwrap();
info!("Starting linera_storage_service on endpoint={}", endpoint);
Server::builder()
.add_service(StorageServiceServer::new(store))
.serve(endpoint)
.await
.expect("a successful running of the server");
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.