stack_sd

Stack for sd_t's
git clone git://www.tkruger.se/stack_sd.git
Log | Files | Refs | README

stack_sd.c (1108B)


      1 #include "stack_sd.h"
      2 
      3 void stack_sd_init(stack_sd_t *d) {
      4   d->nmemb = 0;
      5   d->alloc = BASE_STACK_SD_SIZE;
      6 
      7   d->data = calloc(d->alloc, sizeof(*(d->data)));
      8 }
      9 
     10 void stack_sd_init_size(stack_sd_t *d, const size_t size) {
     11   d->nmemb = 0;
     12   d->alloc = size;
     13 
     14   d->data = calloc(d->alloc, sizeof(*(d->data)));
     15 }
     16 
     17 void stack_sd_clear(stack_sd_t *d) {
     18   d->nmemb = 0;
     19   free(d->data);
     20   d->data = NULL;
     21 }
     22 
     23 void stack_sd_push(stack_sd_t *d, sd_t x) {
     24   if (d->alloc <= d->nmemb) {
     25     d->alloc <<= 1;
     26     d->data = realloc(d->data, d->alloc * sizeof(*(d->data)));
     27   }
     28 
     29   d->data[d->nmemb] = x;
     30   d->nmemb++;
     31 }
     32 
     33 sd_t stack_sd_get(const stack_sd_t *d, const size_t i) { return d->data[i]; }
     34 
     35 sd_t stack_sd_getlast(const stack_sd_t *d) { return stack_sd_get(d, d->nmemb - 1); }
     36 
     37 sd_t stack_sd_pop(stack_sd_t *d) {
     38   if (d->nmemb == 0)
     39     return STACK_SD_EMPTY_POP;
     40 
     41   sd_t r = stack_sd_getlast(d);
     42   d->nmemb--;
     43   return r;
     44 }
     45 
     46 int stack_sd_lookup(stack_sd_t *d, sd_t s) {
     47   size_t i;
     48   for (i = 0; i < d->nmemb; i++) {
     49     if (sd_cmp(&d->data[i], &s) == 0)
     50       return i;
     51   }
     52   return STACK_SD_LOOKUP_NOT_FOUND;
     53 }