Home | History | Annotate | Download | only in toolbox
      1 #include "dynarray.h"
      2 #include <stdlib.h>
      3 #include <limits.h>
      4 
      5 void
      6 dynarray_init( dynarray_t *a )
      7 {
      8     a->count = a->capacity = 0;
      9     a->items = NULL;
     10 }
     11 
     12 
     13 static void
     14 dynarray_reserve_more( dynarray_t *a, int count )
     15 {
     16     int old_cap = a->capacity;
     17     int new_cap = old_cap;
     18     const int max_cap = INT_MAX/sizeof(void*);
     19     void** new_items;
     20     int new_count = a->count + count;
     21 
     22     if (count <= 0)
     23         return;
     24 
     25     if (count > max_cap - a->count)
     26         abort();
     27 
     28     new_count = a->count + count;
     29 
     30     while (new_cap < new_count) {
     31         old_cap = new_cap;
     32         new_cap += (new_cap >> 2) + 4;
     33         if (new_cap < old_cap || new_cap > max_cap) {
     34             new_cap = max_cap;
     35         }
     36     }
     37     new_items = realloc(a->items, new_cap*sizeof(void*));
     38     if (new_items == NULL)
     39         abort();
     40 
     41     a->items = new_items;
     42     a->capacity = new_cap;
     43 }
     44 
     45 void
     46 dynarray_append( dynarray_t *a, void* item )
     47 {
     48     if (a->count >= a->capacity)
     49         dynarray_reserve_more(a, 1);
     50 
     51     a->items[a->count++] = item;
     52 }
     53 
     54 void
     55 dynarray_done( dynarray_t *a )
     56 {
     57     free(a->items);
     58     a->items = NULL;
     59     a->count = a->capacity = 0;
     60 }
     61 
     62 // string arrays
     63 
     64 void strlist_init( strlist_t *list )
     65 {
     66     dynarray_init(list);
     67 }
     68 
     69 void strlist_append_b( strlist_t *list, const void* str, size_t  slen )
     70 {
     71     char *copy = malloc(slen+1);
     72     memcpy(copy, str, slen);
     73     copy[slen] = '\0';
     74     dynarray_append(list, copy);
     75 }
     76 
     77 void strlist_append_dup( strlist_t *list, const char *str)
     78 {
     79     strlist_append_b(list, str, strlen(str));
     80 }
     81 
     82 void strlist_done( strlist_t *list )
     83 {
     84     STRLIST_FOREACH(list, string, free(string));
     85     dynarray_done(list);
     86 }
     87 
     88 static int strlist_compare_strings(const void* a, const void* b)
     89 {
     90     const char *sa = *(const char **)a;
     91     const char *sb = *(const char **)b;
     92     return strcmp(sa, sb);
     93 }
     94 
     95 void strlist_sort( strlist_t *list )
     96 {
     97     if (list->count > 0) {
     98         qsort(list->items,
     99               (size_t)list->count,
    100               sizeof(void*),
    101               strlist_compare_strings);
    102     }
    103 }
    104