#alignment of array

1 messages · Page 1 of 1 (latest)

hot scaffold
#

How would I declare an array with a specific alignment?

finite bough
#

var foo: [32]byte align(8) = undefined;

hot scaffold
#

Thanks.

finite bough
#

o7

delicate mantle
#

silly question but what does the alignment change ?

dire fable
delicate mantle
#

but why would there be a spacing between two elements of an array ?

#

and from the doc

fn noop1() align(1) void {}
fn noop4() align(4) void {}

what does it change here, why would I need this ?
(I am asking that in a curious way xD like want to understand)

dire fable
# delicate mantle but why would there be a spacing between two elements of an array ?

CPUs are often faster if e.g. the addresses of a u64 only differ in the last 3 bits. This means u64 have an alignment of 8 (if you don't change it). This means every pointer to a u8 is divisble by 8. Otherwise the CPU may need to load more values and combine them, which takes longer. This means the struct struct { a: u64, b: u32, } has a size of 8+4=12 bytes, but in an array between two such elements there has to be a spacing of 16, to keep a aligned.

There are some specifc usecases where changing the alignment is sometimes a good idea. If you receive a blob of data with no alignment and want to read a u64, you can read from this *align(1) u8, but this is, how I explained slower, than reading from a * u8.

Another very specific usecase I once had, was GPU programming. Some 3 value Vectors had be be aligned as if they had 4 values.

dire fable
wintry furnace
delicate mantle
dire fable
vast ginkgo
# finite bough `var foo: [32]byte align(8) = undefined;`

IIUC this changes the alignment of all elements of the array? Is there a way to change the alignment only of the array itself? E.g. have array of u8 aligned on a 4 byte boundary? IIUC one can specify this for a variable:

var x align(4): .....

but is there a way to specify this for a type?

autumn minnow
#

the type of &foo given var foo: [32]u8 align(8) is *align(8) [32]u8 - an 8-byte-aligned pointer to an array of 32 normally-aligned u8s

vast ginkgo
#

How would I request that each individual item of the array is aligned instead?