]> begriffs open source - libderp/blob - test/t_vector.c
Match numeric types
[libderp] / test / t_vector.c
1 #include "vector.h"
2
3 #include <assert.h>
4 #include <stdint.h>
5 #include <stdlib.h>
6
7 #define ARRAY_LEN(a) (sizeof(a)/sizeof(*a))
8
9 int cmpint(const void *a, const void *b, void *aux)
10 {
11         (void)aux;
12         return *(int*)a - *(int*)b;
13 }
14
15 void myfree(void *a, void *aux)
16 {
17         (void)aux;
18         free(a);
19 }
20
21 int main(void)
22 {
23         int ivals[] =  {0,1,2,3,4,5,6,7,8,9},
24             ivals2[] = {10,11,12,13,14,15,16,17,18,19};
25         size_t i;
26         vector *vint = v_new();
27         assert(v_length(vint) == 0);
28         assert(v_is_empty(vint));
29
30         for (i = 0; i < ARRAY_LEN(ivals); i++)
31                 v_prepend(vint, ivals+i);
32         assert(v_length(vint) == ARRAY_LEN(ivals));
33         assert(*(int*)v_first(vint) == 9);
34         assert(*(int*)v_remove_first(vint) == 9);
35         assert(*(int*)v_remove_first(vint) == 8);
36         v_sort(vint, cmpint, NULL);
37         assert(*(int*)v_first(vint) == 0);
38
39         v_clear(vint);
40         assert(v_length(vint) == 0);
41         for (i = 0; i < ARRAY_LEN(ivals); i++)
42                 v_append(vint, ivals+i);
43         assert(v_length(vint) == ARRAY_LEN(ivals));
44         assert(*(int*)v_last(vint) == 9);
45         assert(*(int*)v_remove_last(vint) == 9);
46         assert(*(int*)v_remove_last(vint) == 8);
47
48         assert(v_find_index(vint, ivals+5, cmpint, NULL) == 5);
49         v_insert(vint, 5, ivals2+5);
50         assert(v_find_index(vint, ivals2+5, cmpint, NULL) == 5);
51         v_swap(vint, 5, 6);
52         assert(v_find_index(vint, ivals2+5, cmpint, NULL) == 6);
53         v_remove(vint, 6);
54         assert(v_find_index(vint, ivals2+5, cmpint, NULL) == SIZE_MAX);
55         assert(v_find_last_index(vint, ivals2+5, cmpint, NULL) == SIZE_MAX);
56
57         v_clear(vint);
58         int revme_even[] = {1,2};
59         for (i = 0; i < ARRAY_LEN(revme_even); i++)
60                 v_append(vint, revme_even+i);
61         v_reverse(vint);
62         assert(*(int*)v_at(vint, 0) == 2);
63         assert(*(int*)v_at(vint, 1) == 1);
64
65         v_clear(vint);
66         int revme_odd[] = {1,2,3};
67         for (i = 0; i < ARRAY_LEN(revme_odd); i++)
68                 v_append(vint, revme_odd+i);
69         v_reverse(vint);
70         assert(*(int*)v_at(vint, 0) == 3);
71         assert(*(int*)v_at(vint, 1) == 2);
72         assert(*(int*)v_at(vint, 2) == 1);
73
74         v_clear(vint);
75         /* test for memory leak */
76         v_dtor(vint, myfree, NULL);
77         int *life = malloc(sizeof *life);
78         *life = 42;
79         v_append(vint, life);
80
81         v_free(vint);
82
83         return 0;
84 }