Skip to main content

zero_copy_layout

Macro zero_copy_layout 

Source
macro_rules! zero_copy_layout {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident, discriminator = $disc:literal, version = $ver:literal {
            $( $(#[$fmeta:meta])* $field:ident : $fty:ident = $fsize:expr ),+ $(,)?
        }
    ) => { ... };
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident, discriminator = $disc:literal, version = $ver:literal, extends = $parent:ty {
            $( $(#[$fmeta:meta])* $field:ident : $fty:ident = $fsize:expr ),+ $(,)?
        }
    ) => { ... };
}
Expand description

Declare a zero-copy account layout with typed field accessors.

Each field specifies name: Type = byte_size. The macro generates a #[repr(C)] struct along with Pod, FixedLayout, overlay methods, and a deterministic LAYOUT_ID computed via SHA-256.

zero_copy_layout! {
    pub struct Pool, discriminator = 3, version = 1 {
        header:     AccountHeader = 16,
        authority:  Address       = 32,
        reserve_a:  u64           = 8,
        reserve_b:  u64           = 8,
    }
}

§Layout Inheritance

Use extends = ParentType to assert that a new version is a byte-compatible superset of an older version. The macro verifies at compile time that the child has the same discriminator and is at least as large as the parent:

zero_copy_layout! {
    pub struct PoolV2, discriminator = 3, version = 2, extends = Pool {
        header:     AccountHeader = 16,
        authority:  Address       = 32,
        reserve_a:  u64           = 8,
        reserve_b:  u64           = 8,
        fee_bps:    u16           = 2,
    }
}