blob: e9b7b03fdfb5f9bee0512d93978e288f99c4ba3d [file] [log] [blame]
David 'Digit' Turnera8d1afb2011-01-06 08:39:44 +01001#include "dynarray.h"
2#include <stdlib.h>
3#include <limits.h>
4
5void
6dynarray_init( dynarray_t *a )
7{
8 a->count = a->capacity = 0;
9 a->items = NULL;
10}
11
12
13static void
14dynarray_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
45void
46dynarray_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
54void
55dynarray_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
64void strlist_init( strlist_t *list )
65{
66 dynarray_init(list);
67}
68
69void 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
77void strlist_append_dup( strlist_t *list, const char *str)
78{
79 strlist_append_b(list, str, strlen(str));
80}
81
82void strlist_done( strlist_t *list )
83{
84 STRLIST_FOREACH(list, string, free(string));
85 dynarray_done(list);
86}
87
88static 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
95void 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}