#const-generics #alignment #const #layout #align

no-std elain

Set a type's minimum alignment with const generics

4 releases (2 breaking)

0.3.1 Oct 17, 2024
0.3.0 Apr 13, 2021
0.2.0 Apr 8, 2021
0.1.0 Apr 8, 2021

#144 in Rust patterns

Download history 1145/week @ 2024-07-27 1709/week @ 2024-08-03 1111/week @ 2024-08-10 838/week @ 2024-08-17 706/week @ 2024-08-24 958/week @ 2024-08-31 1611/week @ 2024-09-07 1371/week @ 2024-09-14 1906/week @ 2024-09-21 1961/week @ 2024-09-28 1423/week @ 2024-10-05 5357/week @ 2024-10-12 4380/week @ 2024-10-19 3097/week @ 2024-10-26 3783/week @ 2024-11-02 2263/week @ 2024-11-09

14,592 downloads per month
Used in 15 crates (6 directly)

MIT/Apache

17KB
166 lines

Elain

Set the minimum alignments of types using const generics, rather than #[repr(align(N))].

Basic Use

The type Align<N> is a zero-sized-type with alignment equal to N:

use elain::Align;
use core::mem::{align_of, align_of_val};

assert_eq!(align_of::<Align<1>>(), 1);
assert_eq!(align_of::<Align<2>>(), 2);
assert_eq!(align_of::<Align<4>>(), 4);

const FOO_ALIGN: usize = 8;

#[repr(C)]
struct Foo {
    _align: Align<FOO_ALIGN>,
}

let foo: Foo = Foo { _align: Align::NEW };

assert_eq!(align_of_val(&foo), 8);

Valid alignments are powers of two less-than-or-equal to 228. Supplying an invalid alignment to Align is a type error:

use elain::Align;

struct Foo(Align<3>); // Compile Error

Generic Use

Because only some integers are valid alignments, supplying the alignment of a type generically requires some extra work:

use elain::Align;

struct Foo<const N: usize> {
    _align: Align<N>,
}

To resolve this error, add a where bound like so, using the Alignment trait to check that Align<N> is valid.

use elain::{Align, Alignment};
use core::mem::align_of;

struct Foo<const MIN_ALIGNMENT: usize>
where
    Align<MIN_ALIGNMENT>: Alignment
{
    _align: Align<MIN_ALIGNMENT>,
    bar: u8,
    baz: u16,
}

assert_eq!(align_of::<Foo<1>>(), 2);
assert_eq!(align_of::<Foo<2>>(), 2);
assert_eq!(align_of::<Foo<4>>(), 4);

No runtime deps