r/ProgrammingLanguages • • Apr 29 '26

Blessed Syntax and Ergonomics

https://www.gingerbill.org/article/2026/04/29/blessed-syntax-and-ergonomics/

(not my article, but thought y'all might find it interesting)

33 Upvotes

22 comments sorted by

View all comments

Show parent comment

3

u/WittyStick Apr 29 '26 edited Apr 30 '26

I use the "16-byte fat-pointer" a for almost everything in C, because it is optimized on x64 SYSV to get returned in 2 hardware registers, so we can avoid touching the stack in many places.

If the "auxiliary" information attached to the pointer is an intptr_t, then it can be used for an integer or pointer.

#define FatPointer(T) struct { intptr_t aux; T *ptr; }

typdef FatPointer(char) String;

String str_create(size_t len, char *ptr) {
    return (String){ (intptr_t)len, (void*)ptr };
}

size_t str_length(String p) {
    return (size_t)p.aux;
}

Anything where we can't fit it into 64-bits, we just allocate a "header" structure and store the pointer to that header in the auxiliary field. Eg:

struct gb_header {
    uint64_t start;
    uint64_t end;
};

typedef FatPointer(char) GapBuffer;

GapBuffer gb_create(uint64_t start, uint64_t end, char *ptr) {
    struct gb_header *header = malloc(sizeof(struct gb_header));
    header->start = start;
    header->end = end;
    return (GapBuffer){ (intptr_t)header, (void*)ptr };
}

int64_t gb_start(GapBuffer p) {
    return ((struct gb_header*)(p.aux))->start;
}

int64_t gb_end(GapBuffer p) {
    return ((struct gb_header*)(p.aux))->end;
}

Would permit gap buffers larger than 4GiB, but using two 32-bit integers in the aux field is fine too if this isn't an issue.

For dynamic arrays, many implementations in C use something like:

struct darray {
    size_t len;
    size_t cap;
    void *ptr;
};

But this sucks because it's 24 bytes (which gets put on the stack for both argument passing and returns). We could limit the array to 4GiB by using 2 32-bit ints, or use a pointer to a header like above - but there's another option. Most of these dynamic arrays work by doubling the capacity when it is full. If we're doing this, then storing the capacity is just wasted space - we can compute the capacity from the length: cap = __builtin_stdc_bit_ceil(len). We get rid of the cap from the structure and now it fits nicely into our optimized 16-byte fat pointer.

I use a bunch of other tricks to basically make most data types a fat pointer.