src/linked_list.c

changeset 402
a34b93911956
parent 401
e6a8f7fb0c45
child 403
8fa43b732980
equal deleted inserted replaced
401:e6a8f7fb0c45 402:a34b93911956
49 49
50 return last; 50 return last;
51 } 51 }
52 } 52 }
53 53
54 int cx_linked_list_add(void **begin, void **end, ptrdiff_t loc_next, ptrdiff_t loc_prev, void *newnode) { 54 int cx_linked_list_add(void **begin, void **end, ptrdiff_t loc_prev, ptrdiff_t loc_next, void *newnode) {
55 // TODO: how do we report error messages? 55 // TODO: how do we report error messages?
56 if (loc_next < 0 || (begin == NULL && end == NULL)) { 56 if (loc_next < 0 || (begin == NULL && end == NULL)) {
57 return 1; 57 return 1;
58 } 58 }
59 59
77 return 0; 77 return 0;
78 } 78 }
79 79
80 /* HIGH LEVEL LINKED LIST IMPLEMENTATION */ 80 /* HIGH LEVEL LINKED LIST IMPLEMENTATION */
81 81
82 struct cx_linked_list_node {
83 void *prev;
84 void *next;
85 int payload;
86 };
87
82 typedef struct { 88 typedef struct {
83 void *begin; 89 void *begin;
84 void *end; 90 void *end;
85 } cx_linked_list; 91 } cx_linked_list;
86 92
87 int cx_ll_add(cx_list *list, void *elem) { 93 int cx_ll_add(cx_list *list, void *elem) {
88 cx_linked_list *listdata = list->listdata; 94 cx_linked_list *listdata = list->listdata;
89 CxAllocator allocator = list->allocator; 95 CxAllocator allocator = list->allocator;
90 96
91 /* 97 struct cx_linked_list_node *node = cxMalloc(allocator,
92 * Memory layout: 98 sizeof(struct cx_linked_list_node) - sizeof(int) + list->itemsize);
93 * next : sizeof(void*)
94 * prev : sizeof(void*)
95 * data : itemsize
96 */
97 void *node = cxMalloc(allocator,2*sizeof(void*)+list->itemsize);
98 if (node == NULL) 99 if (node == NULL)
99 return 1; 100 return 1;
100 101
101 memset(node, 0, sizeof(void*)); 102 node->next = NULL;
102 memcpy(node+2, elem, list->itemsize); 103 memcpy(&node->payload, elem, list->itemsize);
103 104
104 int ret = cx_linked_list_add( 105 int ret = cx_linked_list_add(
105 &listdata->begin, 106 &listdata->begin,
106 &listdata->end, 107 &listdata->end,
107 0, 108 offsetof(struct cx_linked_list_node, prev),
108 sizeof(void*), 109 offsetof(struct cx_linked_list_node, next),
109 node 110 node
110 ); 111 );
111 if (ret == 0) { 112 if (ret == 0) {
112 list->size++; 113 list->size++;
113 return 0; 114 return 0;

mercurial