Skip to content

Instantly share code, notes, and snippets.

@jdf-id-au
Created February 5, 2025 11:28
Show Gist options
  • Select an option

  • Save jdf-id-au/641f94d13d80df57163399461c574894 to your computer and use it in GitHub Desktop.

Select an option

Save jdf-id-au/641f94d13d80df57163399461c574894 to your computer and use it in GitHub Desktop.
Alignment calculation for arena
// Trying to understand the padding calculation from https://nullprogram.com/blog/2023/09/27/
byte *alloc(arena *a, size objsize, size align, size count) {
size avail = a->end - a->beg;
/*
Padding is how far the next aligned address is beyond the beginning of the arena.
(The "beginning" of the arena advances as data is added, and is really the beginning of the remaining avilable space.)
Use wrapping unsigned integer negation of the beginning address to measure what's left rather than what's in use.
Calculate how far this address is beyond the previous aligned address using modulo:
addr % align == addr & (align - 1) // because align is a power of 2 (i.e. > 0)
Example with u4 address and 4 byte alignment:
0x 0 4 8 c
beg ---------->..... 0xb 0b1011
-beg .....<---------- 0x5 0b0101
align | | | | 4 0b0100
align-1 0b0011
padding x 1 0b0001 == -beg & (align-1)
giving ----------->.... 0xc = 0xb + 1
*/
size padding = -(uptr)a->beg & (align - 1);
if (count > (avail - padding)/objsize) oom();
size total = count * objsize;
byte *p = a->beg + padding;
a->beg += padding + total;
for (size i = 0; i < total; i++) p[i] = 0;
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment