1 | #include <stdlib.h> |
---|
2 | |
---|
3 | #include "abac_list.h" |
---|
4 | #include "abac_util.h" |
---|
5 | |
---|
6 | abac_list_t *abac_list_new(void) { |
---|
7 | abac_list_t *ret = abac_xmalloc(sizeof(abac_list_t)); |
---|
8 | ret->elts = NULL; |
---|
9 | ret->size = 0; |
---|
10 | return ret; |
---|
11 | } |
---|
12 | |
---|
13 | void abac_list_add(abac_list_t *list, void *elt) { |
---|
14 | abac_list_element_t *new_element = abac_xmalloc(sizeof(abac_list_element_t)); |
---|
15 | |
---|
16 | new_element->ptr = elt; |
---|
17 | DL_APPEND(list->elts, new_element); |
---|
18 | ++list->size; |
---|
19 | } |
---|
20 | |
---|
21 | /* add only if it is not in the list already */ |
---|
22 | int abac_list_unique_add(abac_list_t *list, void *elt) { |
---|
23 | void *cur; |
---|
24 | abac_list_foreach(list, cur, |
---|
25 | if(cur == elt) |
---|
26 | return 0; |
---|
27 | ); |
---|
28 | |
---|
29 | abac_list_element_t *new_element = abac_xmalloc(sizeof(abac_list_element_t)); |
---|
30 | new_element->ptr = elt; |
---|
31 | DL_APPEND(list->elts, new_element); |
---|
32 | ++list->size; |
---|
33 | return 1; |
---|
34 | } |
---|
35 | |
---|
36 | void abac_list_prepend(abac_list_t *list, void *elt) { |
---|
37 | abac_list_element_t *new_element = abac_xmalloc(sizeof(abac_list_element_t)); |
---|
38 | |
---|
39 | new_element->ptr = elt; |
---|
40 | DL_PREPEND(list->elts, new_element); |
---|
41 | ++list->size; |
---|
42 | } |
---|
43 | |
---|
44 | int abac_list_remove(abac_list_t *list, void *elt) { |
---|
45 | abac_list_element_t *cur; |
---|
46 | |
---|
47 | // iterate the list, remove the item if we find it |
---|
48 | DL_FOREACH(list->elts, cur) { |
---|
49 | if (cur->ptr == elt) { |
---|
50 | DL_DELETE(list->elts, cur); |
---|
51 | free(cur); |
---|
52 | --list->size; |
---|
53 | return 1; |
---|
54 | } |
---|
55 | } |
---|
56 | |
---|
57 | // return false if we don't |
---|
58 | return 0; |
---|
59 | } |
---|
60 | |
---|
61 | int abac_list_size(abac_list_t *list) { |
---|
62 | if (list) |
---|
63 | return list->size; |
---|
64 | return 0; |
---|
65 | } |
---|
66 | |
---|
67 | void abac_list_free(abac_list_t *list) { |
---|
68 | abac_list_element_t *elt, *tmp; |
---|
69 | |
---|
70 | if (list) { |
---|
71 | // free everthing in the list |
---|
72 | DL_FOREACH_SAFE(list->elts, elt, tmp) { |
---|
73 | DL_DELETE(list->elts, elt); |
---|
74 | free(elt); |
---|
75 | } |
---|
76 | |
---|
77 | // free the list |
---|
78 | free(list); |
---|
79 | } |
---|
80 | } |
---|