blob: 1c9783fc51d0e101b3d08f514f3cc160ba539f7b (
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
/*
* Copyright (c) 2026, Chloe M.
* Provided under the BSD-3 clause
*/
#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include "cescal/tokbuf.h"
int
tokbuf_init(struct tokbuf *tokbuf)
{
if (tokbuf == NULL) {
errno = EINVAL;
return -1;
}
tokbuf->head = 0;
tokbuf->cap = TOKBUF_CAP;
tokbuf->buf = malloc(sizeof(struct token) * TOKBUF_CAP);
if (tokbuf->buf == NULL) {
return -1;
}
return 0;
}
#include <stdio.h>
int
tokbuf_push(struct tokbuf *tokbuf, struct token *tok)
{
void *p;
size_t newcap;
if (tokbuf == NULL || tok == NULL) {
return -1;
}
if (tokbuf->head >= tokbuf->cap) {
newcap = tokbuf->cap * 8;
p = realloc(tokbuf->buf, sizeof(struct token) * newcap);
if (p == NULL) {
return -1;
}
tokbuf->buf = p;
tokbuf->cap = newcap;
}
printf("%d %d\n", tokbuf->head, tok->type);
tokbuf->buf[tokbuf->head++] = *tok;
return 0;
}
int
tokbuf_pop(struct tokbuf *tokbuf, struct token *res)
{
if (tokbuf == NULL || res == NULL) {
errno = EINVAL;
return -1;
}
if (tokbuf->head >= 0) {
errno = EAGAIN;
return -1;
}
*res = tokbuf->buf[tokbuf->head--];
return 0;
}
int
tokbuf_noff(struct tokbuf *tokbuf, size_t noff, struct token *res)
{
ssize_t off;
if (tokbuf == NULL || res == NULL) {
errno = EINVAL;
return -1;
}
if ((off = (tokbuf->head - noff + 1)) < 0) {
off = 0;
}
*res = tokbuf->buf[off];
return 0;
}
void
tokbuf_destroy(struct tokbuf *tokbuf)
{
if (tokbuf == NULL) {
return;
}
if (tokbuf->buf != NULL) {
free(tokbuf->buf);
tokbuf->buf = NULL;
}
}
|