So I’m writing data structure that can store data types in []u8
’s as raw bytes. But I’m wondering how to handle alignment.
My idea is to group types by alignment and basically store them in a hashmap where the key is the alignment to reduce fragmentation. This means the type that stores each group can’t be generic because then it can’t go into a hashmap.
Since i have access to the type when i add data to each group i can use alignedAlloc
but i cant free that memory later without getting an error: Allocation alignment 4 does not match free alignment 1
(because i no longer have access to the type in the deinit
function).
I don’t know if it’s reasonable to maybe just store the []u8
as []align(8) u8
or []align(16) u8
(which seems to be the biggest alignment on my platform).
Right now i just do it like this:
const mem = try allocator.alloc(u8, new_size);
And later i just cast it back
const a1: *A = @alignCast(@ptrCast(the_slice));
When i think about it i don’t even know why this works. Why does @alignCast
not assert? Is it because the allocator always return a block thas is the biggest supported alignment an therefore its safe to cast it to a smaller alignment?
I don’t know what the correct way is to go about this and would be thankful for any help you can provide.