set_u64p.c (1523B)
1 #include "set_u64p.h" 2 3 void set_u64p_init_size(set_u64p_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_u64p_init(set_u64p_t *s) { 15 set_u64p_init_size(s, SET_U64_DEFAULT_SIZE); 16 } 17 18 void set_u64p_clear(set_u64p_t *s) { 19 size_t i; 20 struct list_entry *n1; 21 22 for (i = 0; i < s->nalloc; i++) { 23 while (!LIST_EMPTY(&(s->head[i]))) { 24 n1 = LIST_FIRST(&(s->head[i])); 25 LIST_REMOVE(n1, entries); 26 free(n1); 27 } 28 } 29 30 free(s->head); 31 s->head = NULL; 32 s->nalloc = 0; 33 s->nelts = 0; 34 } 35 36 static inline size_t u64p_hash(const uint64_t *pair) { 37 return (size_t)(pair[0] ^ pair[1]); 38 } 39 40 static inline le_t *list_lookup(struct lh_u64p h, uint64_t *pair) { 41 le_t *np; 42 LIST_FOREACH(np, &h, entries) { 43 if (np->v[0] == pair[0] && np->v[1] == pair[1]) 44 return np; 45 } 46 47 return NULL; 48 } 49 50 size_t set_u64p_lookup(le_t *r, set_u64p_t *s, uint64_t *pair) { 51 size_t i = u64p_hash(pair) % s->nalloc; 52 le_t *elt = list_lookup(s->head[i], pair); 53 54 if (elt != NULL) { 55 *r = *elt; 56 return i; 57 } 58 59 return SIZE_MAX; 60 } 61 62 int set_u64p_insert(set_u64p_t *s, uint64_t *pair) { 63 size_t i = u64p_hash(pair) % s->nalloc; 64 65 if (list_lookup(s->head[i], pair) == NULL) { 66 le_t *new = malloc(sizeof(*new)); 67 new->v[0] = pair[0]; 68 new->v[1] = pair[1]; 69 LIST_INSERT_HEAD(&(s->head[i]), new, entries); 70 s->nelts++; 71 return 1; 72 } 73 74 return 0; 75 }