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

no-std elain

Set a type's minimum alignment with const generics

3 releases (breaking)

0.3.0 Apr 13, 2021
0.2.0 Apr 8, 2021
0.1.0 Apr 8, 2021

#839 in Rust patterns

Download history 165/week @ 2024-01-04 168/week @ 2024-01-11 512/week @ 2024-01-18 285/week @ 2024-01-25 691/week @ 2024-02-01 3219/week @ 2024-02-08 3822/week @ 2024-02-15 6715/week @ 2024-02-22 7311/week @ 2024-02-29 2326/week @ 2024-03-07 1242/week @ 2024-03-14 1571/week @ 2024-03-21 923/week @ 2024-03-28 1872/week @ 2024-04-04 1834/week @ 2024-04-11 2801/week @ 2024-04-18

7,647 downloads per month
Used in 15 crates (7 directly)

MIT/Apache

15KB
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