aboutsummaryrefslogtreecommitdiff
path: root/sloth.c
blob: 8314b79dcae90ff11d70b0ceba4e0ba90af8a9ba (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
#include "sloth.h"
#include <stdio.h>
#include <stdlib.h>

void sloth_deinit(Sloth *ctx)
{
	if (ctx->stack != NULL) {
		free(ctx->stack);
		ctx->stack = NULL;
	}
}

SlothError sloth_pop(Sloth *ctx, SlothByte *v)
{
	if (ctx->stack_size == 0)
		return "sloth_pull: stack is empty";
	*v = ctx->stack[ctx->stack_size - 1];
	ctx->stack_size -= 1;
	return NULL;
}

SlothError sloth_push(Sloth *ctx, SlothByte v)
{
	if (ctx->stack == NULL) {
		ctx->stack = malloc(sizeof(SlothByte) * 16);
		if (ctx->stack == NULL)
			return "sloth_push: calloc failed";
		ctx->stack_capacity = 16;
	} else if (ctx->stack_size == ctx->stack_capacity) {
		SlothByte *const new_stack =
			realloc(ctx->stack, ctx->stack_capacity * 2);
		if (new_stack == NULL)
			return "sloth_push: realloc failed";
		ctx->stack_capacity *= 2;
	}
	ctx->stack[ctx->stack_size] = v;
	ctx->stack_size += 1;
	return NULL;
}

void sloth_inspect_stack(const Sloth *ctx)
{
	printf("<%lu> ", ctx->stack_size);
	for (size_t i = 0; i < ctx->stack_size; i++)
		printf("%d ", ctx->stack[i]);
}