diff options
Diffstat (limited to 'src/context.c')
-rw-r--r-- | src/context.c | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/context.c b/src/context.c new file mode 100644 index 0000000..3a98a64 --- /dev/null +++ b/src/context.c @@ -0,0 +1,53 @@ +#include <assert.h> +#include <context.h> +#include <stdio.h> +#include <stdlib.h> +#include <tokenize.h> + +struct ctx *context_create(const char *path) +{ + struct ctx *ctx = calloc(1, sizeof(*ctx)); + ctx->tokens = calloc(TOKENS_MAX, sizeof(*ctx->tokens)); + ctx->path = path; // TODO: strdup? + + FILE *file = fopen(path, "r"); + assert(file); + + // Find size of file + fseek(file, 0, SEEK_END); + ctx->size = ftell(file); + rewind(file); + assert(ctx->size); + + ctx->raw = malloc(ctx->size + 1); + assert(ctx->raw); + fread(ctx->raw, 1, ctx->size, file); + fclose(file); + + ctx->raw[ctx->size] = 0; + + return ctx; +} + +void context_destroy(struct ctx *ctx) +{ + if (!ctx) + return; + + if (ctx->raw) + free(ctx->raw); + + if (ctx->data && ctx->data != ctx->raw) + free(ctx->data); + + if (ctx->tokens) + free(ctx->tokens); + + free(ctx); +} + +void context_rewind(struct ctx *ctx) +{ + ctx->line = 0; + ctx->column = 0; +} |