Usage Documentation

Before Anything Else

If you are here for the story of why I locked myself in for a few days to build a graph database in C from scratch and how the binary layout, page math, and free-lists work under the hood, skip ahead to the next post (01. Making a Graph Database).
This first page is purely the reference manual for libc-mmap-graph.so: how to build it, link it, what every function expects, what every return code actually means, and the footguns you need to watch out for since this is raw memory-mapped C (because C always let's you shoot yourself in the foot).

Source code is over on GitHub: Iliyas-Amine/c-mmap-graph.


Compiling & Linking

Building the shared library only requires gcc and make on Linux:

git clone https://github.com/Iliyas-Amine/c-mmap-graph.git
cd c-mmap-graph
make

This compiles src/*.c with -O3 -fPIC -fvisibility=hidden and outputs the shared object at:

build/bin/libc-mmap-graph.so

All internal allocator and page-mapping symbols stay hidden; only the public wrapper API declared in include/api/api.h is exported in the dynamic symbol table.

To compile your own program against it:

gcc main.c -Iinclude -Lbuild/bin -lc-mmap-graph -Wl,-rpath,build/bin -o my_graph_app

And include the single public header:

#include "api/api.h"

Status Codes (Result)

Every operation returns either a Result enum directly or a small wrapper struct containing Result status alongside the requested value. Always check status == OK before touching the returned handle, ID, or pointer.

Enum Value Category Meaning
OK 0 General Operation succeeded.
EIARG 1 General Invalid argument (e.g., passing a NULL graph handle).
ERR 2 General Internal state error during slot replacement or edge removal.
ELNSTR 3 General Invalid string length passed to setNodeData (0 bytes or >= 1016 bytes).
ECREAT 4 File / IO Failed to create or size a new backing graph file on disk.
EOPEN 5 File / IO Failed to open an existing graph file, or file size does not match FILESIZE (500 MiB).
EMMAP 6 File / IO mmap() failed to map the file into memory.
ESYNC 7 File / IO msync() or munmap() failed while syncing/closing the mapped region.
ECLOSE 8 File / IO Reserved close error code (note: closeGraph currently reports unmap failure as ESYNC).
ENSSLT 9 Capacity Out of free Small payload slots (SlotS, < 248 bytes).
ENMSLT 10 Capacity Out of free Medium payload slots (SlotM, 248..503 bytes).
ENLSLT 11 Capacity Out of free Large payload slots (SlotL, 504..1015 bytes).
ENNODE 12 Capacity Out of free GraphNode records in the node partition.
ENBUCK 13 Capacity Reserved bucket exhaustion code (note: addEdge currently surfaces bucket exhaustion as EBBUCK).
EIDSLT 14 Bounds / ID Node has no payload assigned yet (getNodeData), or corrupt slot ID during deallocation.
EBNODE 15 Bounds / ID node_id is out of bounds (>= max_nodes).
EBBUCK 16 Bounds / ID Overflow EdgeBucket allocation/deallocation error.

Wrapped Return Structs

Because C doesn't have multiple return values and out-parameters get ugly fast, functions that produce data return one of five value structs:

typedef struct { Result status; void *handle; }        OpenResult;
typedef struct { Result status; uint32_t node_id; }    NCreateResult;
typedef struct { Result status; const char *content; } NGetResult;
typedef struct { Result status; bool exists; }         ECheckResult;
typedef struct { Result status; uint32_t count; }      NeighborCountResult;

Public API Reference

1. Lifecycle & Persistence

OpenResult openGraph(const char *filename)

Opens an existing .db / graph file, or creates, sparse allocates (500 MiB), maps, and formats a brand-new one if filename does not exist yet.

  • Returns: res.status == OK and a non-null opaque res.handle on success.

Result syncGraph(void *handle)

Triggers an asynchronous flush (msync(..., MS_ASYNC)) of dirty mapped pages back to the underlying file.

Result closeGraph(void *handle)

Unmaps the 500 MiB region via munmap(). Once called, handle and any const char * pointers previously obtained from getNodeData become invalid immediately.


2. Node Operations

NCreateResult createNode(void *handle)

Pops the next available node from the header's O(1) intrusive free-list.

  • Returns: { OK, node_id } (0-indexed) or { ENNODE, UINT32_MAX } if the node table is full.

Result killNode(void *handle, uint32_t node_id)

Deallocates node_id, automatically freeing its attached data slot (SlotS/SlotM/SlotL) and recursively freeing any chained overflow EdgeBuckets attached to its outgoing edges.

Result setNodeData(void *handle, uint32_t node_id, char *content)

Copies a null-terminated string into the smallest slab tier that fits it:

  • 1 .. 247 chars $\rightarrow$ SlotS (256 B record)
  • 248 .. 503 chars $\rightarrow$ SlotM (512 B record)
  • 504 .. 1015 chars $\rightarrow$ SlotL (1024 B record)

If the node already holds data, the old slot is automatically freed after the new slot is populated. Empty strings ("") or strings >= 1016 bytes return ELNSTR.

NGetResult getNodeData(void *handle, uint32_t node_id)

Resolves the node's data_id into the corresponding SlotS, SlotM, or SlotL region and returns a direct pointer to the mapped character buffer.

  • If node_id exists but has no payload set yet, returns { EIDSLT, NULL }.

3. Edge & Neighbor Operations

Result addEdge(void *handle, uint32_t from_node, uint32_t to_node, uint16_t rel_type)

Appends a directed edge from_node -> to_node tagged with a 16-bit relationship type.

  • The first 8 outgoing edges live inline inside the 64-byte GraphNode. Adding a 9th edge automatically spills slot 7 into a chained 32-byte EdgeBucket without moving the node.

Result removeEdge(void *handle, uint32_t from_node, uint32_t to_node)

Removes a directed edge from from_node to to_node using swap-with-last compaction (moving the final active outgoing edge into the deleted slot so edge arrays stay contiguous, and freeing the tail EdgeBucket if it becomes empty).

ECheckResult checkEdge(void *handle, uint32_t from_node, uint32_t to_node)

Scans from_node's inline edges and overflow bucket chain to check whether an edge to to_node exists. (See Known Quirks below regarding v1's boolean inversion.)

NeighborCountResult countNeighbors(void *handle, uint32_t node_id)

Counts total active outgoing edges from node_id across inline slots and overflow buckets.

Result getNeighbors(void *handle, uint32_t node_id, uint32_t *neighbors)

Writes all outgoing target node_ids of node_id into the caller-provided neighbors array.


Minimal Example

#include <stdio.h>
#include <stdlib.h>
#include "api/api.h"

int main(void) {
    OpenResult db = openGraph("social.cmgp");
    if (db.status != OK) return 1;

    NCreateResult a = createNode(db.handle);
    NCreateResult b = createNode(db.handle);

    setNodeData(db.handle, a.node_id, "iliyas");
    setNodeData(db.handle, b.node_id, "debian");

    addEdge(db.handle, a.node_id, b.node_id, 1); // rel_type 1 = "uses"

    NeighborCountResult nc = countNeighbors(db.handle, a.node_id);
    if (nc.status == OK && nc.count > 0) {
        uint32_t *adj = malloc(nc.count * sizeof(uint32_t));
        getNeighbors(db.handle, a.node_id, adj);

        NGetResult target = getNodeData(db.handle, adj[0]);
        if (target.status == OK) {
            printf("Node %u -> %s\n", a.node_id, target.content);
        }
        free(adj);
    }

    syncGraph(db.handle);
    closeGraph(db.handle);
    return 0;
}

Safety Warnings & Known Quirks

WARNING: This library talks straight to an mmap'ed region with zero runtime hand-holding. Keep these rules in mind:

  1. Never free() or mutate getNodeData().content: That const char * points straight into the mapped file page. Freeing it will crash your process, and calling setNodeData, killNode, or closeGraph invalidates the pointer. Copy it (strdup) if you need to hold onto it.
  2. Reserved rel_type values (65534 and 65535): Valid user rel_type IDs are 0 through 65533. Internally, 65534 (UINT16_MAX - 1) marks an overflow bucket pointer, and 65535 (UINT16_MAX) marks an empty edge slot. Passing either value to addEdge will corrupt edge traversal.
  3. Pre-size your getNeighbors buffer: getNeighbors assumes neighbors has room for at least countNeighbors(handle, node_id).count uint32_t entries. Passing a smaller buffer will overflow stack/heap memory.
  4. Dangling incoming edges on killNode: killNode is strictly O(1) (+ outgoing bucket chain length), it does not scan the entire graph to remove incoming edges from other nodes that still point to the killed node_id. Remove incoming edges yourself or track active nodes at the application layer.
  5. No internal locking: There are no mutexes or atomic CAS loops on free-list heads. Wrap calls in a mutex or flock if multiple threads/processes touch the same graph.
  6. Fixed 500 MiB sparse file: FILESIZE is compiled at 524,288,000 bytes (include/common.h). On Linux (ext4/btrfs/xfs), creating a new file uses lseek + a 1-byte write so actual disk blocks are allocated lazily as pages are dirtied, though ls -lh will report 500M.
  7. Known v1 bug in checkEdge: In commit eea629e, checkEdge evaluates coords[1] == UINT32_MAX instead of != UINT32_MAX, inverting res.exists. Until patched, flip the boolean or inspect getNeighbors.

Written on: 2026-08-21