#include #include #include typedef struct _list { int index; int prev; int next; } list; list* clib_llist_elt(list* parent, int index) { return parent + index; } list* clib_llist_prev(list* parent, list* elt) { return clib_llist_elt(parent, elt->prev); } list* clib_llist_next(list* parent, list* elt) { return clib_llist_elt(parent, elt->next); } int clib_llist_prev_index(list* elt) { return elt->prev; } int clib_llist_next_index(list* elt) { return elt->next; } void clib_llist_remove(list* parent, list* elt) { assert ( elt != clib_llist_next(parent, elt)); assert ( elt->next != -1); assert ( elt->prev != -1); list* prev = clib_llist_prev(parent, elt); list* next = clib_llist_next(parent, elt); prev->next = elt->next; next->prev = elt->prev; elt->next = elt->prev = -1; } void clib_llist_insert(list* parent, list* elt, list* prev, list* next) { elt->prev = next->prev; elt->next = prev->next; next->prev = elt - parent; prev->next = elt - parent; } int clib_llist_is_empty(list* parent, list* elt) { return (elt - parent) == elt->next; } int clib_llist_elt_is_cycle(list* elt) { return elt->next == elt->prev; } void clib_llist_add_tail(list* parent, list* elt, list* he) { list* prev = clib_llist_prev (parent, he); clib_llist_insert(parent, elt, prev, he); } int clib_llist_elt_is_linked(list* elt) { return (elt->next != -1) && (elt->prev != -1); } int main(int argc, const char** argv, const char** env) { list elts[17] = { -1 }; for (int i = 0; i < sizeof(elts) / sizeof(list); i++) { elts[i].index = i; } elts[4].prev = 16; elts[4].next = 12; elts[12].prev = 4; elts[12].next = 16; elts[16].prev = 12; elts[16].next = 4; list* event_elts = elts, *elt, *he; int ei = 0, next_ei = 0, pending_main_ei = 4; he = clib_llist_elt (event_elts, pending_main_ei); ei = clib_llist_next_index (he); while (ei != pending_main_ei) { elt = clib_llist_elt(event_elts, ei); next_ei = clib_llist_next_index(elt); clib_llist_remove(event_elts, elt); he = clib_llist_elt(event_elts, pending_main_ei); #ifdef LOOP if ((!clib_llist_is_empty(event_elts, he))) //infinite loop #else if ((!clib_llist_elt_is_cycle(he))) #endif { clib_llist_add_tail(event_elts, elt, he); } else { printf("Processing: %d\r\n", ei); } elt = clib_llist_elt (event_elts, ei); if (clib_llist_elt_is_linked (elt)) { printf("free elt: %d\r\n", elt->index); } ei = next_ei; } return 0; }