thesis-lisp/vm/stack.c
2021-04-07 22:24:33 +03:00

35 lines
708 B
C

#include "error.h"
#include "stack.h"
#include <stdlib.h>
int stack_init(struct stack *st, size_t size) {
st->data = malloc(sizeof(uint64_t) * size);
if (!st->data) {
return -ERR_OUT_OF_MEMORY;
}
st->size = size;
st->sp = size;
return 0;
}
void stack_free(struct stack *st) {
free(st->data);
st->data = NULL;
st->size = 0;
st->sp = 0;
}
int stack_push(struct stack *st, uint64_t w) {
if (st->sp == 0) {
return -ERR_STACK_OVERFLOW;
}
st->data[--st->sp] = w;
return 0;
}
int stack_pop(struct stack *st, uint64_t *w) {
if (st->sp == st->size) {
return -ERR_STACK_UNDERFLOW;
}
*w = st->data[st->sp++];
return 0;
}