set_u64.c (1401B)
1 #include "set_u64.h" 2 3 void set_u64_init_size(set_u64_t *s, const size_t size) { 4 size_t i; 5 s->nalloc = size; 6 s->nelts = 0; 7 8 s->head = malloc((s->nalloc) * sizeof(*(s->head))); 9 10 for (i = 0; i < s->nalloc; i++) 11 LIST_INIT(&(s->head[i])); 12 } 13 14 void set_u64_init(set_u64_t *s) { set_u64_init_size(s, SET_U64_DEFAULT_SIZE); } 15 16 void set_u64_clear(set_u64_t *s) { 17 size_t i; 18 struct list_entry *n1; 19 20 for (i = 0; i < s->nalloc; i++) { 21 while (!LIST_EMPTY(&(s->head[i]))) { 22 n1 = LIST_FIRST(&(s->head[i])); 23 LIST_REMOVE(n1, entries); 24 free(n1); 25 } 26 } 27 28 free(s->head); 29 s->head = NULL; 30 s->nalloc = 0; 31 s->nelts = 0; 32 } 33 34 static inline size_t u64_hash(const uint64_t c) { return (size_t)c; } 35 36 static inline le_t *list_lookup(struct listhead h, uint64_t v) { 37 le_t *np; 38 LIST_FOREACH(np, &h, entries) { 39 if (np->value == v) 40 return np; 41 } 42 43 return NULL; 44 } 45 46 size_t set_u64_lookup(le_t *r, set_u64_t *s, uint64_t v) { 47 size_t i = u64_hash(v) % s->nalloc; 48 le_t *elt = list_lookup(s->head[i], v); 49 50 if (elt != NULL) { 51 *r = *elt; 52 return i; 53 } 54 55 return SIZE_MAX; 56 } 57 58 int set_u64_insert(set_u64_t *s, uint64_t v) { 59 size_t i = u64_hash(v) % s->nalloc; 60 61 if (list_lookup(s->head[i], v) == NULL) { 62 le_t *new = malloc(sizeof(*new)); 63 new->value = v; 64 LIST_INSERT_HEAD(&(s->head[i]), new, entries); 65 s->nelts++; 66 return 1; 67 } 68 69 return 0; 70 }