liveBook · Manning

Repr(align)

As explained in Embedded Software with Rust

`repr(align)` is a Rust representation attribute that raises a type's minimum alignment to a specified boundary.

Rust’s `#[repr(align(N))]` sets a type’s minimum alignment to a specified boundary, even when its fields would otherwise require less. Use it when data must begin at an aligned address, such as a cache-sensitive buffer. section 5.4.3

Alignment can help prevent buffers from straddling cache lines and is a common prerequisite for cache maintenance around DMA transfers. It does not, by itself, ensure DMA coherency: appropriate cache clean or invalidate operations are still required. For memory-mapped register overlays, avoid `#[repr(packed)]`, which can allow unaligned fields. section 5.4.3

use core::mem::{size_of, align_of};

#[repr(align(64))]
struct CacheAlignedBuffer([u8; 32]);

fn main() {
    dbg!(align_of::<CacheAlignedBuffer>()); // 64 bytes
    dbg!(size_of::<CacheAlignedBuffer>()); // 64 bytes (32 bytes payload + 32 bytes padding)
}

This example aligns a 32-byte buffer to 64 bytes and shows the resulting 32 bytes of padding. section 5.4.3

How Embedded Software with Rust covers it

How deep it goes
Defines the minimum-alignment guarantee and illustrates cache-line padding, while noting that alignment alone does not ensure DMA coherency.
Examples
Uses a 32-byte buffer aligned to 64 bytes, yielding 32 bytes of padding.
What you can do after
Apply `#[repr(align(N))]` to align buffers, while retaining required cache maintenance for DMA.
How it connects
Connects type alignment to packed layouts, memory-mapped I/O, cache lines, and DMA cache maintenance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.