Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

mikronova/openzl-sys-rs

csrc/zlsys_budget.c

/* openzl-sys-rs: the budget itself. Compiled with the real malloc family. */
#include <stdlib.h>
#include "zlsys_budget.h"

static _Thread_local zlsys_budget budget;

void zlsys_budget_get(zlsys_budget* out) { *out = budget; }
void zlsys_budget_set(const zlsys_budget* in) { budget = *in; }

/* Charge `size` bytes; 0 means refuse. A free gives nothing back. */
static int charge(size_t size)
{
    if (!budget.active) return 1;
    if (size > budget.remaining) {
        budget.exceeded = 1;
        return 0;
    }
    budget.remaining -= size;
    return 1;
}

void* zlsys_malloc(size_t size) { return charge(size) ? malloc(size) : NULL; }

void* zlsys_calloc(size_t n, size_t size)
{
    size_t total;
    if (__builtin_mul_overflow(n, size, &total)) return NULL;
    return charge(total) ? calloc(n, size) : NULL;
}

void* zlsys_realloc(void* ptr, size_t size) { return charge(size) ? realloc(ptr, size) : NULL; }