ref.c (1279B)
1#include "ref.h" 2#include "list.h" 3#include "util.h" 4 5#include <stdlib.h> 6 7struct ref * 8ref_alloc(void *data) 9{ 10 struct ref *ref; 11 12 ref = malloc(sizeof(struct ref)); 13 if (!ref) ERROR(SYSTEM, "malloc"); 14 15 ref->link = LIST_LINK_INIT; 16 ref->data = data; 17 18 return ref; 19} 20 21void 22ref_free(void *ref) 23{ 24 free(ref); 25} 26 27void 28refs_free(struct list *list) 29{ 30 list_free_items(list, ref_free, LIST_OFFSET(struct ref, link)); 31} 32 33int 34refs_index(struct list *list, void *data) 35{ 36 struct list_link *iter; 37 struct ref *ref; 38 int index; 39 40 index = 0; 41 for (LIST_ITER(list, iter)) { 42 ref = LIST_UPCAST(iter, struct ref, link); 43 if (ref->data == data) 44 return index; 45 index++; 46 } 47 48 return -1; 49} 50 51struct list_link * 52refs_find(struct list *list, void *data) 53{ 54 struct list_link *iter; 55 struct ref *ref; 56 57 for (LIST_ITER(list, iter)) { 58 ref = LIST_UPCAST(iter, struct ref, link); 59 if (ref->data == data) 60 return iter; 61 } 62 63 return NULL; 64} 65 66int 67refs_incl(struct list *list, void *data) 68{ 69 struct list_link *ref; 70 71 ref = refs_find(list, data); 72 73 return ref != NULL; 74} 75 76void 77refs_rm(struct list *list, void *data) 78{ 79 struct list_link *ref; 80 struct ref *dataref; 81 82 ref = refs_find(list, data); 83 if (!ref) return; 84 85 dataref = LIST_UPCAST(ref, struct ref, link); 86 list_link_pop(ref); 87 free(dataref); 88} 89