int hash_add(hash *h, const char *key, const unsigned int len, void *value) { struct record *recs; int rc; unsigned int off, ind, size, code; if (key == NULL) return -2; if (h->records_count > sizes[h->size_index] * load_factor) { rc = hash_grow(h); if (rc) return rc; } code = vechash(key,len); recs = h->records; size = sizes[h->size_index]; ind = code % size; off = 0; while (recs[ind].key) ind = (code + (int)pow(++off,2)) % size; recs[ind].hash = code; recs[ind].key = key; recs[ind].len = len; recs[ind].value = value; h->records_count++; return 0; }
int hash_add(hash *h, uint64_t key, char *value, time_t lifetime) { int rc; char tmp[30]; struct record *recs; unsigned int off, ind, size, code; if (key <= 0 ) return -2; if (h->records_count > sizes[h->size_index] * load_factor) { rc = hash_grow(h); if (rc) return rc; } memset(&tmp, 0, sizeof(tmp)); snprintf(tmp, sizeof(tmp), "%llu", key); recs = h->records; size = sizes[h->size_index]; code = stringhash(tmp); ind = code % size; off = 0; rc = 1; while (recs[ind].key) { rc = _timeout(recs[ind].lifetime); if(!rc) { //超时的记录 h->records_count--; break; } if(key == recs[ind].key) { return 0; } ind = (code + (int)pow(++off,2)) % size; } recs[ind].key = key; recs[ind].lifetime = lifetime; memcpy(recs[ind].value, value, sizeof(recs[ind].value)); h->records_count++; return 1; }
static int hash_put(hash_t *hash, uint32_t code) { int bucket_i = code & (hash->size / HASH_BUCKET_SIZE - 1); uint32_t *bucket = hash->codes + (bucket_i * HASH_BUCKET_SIZE); int i; for (i = 0; i < HASH_BUCKET_SIZE; i++, bucket++) { if (*bucket == 0) { *bucket = code; return 0; } else if (*bucket == code) { return 1; } } /* The bucket is full. */ hash_grow(hash); hash_put(hash, code); return 0; }