So we've got our struct. Imagine augmenting it with a bool called mark
:
struct Foo {
bool mark;
int data_size;
char[] data;
}
So we can walk through the pool of Foo
s that begins at buffer
and ends at end
:
while (iter < end) {
Foo *block = (Foo *)iter;
printf(“I’ve got a block of size %d. She is %s. She encodes: %s.”,
block->size, block->mark ? "marked" : "not marked", block->data);
iter += sizeof(struct Foo) + block->size;
}
Imagine I wanted to compact this buffer, removing all the structs which have mark == false
...
So compaction basically looks like:
char *from = buffer, *to = buffer;
while (from < end) {
Foo *block = (Foo *)from;
size_t size = sizeof(struct Foo) + block->data_size;
if (block->mark) {
// reset the mark:
block->mark = false;
// Compact by moving from `from` to `to`.
memmove(to, from, size);
to += size;
} else {
// Don't do anything, since we're getting rid of this block.
printf("Freed block of size %d\n", block->data_size);
}
from += size;
}
end = to;