[ctxt] ax_ctxt basics

This commit is contained in:
Milo Turner 2020-02-07 17:32:41 -05:00
parent b881b62e5b
commit f36272b66f
3 changed files with 75 additions and 15 deletions

23
src/ctxt.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
#include "util/region.h"
struct ax_ctxt {
struct rgn* self_rgn;
struct rgn err_rgn;
char* err;
};
void ax__ctxt_init(struct ax_ctxt* ax, struct rgn* self_rgn);
void ax__ctxt_cleanup(struct ax_ctxt* ax);
static inline char* ax__make_error_buf(struct ax_ctxt* ax, size_t n)
{
rgn_clear(&ax->err_rgn);
return (ax->err = ralloc_typed(&ax->err_rgn, char, n));
}
static inline void ax__set_error(struct ax_ctxt* ax, const char* text)
{
strcpy(ax__make_error_buf(ax, strlen(text) + 1), text);
}

45
src/ctxt/ctxt.c Normal file
View File

@ -0,0 +1,45 @@
#include "../ctxt.h"
#include "../ax.h"
/* -----------------------------------------------------------------------------
* API functions
* -------------------------------------------------------------------------- */
struct ax_ctxt* ax_new(void)
{
// "bootstrap" a new region
struct rgn rgn0;
rgn_init(&rgn0, SMALL);
struct rgn* rgn = rmemdup_typed(&rgn0, struct rgn, &rgn0, 1);
// use it to make a new context
struct ax_ctxt* ax = ralloc_typed(rgn, struct ax_ctxt, 1);
ax__ctxt_init(ax, rgn);
return ax;
}
void ax_free(struct ax_ctxt* ax)
{
ax__ctxt_cleanup(ax);
rgn_cleanup(ax->self_rgn);
}
const char* ax_get_error(struct ax_ctxt* ax)
{
return ax->err;
}
/* -----------------------------------------------------------------------------
* Internal 'ax_ctxt' operations
* -------------------------------------------------------------------------- */
void ax__ctxt_init(struct ax_ctxt* ax, struct rgn* self_rgn)
{
ax->self_rgn = self_rgn;
rgn_init(&ax->err_rgn, SMALL);
ax->err = "";
}
void ax__ctxt_cleanup(struct ax_ctxt* ax)
{
rgn_cleanup(&ax->err_rgn);
}

View File

@ -1,21 +1,13 @@
#include "../src/region.h"
#include <stdio.h>
#include "../src/ax.h"
#include "../src/ctxt.h"
int main(void)
{
struct rgn rgn[1];
rgn_init(rgn, SMALL);
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 30; i++) {
char test[100];
memset(test, 'A', 99);
test[99] = '\0';
printf("%d; %p\n", j, rstrdup(rgn, test));
}
rgn_clear(rgn);
}
rgn_cleanup(rgn);
struct ax_ctxt* ax = ax_new();
ax__set_error(ax, "hello world");
printf("--> %s\n", ax_get_error(ax));
ax_free(ax);
return 0;
}