stack.c 1.64 KB
//
// 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 = 0xFFFF;
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]);
    }
}