2008-11-23 02:12:37 -05:00
|
|
|
/*
|
|
|
|
functions common to all hash table instantiations
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <assert.h>
|
|
|
|
#include <limits.h>
|
2019-08-09 12:00:17 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
2008-11-23 02:12:37 -05:00
|
|
|
|
|
|
|
#include "dtypes.h"
|
|
|
|
#include "htable.h"
|
|
|
|
#include "hashing.h"
|
|
|
|
|
2019-08-09 12:26:09 -04:00
|
|
|
struct htable *htable_new(struct htable *h, size_t size)
|
2008-11-23 02:12:37 -05:00
|
|
|
{
|
2019-08-09 07:02:02 -04:00
|
|
|
if (size <= HT_N_INLINE / 2) {
|
2008-12-22 01:36:50 -05:00
|
|
|
h->size = size = HT_N_INLINE;
|
|
|
|
h->table = &h->_space[0];
|
2019-08-09 07:02:02 -04:00
|
|
|
} else {
|
2008-12-22 01:36:50 -05:00
|
|
|
size = nextipow2(size);
|
|
|
|
size *= 2; // 2 pointers per key/value pair
|
|
|
|
size *= 2; // aim for 50% occupancy
|
|
|
|
h->size = size;
|
2019-08-09 07:02:02 -04:00
|
|
|
h->table = (void **)LLT_ALLOC(size * sizeof(void *));
|
2008-12-22 01:36:50 -05:00
|
|
|
}
|
2019-08-09 07:02:02 -04:00
|
|
|
if (h->table == NULL)
|
|
|
|
return NULL;
|
2008-11-23 02:12:37 -05:00
|
|
|
size_t i;
|
2019-08-09 07:02:02 -04:00
|
|
|
for (i = 0; i < size; i++)
|
2008-11-23 02:12:37 -05:00
|
|
|
h->table[i] = HT_NOTFOUND;
|
|
|
|
return h;
|
|
|
|
}
|
|
|
|
|
2019-08-09 12:26:09 -04:00
|
|
|
void htable_free(struct htable *h)
|
2008-11-23 02:12:37 -05:00
|
|
|
{
|
2008-12-22 01:36:50 -05:00
|
|
|
if (h->table != &h->_space[0])
|
2010-02-24 23:37:33 -05:00
|
|
|
LLT_FREE(h->table);
|
2008-11-23 02:12:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// empty and reduce size
|
2019-08-09 12:26:09 -04:00
|
|
|
void htable_reset(struct htable *h, size_t sz)
|
2008-11-23 02:12:37 -05:00
|
|
|
{
|
2008-12-22 01:36:50 -05:00
|
|
|
sz = nextipow2(sz);
|
2019-08-09 07:02:02 -04:00
|
|
|
if (h->size > sz * 4 && h->size > HT_N_INLINE) {
|
|
|
|
size_t newsz = sz * 4;
|
|
|
|
void **newtab =
|
|
|
|
(void **)LLT_REALLOC(h->table, newsz * sizeof(void *));
|
2008-11-23 02:12:37 -05:00
|
|
|
if (newtab == NULL)
|
|
|
|
return;
|
|
|
|
h->size = newsz;
|
|
|
|
h->table = newtab;
|
|
|
|
}
|
2019-08-09 07:02:02 -04:00
|
|
|
size_t i, hsz = h->size;
|
|
|
|
for (i = 0; i < hsz; i++)
|
2008-11-23 02:12:37 -05:00
|
|
|
h->table[i] = HT_NOTFOUND;
|
|
|
|
}
|