linera_witty/type_traits/
mod.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Traits used to allow complex types to be sent and received between hosts and guests using WIT.
5
6mod implementations;
7mod register_wit_types;
8
9use std::borrow::Cow;
10
11pub use self::register_wit_types::RegisterWitTypes;
12use crate::{
13    GuestPointer, InstanceWithMemory, Layout, Memory, Runtime, RuntimeError, RuntimeMemory,
14};
15
16/// A type that is representable by fundamental WIT types.
17pub trait WitType {
18    /// The size of the type when laid out in memory.
19    const SIZE: u32;
20
21    /// The layout of the type as fundamental types.
22    type Layout: Layout;
23
24    /// Other [`WitType`]s that this type depends on.
25    type Dependencies: RegisterWitTypes;
26
27    /// Generates the WIT type name for this type.
28    fn wit_type_name() -> Cow<'static, str>;
29
30    /// Generates the WIT type declaration for this type.
31    fn wit_type_declaration() -> Cow<'static, str>;
32}
33
34/// A type that can be loaded from a guest Wasm module.
35pub trait WitLoad: WitType + Sized {
36    /// Loads an instance of the type from the `location` in the guest's `memory`.
37    fn load<Instance>(
38        memory: &Memory<'_, Instance>,
39        location: GuestPointer,
40    ) -> Result<Self, RuntimeError>
41    where
42        Instance: InstanceWithMemory,
43        <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
44
45    /// Lifts an instance of the type from the `flat_layout` representation.
46    ///
47    /// May read from the `memory` if the type has references to heap data.
48    fn lift_from<Instance>(
49        flat_layout: <Self::Layout as Layout>::Flat,
50        memory: &Memory<'_, Instance>,
51    ) -> Result<Self, RuntimeError>
52    where
53        Instance: InstanceWithMemory,
54        <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
55}
56
57/// A type that can be stored in a guest Wasm module.
58pub trait WitStore: WitType {
59    /// Stores the type at the `location` in the guest's `memory`.
60    fn store<Instance>(
61        &self,
62        memory: &mut Memory<'_, Instance>,
63        location: GuestPointer,
64    ) -> Result<(), RuntimeError>
65    where
66        Instance: InstanceWithMemory,
67        <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
68
69    /// Lowers the type into its flat layout representation.
70    ///
71    /// May write to the `memory` if the type has references to heap data or if it doesn't fit in
72    /// the maximum flat layout size.
73    fn lower<Instance>(
74        &self,
75        memory: &mut Memory<'_, Instance>,
76    ) -> Result<<Self::Layout as Layout>::Flat, RuntimeError>
77    where
78        Instance: InstanceWithMemory,
79        <Instance::Runtime as Runtime>::Memory: RuntimeMemory<Instance>;
80}