/* * Copyright (c) 2026, Chloe M. * Provided under the BSD-3 clause */ #include #include #include #include #include #include #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; } int tokbuf_push(struct tokbuf *tokbuf, struct token *tok) { void *p; if (tokbuf == NULL || tok == NULL) { return -1; } if ((tokbuf->head++) >= tokbuf->cap - 1) { tokbuf->cap += 8; p = realloc(tokbuf->buf, sizeof(struct token) * tokbuf->cap); if (tokbuf->buf == NULL) { return -1; } tokbuf->buf = p; } tokbuf->buf[tokbuf->head] = *tok; 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 (noff == 0) { *res = tokbuf->buf[tokbuf->head + 1]; return 0; } 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; } }