03. Coding It!
Recap
In the previous post, I laid out the binary architecture: a 500 MiB page aligned arena with 64-byte nodes, 32-byte overflow edge buckets, three store tiers for strings, and O(1) free-lists. Now it was time to actually write the C code and see if my idea survives getting written down, also how many segfaults I might get. (I lost count)
The whole core engine, file mapping, header layout, allocators, and edge operations, came together in a quick sprint over a few days, around 3 to 4. Then it sat there for about a month.
Why the gap? Honestly, I just got lazy about writing the API. It was also my first time actually designing a proper C library API from scratch, and I genuinely wasn't sure which features belonged on the public interface versus what should stay buried inside the engine. Once I finally stopped putting it off in, wrapping it into a .so took less than a day.
Sparse Files & mmap
First thing I wrote was src/file_mapper.c. When creating a new graph file, I need it to be 500 MiB (FILESIZE = 524288000) before calling mmap, otherwise touching pages past EOF triggers a SIGBUS crash.
Instead of writing 500 MiB of zeros lazily in a loop, POSIX lets me seek straight to the last byte and write a single \0:
int _create_file(const char *filename, int *fd){
*fd = open(filename, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (*fd == -1) return -1;
if (lseek(*fd, FILESIZE - 1, SEEK_SET) == -1) { close(*fd); return -1; }
if (write(*fd, "", 1) == -1) { close(*fd); return -1; }
return 0;
}
On modern Linux filesystems, that creates a sparse file almost instantly. Right after that, map_file maps the whole descriptor with PROT_READ | PROT_WRITE and MAP_SHARED, closes fd (since mmap keeps its own kernel reference so no reason to leak file descriptors), and if the file was freshly created, runs map_header() and map_scheme() to initialize Page 0 and thread all five free-lists from 0 up to max - 1.
The Core Allocators
Rather than passing six different struct pointers into every internal function, I wrote a tiny helper load_graph(char *file, uintptr_t *out_pointers) that reads the page offsets out of Page 0 (GraphHeader) and computes the base addresses of nodes, buckets, slots_s, slots_m, and slots_l on the fly.
With that in place, writing the ten *_alloc and *_dealloc functions was almost therapeutic, for a chore-like task I had a good time writing those. Every single allocator follows the exact same O(1) pop pattern. For example, node_alloc:
uint32_t node_alloc(GraphHeader *header, GraphNode *nodes){
uint32_t new_id = header->first_free_node_idx;
if (new_id == UINT32_MAX) return UINT32_MAX;
header->first_free_node_idx = nodes[new_id].data_id;
header->num_nodes++;
nodes[new_id].data_id = UINT32_MAX;
return new_id;
}
And when node_dealloc kills a node, it checks which slot range data_id falls into (SlotS, SlotM, or SlotL), frees the string slot, checks if edges[7].rel_type == UINT16_MAX - 1 (65534), and if so calls bucket_dealloc which recursively walks edges[3] down any chained overflow buckets and pushes every single one back onto the bucket free-list.
Edge Spilling & Compaction
This 428-line file was the real meat of the project.
set_node_data and get_node_data were mostly careful bounds-checking and offset arithmetic (making sure if you overwrite an existing node's string, we allocate and populate the new slot before freeing the old one, rolling back if anything fails), mostly standard procedures.
Edges were much trickier specifically deleting an edge (remove_edge) without leaving leaking holes scattered across inline arrays and chained EdgeBuckets.
If a node has 14 edges spread across node.edges[0..6] plus two overflow buckets, and you delete node.edges[2], leaving a UINT16_MAX hole at index 2 means traverse_edges would stop early or every insert would have to scan the entire chain.
The fix was compaction through swapping with last element:
find_edgelocates the(bucket_id, edge_idx)coordinates of the edge we want to delete.find_last_edgewalks to the very end of the chain and records(last_bucket_id, last_edge_idx, prev_bucket_id).- We overwrite the deleted edge slot with the last edge's
{ target_id, rel_type }, and clear the last slot. - Bonus cleanup: If that last active edge happened to be at
index 0of the tailEdgeBucket, moving it out leaves the tail bucket completely empty! Sincefind_last_edgealso trackedprev_bucket_id(ornode.edges[7]if it was the first bucket), we sever the65534link andbucket_deallocthe empty bucket immediately.
No fragmentation, dense arrays for fast iteration, and buckets shrink back down automatically when edges are removed. This was the hardest part honestly.
Polishing It Into a Library
Originally, my internal functions returned raw uintptr_t addresses and integer error codes like (UINTPTR_MAX - 1, 1..6, etc.) which only I understood while I still ahd the full codebase etched in my head.
So when I revisited the repo a month later, I did two cleanups:
- Added
include/api/api.handsrc/api.cto translate every internal sentinel value into a unifiedResultenum (OK,EIARG,ENNODE,EBNODE, etc.) and clean return structs (OpenResult,NCreateResult,NGetResult, ...). - Updated the
Makefilewith-fPIC -fvisibility=hidden -shared, marking only the public functions inapi.hwith#define API __attribute__((visibility("default"))). That waybuild/bin/libc-mmap-graph.soexports a crisp 11-function ABI and hidesmap_scheme,load_graph, and all raw allocators from callers.
Wrapping Up
At this point, make spat out a clean shared library, zero external dependencies, all hand-written in just over a thousand lines of C. Of course, building something fast on a whim also leaves behind some funny sharp edges and design lessons which I'll be brutally honest about in the final post.
Written on: 2026-08-22