Blame view

stack.c 1.65 KB
Imanol-Mikel Barba Sabariego authored
1
2
3
4
5
6
7
8
9
//
// Created by imanol on 12/25/16.
//

#include <malloc.h>
#include "stack.h"

#define EXTEND_SIZE 10
10
uint8_t STACK_FAULT = 0;
Imanol-Mikel Barba Sabariego authored
11
uint32_t stack_size = EXTEND_SIZE;
12
uint32_t stack_pos = 0xFFFFFFFF;
13
14
uint32_t stack_elems = 0;
uint16_t *stack;
Imanol-Mikel Barba Sabariego authored
15
16
17

void initialize_stack()
{
18
    stack = calloc(EXTEND_SIZE,sizeof(uint16_t));
Imanol-Mikel Barba Sabariego authored
19
20
}
21
22
23
24
25
26
27
28
void free_stack()
{
    free(stack);
    stack_size = 0;
    stack_pos = 0;
    stack = NULL;
}
Imanol-Mikel Barba Sabariego authored
29
30
31
void extend_stack()
{
    stack_size += EXTEND_SIZE;
32
    void *new_ptr = realloc(stack,stack_size*sizeof(uint16_t));
33
34
35
36
37
38
    if(new_ptr == NULL)
    {
        fprintf(stderr,"CRITICAL: STACK ALLOCATION ERROR\n");
        core_dump();
    }
    stack = new_ptr;
Imanol-Mikel Barba Sabariego authored
39
40
41
42
43
}

void shrink_stack()
{
    stack_size -= EXTEND_SIZE;
44
    void *new_ptr = realloc(stack,stack_size*sizeof(uint16_t));
45
46
47
48
49
50
    if(new_ptr == NULL)
    {
        fprintf(stderr,"CRITICAL: STACK ALLOCATION ERROR\n");
        core_dump();
    }
    stack = new_ptr;
Imanol-Mikel Barba Sabariego authored
51
52
}
53
void stack_push(uint16_t value)
Imanol-Mikel Barba Sabariego authored
54
{
55
    stack[++stack_pos] = value;
56
    if(++stack_elems == stack_size-1)
Imanol-Mikel Barba Sabariego authored
57
58
59
60
    {
        extend_stack();
    }
}
61
62
uint16_t stack_pop()
Imanol-Mikel Barba Sabariego authored
63
{
64
    if(!stack_elems)
65
66
    {
        STACK_FAULT = 1;
67
        return 0xFFFF;
68
    }
69
    uint16_t value = stack[stack_pos--];
70
    if(stack_size - --stack_elems == 2*EXTEND_SIZE)
Imanol-Mikel Barba Sabariego authored
71
72
73
74
    {
        shrink_stack();
    }
    return value;
75
76
}
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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]);
    }
}
97