summaryrefslogtreecommitdiff
path: root/core/state.c
blob: b64271c73e6b6beb125572c9643d098c0d87f9e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (c) 2026, Chloe M.
 * Provided under the BSD-3 clause
 */

#include <stdint.h>
#include <stddef.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "cescal/state.h"

int
state_init(struct cescal_state *state, const char *pathname)
{
    if (state == NULL || pathname == NULL) {
        errno = EINVAL;
        return -1;
    }

    memset(state, 0, sizeof(*state));
    state->in_fd = open(pathname, O_RDONLY);
    if (state->in_fd < 0) {
        return -1;
    }

    if (readbuf_init(&state->rb) < 0) {
        close(state->in_fd);
        return -1;
    }

    if (tokbuf_init(&state->tokbuf) < 0) {
        close(state->in_fd);
        return -1;
    }

    if (symbol_table_init(&state->symtab) < 0) {
        close(state->in_fd);
        return -1;
    }

    if (ptrbox_init(&state->ptrbox) < 0) {
        close(state->in_fd);
        return -1;
    }

    return 0;
}

void
state_close(struct cescal_state *state)
{
    close(state->in_fd);
    state->in_fd = -1;
    ptrbox_destroy(&state->ptrbox);
    tokbuf_destroy(&state->tokbuf);
    symbol_table_destroy(&state->symtab);
}