#include "scratch.h"

INTERNAL THREAD_LOCAL_VAR_ALLOC_FUNC_DEF(scratch_context_alloc, vctx)
{
    __prof;
    struct scratch_ctx *ctx = vctx;
    for (u32 i = 0; i < ARRAY_COUNT(ctx->arenas); ++i) {
        ctx->arenas[i] = arena_alloc(SCRATCH_ARENA_RESERVE);
    }
}

INTERNAL THREAD_LOCAL_VAR_RELEASE_FUNC_DEF(scratch_context_release, vctx)
{
    __prof;
    struct scratch_ctx *ctx = vctx;

#if RTC
    /* If stack count is not 0, then a `scratch_end` is missing on a top-level
     * scratch arena (The temp_arena with
     * `scratch_id` = ctx->scratch_id_stack[ctx->scratch_id_stack_count - 1]) */
    ASSERT(ctx->scratch_id_stack_count == 0);
#endif

    for (u32 i = 0; i < ARRAY_COUNT(ctx->arenas); ++i) {
        arena_release(&ctx->arenas[i]);
    }
}

THREAD_LOCAL_VAR_DEF_EXTERN(tl_scratch_ctx, struct scratch_ctx, &scratch_context_alloc, &scratch_context_release);
