stack.c
1.65 KB
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
//
// Created by imanol on 12/25/16.
//
#include <malloc.h>
#include "stack.h"
#define EXTEND_SIZE 10
uint8_t STACK_FAULT = 0;
uint32_t stack_size = EXTEND_SIZE;
uint32_t stack_pos = 0xFFFFFFFF;
uint32_t stack_elems = 0;
uint16_t *stack;
void initialize_stack()
{
stack = calloc(EXTEND_SIZE,sizeof(uint16_t));
}
void free_stack()
{
free(stack);
stack_size = 0;
stack_pos = 0;
stack = NULL;
}
void extend_stack()
{
stack_size += EXTEND_SIZE;
void *new_ptr = realloc(stack,stack_size*sizeof(uint16_t));
if(new_ptr == NULL)
{
fprintf(stderr,"CRITICAL: STACK ALLOCATION ERROR\n");
core_dump();
}
stack = new_ptr;
}
void shrink_stack()
{
stack_size -= EXTEND_SIZE;
void *new_ptr = realloc(stack,stack_size*sizeof(uint16_t));
if(new_ptr == NULL)
{
fprintf(stderr,"CRITICAL: STACK ALLOCATION ERROR\n");
core_dump();
}
stack = new_ptr;
}
void stack_push(uint16_t value)
{
stack[++stack_pos] = value;
if(++stack_elems == stack_size-1)
{
extend_stack();
}
}
uint16_t stack_pop()
{
if(!stack_elems)
{
STACK_FAULT = 1;
return 0xFFFF;
}
uint16_t value = stack[stack_pos--];
if(stack_size - --stack_elems == 2*EXTEND_SIZE)
{
shrink_stack();
}
return value;
}
uint32_t stack_dump(uint16_t **dump)
{
*dump = calloc(stack_elems,sizeof(uint16_t));
uint32_t i;
for(i = 0; i < stack_elems; i++)
{
(*dump)[i] = stack[i];
}
return stack_elems;
}
void stack_load(uint16_t *dump,uint32_t size)
{
uint32_t i;
for(i = 0; i < size; i++)
{
stack_push(dump[i]);
}
}