Skip to content
This repository has been archived by the owner on Jun 6, 2021. It is now read-only.

Note: Type and Field Alignment

Alex Rønne Petersen edited this page Jun 7, 2013 · 3 revisions

A plain structure like this:

pub struct Foo {
    bar : i32;
    baz : u8;
    qux : f64;
}

Is translated directly to this C struct:

struct Foo {
    int32_t bar;
    uint8_t baz;
    float64_t qux;
};

That is, it uses the native alignment rules of the target.

Fields in structures can be given a particular alignment:

pub struct Bar {
    pub baz : u8;

    @[align(8)]
    pub foo : i32;
}

This compiles to:

struct Bar {
    int32_t foo __attribute__((aligned(8)));
};

An alignment value of zero means "use preferred alignment" (i.e. the same as not specifying an align attribute). An alignment value of one means "pack tightly against previous field". Note that an alignment value must be a power of two.

Tuples are treated as structures when being lowered, so they simply get default structure alignment rules.

Fields in a union can also have alignment attributes:

pub union Baz {
    A {
        pub x : i32;
    }
    B {
        pub f : f32;

        @[align(16)]
        pub b : bool;
    }
}

Finally, types themselves can have an alignment attribute. This is useful to ensure that they are always stored on a particular boundary, regardless of whether they are part of structures, unions, arrays, are on the stack, etc.

// A 32-bit signed integer, aligned on a 16-byte boundary.
@[align(16)]
pub type i32_a16 = i32;

// A set of three 4-dimensional vectors aligned on a 16-byte boundary.
@[align(16)]
pub struct Qux {
    pub vec1 : [f32 * 4];
    pub vec2 : [f32 * 4];
    pub vec3 : [f32 * 4];
}
Clone this wiki locally