core: tokbuf: Fix up token buffer
Signed-off-by: Chloe M. <chloe@mirocom.org>
This commit is contained in:
+27
-10
@@ -29,26 +29,48 @@ tokbuf_init(struct tokbuf *tokbuf)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
int
|
int
|
||||||
tokbuf_push(struct tokbuf *tokbuf, struct token *tok)
|
tokbuf_push(struct tokbuf *tokbuf, struct token *tok)
|
||||||
{
|
{
|
||||||
void *p;
|
void *p;
|
||||||
|
size_t newcap;
|
||||||
|
|
||||||
if (tokbuf == NULL || tok == NULL) {
|
if (tokbuf == NULL || tok == NULL) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((tokbuf->head++) >= tokbuf->cap - 1) {
|
if (tokbuf->head >= tokbuf->cap) {
|
||||||
tokbuf->cap += 8;
|
newcap = tokbuf->cap * 8;
|
||||||
p = realloc(tokbuf->buf, sizeof(struct token) * tokbuf->cap);
|
p = realloc(tokbuf->buf, sizeof(struct token) * newcap);
|
||||||
if (tokbuf->buf == NULL) {
|
if (p == NULL) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
tokbuf->buf = p;
|
tokbuf->buf = p;
|
||||||
|
tokbuf->cap = newcap;
|
||||||
}
|
}
|
||||||
|
|
||||||
tokbuf->buf[tokbuf->head] = *tok;
|
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;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,11 +84,6 @@ tokbuf_noff(struct tokbuf *tokbuf, size_t noff, struct token *res)
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (noff == 0) {
|
|
||||||
*res = tokbuf->buf[tokbuf->head + 1];
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((off = (tokbuf->head - noff + 1)) < 0) {
|
if ((off = (tokbuf->head - noff + 1)) < 0) {
|
||||||
off = 0;
|
off = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,16 @@ int tokbuf_init(struct tokbuf *tokbuf);
|
|||||||
*/
|
*/
|
||||||
int tokbuf_push(struct tokbuf *tokbuf, struct token *tok);
|
int tokbuf_push(struct tokbuf *tokbuf, struct token *tok);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Pop a token from the token buffer
|
||||||
|
*
|
||||||
|
* @tokbuf: Token buffer to pop from
|
||||||
|
* @res: Result is written here
|
||||||
|
*
|
||||||
|
* Returns zero on success
|
||||||
|
*/
|
||||||
|
int tokbuf_pop(struct tokbuf *tokbuf, struct token *res);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Peek at the token buffer from a negative offset backwards
|
* Peek at the token buffer from a negative offset backwards
|
||||||
*
|
*
|
||||||
|
|||||||
Reference in New Issue
Block a user