linera_witty/memory_layout/
layout.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Representation of the memory layout of complex types as a sequence of fundamental WIT types.
5
6use frunk::{hlist::HList, HCons, HNil};
7
8use super::{element::LayoutElement, FlatLayout};
9use crate::primitive_types::MaybeFlatType;
10
11/// Marker trait to prevent [`LayoutElement`] to be implemented for other types.
12pub trait Sealed {}
13
14/// Representation of the memory layout of complex types as a sequence of fundamental WIT types.
15pub trait Layout: Sealed + HList {
16    /// The alignment boundary required for the layout.
17    const ALIGNMENT: u32;
18
19    /// Result of flattening this layout.
20    type Flat: FlatLayout;
21
22    /// Flattens this layout into a layout consisting of native WebAssembly types.
23    ///
24    /// The resulting flat layout does not have any empty items.
25    fn flatten(self) -> Self::Flat;
26}
27
28impl Sealed for HNil {}
29impl<Head, Tail> Sealed for HCons<Head, Tail>
30where
31    Head: LayoutElement,
32    Tail: Layout,
33{
34}
35
36impl Layout for HNil {
37    const ALIGNMENT: u32 = 1;
38
39    type Flat = HNil;
40
41    fn flatten(self) -> Self::Flat {
42        HNil
43    }
44}
45
46impl<Head, Tail> Layout for HCons<Head, Tail>
47where
48    Head: LayoutElement,
49    Tail: Layout,
50{
51    const ALIGNMENT: u32 = if Head::ALIGNMENT > Tail::ALIGNMENT {
52        Head::ALIGNMENT
53    } else {
54        Tail::ALIGNMENT
55    };
56
57    type Flat = <Head::Flat as MaybeFlatType>::Flatten<Tail>;
58
59    fn flatten(self) -> Self::Flat {
60        self.head.flatten().flatten(self.tail)
61    }
62}