Comment

Comment by cataphract

Fair enough:

    struct hamt_allocator {
        void *(*realloc)(struct hamt_allocator *h, void *chk, size_t oldsize,
                        size_t newsize);
    };
    struct my_allocator {
        struct hamt_allocator parent;
        size_t used;
        char buffer[8192];
    };
    static void *alloc_func(struct hamt_allocator *h, void *chk,
                            const size_t oldsize, const size_t newsize)
    {
        if (!newsize) {
            return NULL;
        }
        if (h && newsize <= oldsize) {
            return h;
        }
        // this cast is allowed by the standard for this purpose
        __auto_type *alloc = (struct my_allocator*) h;
        if (newsize > sizeof(alloc->buffer) - alloc->used) {
            return NULL;
        }
        void *ret = alloc->buffer + alloc->used;
        alloc->used += newsize;
        if (h && oldsize) {
            memcpy(ret, h, oldsize);
        }
        return ret;
    }
    void func_taking_allocator(struct hamt_allocator *h);
    void user_code() {
        struct my_allocator alloc = { .parent.realloc = alloc_func };
        func_taking_allocator(&alloc.parent);
    }
parent cataphract 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton