ref: 7e91f1538aa559da9f3b6a479c2d4227d6be9c38
dir: /htable.c/
/*
functions common to all hash table instantiations
*/
#include "flisp.h"
#include "htable.h"
#include "hashing.h"
htable_t *
htable_new(htable_t *h, size_t size)
{
if(size <= HT_N_INLINE/2){
size = HT_N_INLINE;
h->table = &h->_space[0];
}else{
size = nextipow2(size);
size *= 2; // 2 pointers per key/value pair
size *= 2; // aim for 50% occupancy
if((h->table = MEM_ALLOC(size * sizeof(*h->table))) == nil)
return nil;
}
h->size = size;
h->i = 0;
for(size_t i = 0; i < size; i++)
h->table[i] = HT_NOTFOUND;
return h;
}
void
htable_free(htable_t *h)
{
if(h->table != &h->_space[0])
MEM_FREE(h->table);
}
// empty and reduce size
void
htable_reset(htable_t *h, size_t sz)
{
sz = nextipow2(sz);
if(h->size > sz*4 && h->table != &h->_space[0]){
MEM_FREE(h->table);
htable_new(h, sz);
}else{
for(size_t i = 0, hsz = h->size; i < hsz; i++)
h->table[i] = HT_NOTFOUND;
}
}