-
Notifications
You must be signed in to change notification settings - Fork 3
Note: Type and Field Alignment
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];
}
- Home
- Introduction
- Motivation
- Features
- Tutorial
- Library
- FAQ
- General
- Interoperability
- Syntax
- Type System
- Macros and CTE
- Specification
- Introduction
- Lexical
- Common Grammar Elements
- Modules and Bundles
- Type System
- Declarations
- Expressions
- Macros
- Compile-Time Evaluation
- Memory Management
- Application Binary Interface
- Foreign Function Interface
- Unit Testing
- Documentation Comments
- Style
- Indentation
- Braces
- Spacing
- Naming