view src/parallel_execution/stack.c @ 126:f57e9ffa7960

add comment rb_tree
author ikkun
date Wed, 14 Sep 2016 20:35:21 +0900
parents 9e139a340bd1
children
line wrap: on
line source

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

stack_ptr stack_init(size_t size, int max) {
    stack_ptr p;
    
    if ((p = calloc(1, sizeof(stack))) == NULL)
        return NULL;
    
    if ((p->data = calloc(max, size)) == NULL) {
        free(p);
        return NULL;
    }

    p->size = size;
    p->max = max;
    p->num = 0;

    return p;
}

stack_ptr stack_realloc(stack_ptr p, int max) {
    if (p == NULL)
        return NULL;

    if ((p->data = realloc(p->data, p->size*max)) == NULL)
        return NULL;

    p->max = max;

    return p;
}

void stack_free(stack_ptr p) {
    if (p != NULL && p->data != NULL) {
        free(p->data);
        free(p);
    }
}
    
int stack_push(stack_ptr p, void* data) {
    if (p->max <= p->num)
        return -1;

    memcpy((char*)p->data+p->num*p->size,  data, p->size);
    p->num++;

    return 0;
}

int stack_pop(stack_ptr p, void* data) {
    if (p->num == 0)
        return -1;

    p->num--;

    memcpy(data, (char*)p->data+p->num*p->size, p->size);
    
    return 0;
}

int isMax(const stack_ptr p) {
    return p->max<=p->num;
}

int isEmpty(const stack_ptr p) {
    return p->num<=0;
}