Allocate * mut f32 on multiple of 4kb

I am allocating memory for N = k * 1024 f32's. This is guaranteed to be a multiple of 1024 * 4 bytes = 4kb.

Question: is there a way to force Rust to ensure that the start of the array is a multiple of 4kb?

You can create a newtype like this:

struct FloatChunk<const K: usize>([[f32; 1024]; K]);

pub fn foo() -> Box<FloatChunk<16>> {
    Box::new(FloatChunk([[0.0; 1024]; 16]))

Actually, wait, what if I don't know K until runtime? Is Vec<FloatChunk<1>> guaranteed to be 4096-byte aligned ?

If you only know K at runtime, then declare FloatChunk simply as:

struct FloatChunk([f32; 1024]);

which will still be guaranteed to be 4k-aligned, and then create a Vec<FloatChunk>.


Alternatively, you can use std::alloc for this and specify the required alignment in the Layout configuration.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.