]> git.saurik.com Git - redis.git/blame - dict.c
critical bug about glueoutputbuffers=yes fixed. Under load and with pipelining and...
[redis.git] / dict.c
CommitLineData
ed9b544e 1/* Hash Tables Implementation.
2 *
3 * This file implements in memory hash tables with insert/del/replace/find/
4 * get-random-element operations. Hash tables will auto resize if needed
5 * tables of power of two in size are used, collisions are handled by
6 * chaining. See the source code for more information... :)
7 *
8 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
9 * All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions are met:
13 *
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * * Neither the name of Redis nor the names of its contributors may be used
20 * to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
34 */
35
23d4709d 36#include "fmacros.h"
37
ed9b544e 38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <stdarg.h>
42#include <assert.h>
f2923bec 43#include <limits.h>
ed9b544e 44
45#include "dict.h"
46#include "zmalloc.h"
47
48/* ---------------------------- Utility funcitons --------------------------- */
49
50static void _dictPanic(const char *fmt, ...)
51{
52 va_list ap;
53
54 va_start(ap, fmt);
55 fprintf(stderr, "\nDICT LIBRARY PANIC: ");
56 vfprintf(stderr, fmt, ap);
57 fprintf(stderr, "\n\n");
58 va_end(ap);
59}
60
61/* ------------------------- Heap Management Wrappers------------------------ */
62
71aee3e9 63static void *_dictAlloc(size_t size)
ed9b544e 64{
65 void *p = zmalloc(size);
66 if (p == NULL)
67 _dictPanic("Out of memory");
68 return p;
69}
70
71static void _dictFree(void *ptr) {
72 zfree(ptr);
73}
74
75/* -------------------------- private prototypes ---------------------------- */
76
77static int _dictExpandIfNeeded(dict *ht);
f2923bec 78static unsigned long _dictNextPower(unsigned long size);
ed9b544e 79static int _dictKeyIndex(dict *ht, const void *key);
80static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
81
82/* -------------------------- hash functions -------------------------------- */
83
84/* Thomas Wang's 32 bit Mix Function */
85unsigned int dictIntHashFunction(unsigned int key)
86{
87 key += ~(key << 15);
88 key ^= (key >> 10);
89 key += (key << 3);
90 key ^= (key >> 6);
91 key += ~(key << 11);
92 key ^= (key >> 16);
93 return key;
94}
95
96/* Identity hash function for integer keys */
97unsigned int dictIdentityHashFunction(unsigned int key)
98{
99 return key;
100}
101
102/* Generic hash function (a popular one from Bernstein).
103 * I tested a few and this was the best. */
104unsigned int dictGenHashFunction(const unsigned char *buf, int len) {
105 unsigned int hash = 5381;
106
107 while (len--)
108 hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
109 return hash;
110}
111
112/* ----------------------------- API implementation ------------------------- */
113
114/* Reset an hashtable already initialized with ht_init().
115 * NOTE: This function should only called by ht_destroy(). */
116static void _dictReset(dict *ht)
117{
118 ht->table = NULL;
119 ht->size = 0;
120 ht->sizemask = 0;
121 ht->used = 0;
122}
123
124/* Create a new hash table */
125dict *dictCreate(dictType *type,
126 void *privDataPtr)
127{
128 dict *ht = _dictAlloc(sizeof(*ht));
129
130 _dictInit(ht,type,privDataPtr);
131 return ht;
132}
133
134/* Initialize the hash table */
135int _dictInit(dict *ht, dictType *type,
136 void *privDataPtr)
137{
138 _dictReset(ht);
139 ht->type = type;
140 ht->privdata = privDataPtr;
141 return DICT_OK;
142}
143
144/* Resize the table to the minimal size that contains all the elements,
145 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
146int dictResize(dict *ht)
147{
148 int minimal = ht->used;
149
150 if (minimal < DICT_HT_INITIAL_SIZE)
151 minimal = DICT_HT_INITIAL_SIZE;
152 return dictExpand(ht, minimal);
153}
154
155/* Expand or create the hashtable */
f2923bec 156int dictExpand(dict *ht, unsigned long size)
ed9b544e 157{
158 dict n; /* the new hashtable */
f2923bec 159 unsigned long realsize = _dictNextPower(size), i;
ed9b544e 160
161 /* the size is invalid if it is smaller than the number of
162 * elements already inside the hashtable */
163 if (ht->used > size)
164 return DICT_ERR;
165
166 _dictInit(&n, ht->type, ht->privdata);
167 n.size = realsize;
168 n.sizemask = realsize-1;
169 n.table = _dictAlloc(realsize*sizeof(dictEntry*));
170
171 /* Initialize all the pointers to NULL */
172 memset(n.table, 0, realsize*sizeof(dictEntry*));
173
174 /* Copy all the elements from the old to the new table:
175 * note that if the old hash table is empty ht->size is zero,
176 * so dictExpand just creates an hash table. */
177 n.used = ht->used;
178 for (i = 0; i < ht->size && ht->used > 0; i++) {
179 dictEntry *he, *nextHe;
180
181 if (ht->table[i] == NULL) continue;
182
183 /* For each hash entry on this slot... */
184 he = ht->table[i];
185 while(he) {
186 unsigned int h;
187
188 nextHe = he->next;
189 /* Get the new element index */
190 h = dictHashKey(ht, he->key) & n.sizemask;
191 he->next = n.table[h];
192 n.table[h] = he;
193 ht->used--;
194 /* Pass to the next element */
195 he = nextHe;
196 }
197 }
198 assert(ht->used == 0);
199 _dictFree(ht->table);
200
201 /* Remap the new hashtable in the old */
202 *ht = n;
203 return DICT_OK;
204}
205
206/* Add an element to the target hash table */
207int dictAdd(dict *ht, void *key, void *val)
208{
209 int index;
210 dictEntry *entry;
211
212 /* Get the index of the new element, or -1 if
213 * the element already exists. */
214 if ((index = _dictKeyIndex(ht, key)) == -1)
215 return DICT_ERR;
216
217 /* Allocates the memory and stores key */
218 entry = _dictAlloc(sizeof(*entry));
219 entry->next = ht->table[index];
220 ht->table[index] = entry;
221
222 /* Set the hash entry fields. */
223 dictSetHashKey(ht, entry, key);
224 dictSetHashVal(ht, entry, val);
225 ht->used++;
226 return DICT_OK;
227}
228
229/* Add an element, discarding the old if the key already exists */
230int dictReplace(dict *ht, void *key, void *val)
231{
232 dictEntry *entry;
233
234 /* Try to add the element. If the key
235 * does not exists dictAdd will suceed. */
236 if (dictAdd(ht, key, val) == DICT_OK)
237 return DICT_OK;
238 /* It already exists, get the entry */
239 entry = dictFind(ht, key);
240 /* Free the old value and set the new one */
241 dictFreeEntryVal(ht, entry);
242 dictSetHashVal(ht, entry, val);
243 return DICT_OK;
244}
245
246/* Search and remove an element */
247static int dictGenericDelete(dict *ht, const void *key, int nofree)
248{
249 unsigned int h;
250 dictEntry *he, *prevHe;
251
252 if (ht->size == 0)
253 return DICT_ERR;
254 h = dictHashKey(ht, key) & ht->sizemask;
255 he = ht->table[h];
256
257 prevHe = NULL;
258 while(he) {
259 if (dictCompareHashKeys(ht, key, he->key)) {
260 /* Unlink the element from the list */
261 if (prevHe)
262 prevHe->next = he->next;
263 else
264 ht->table[h] = he->next;
265 if (!nofree) {
266 dictFreeEntryKey(ht, he);
267 dictFreeEntryVal(ht, he);
268 }
269 _dictFree(he);
270 ht->used--;
271 return DICT_OK;
272 }
273 prevHe = he;
274 he = he->next;
275 }
276 return DICT_ERR; /* not found */
277}
278
279int dictDelete(dict *ht, const void *key) {
280 return dictGenericDelete(ht,key,0);
281}
282
283int dictDeleteNoFree(dict *ht, const void *key) {
284 return dictGenericDelete(ht,key,1);
285}
286
287/* Destroy an entire hash table */
288int _dictClear(dict *ht)
289{
f2923bec 290 unsigned long i;
ed9b544e 291
292 /* Free all the elements */
293 for (i = 0; i < ht->size && ht->used > 0; i++) {
294 dictEntry *he, *nextHe;
295
296 if ((he = ht->table[i]) == NULL) continue;
297 while(he) {
298 nextHe = he->next;
299 dictFreeEntryKey(ht, he);
300 dictFreeEntryVal(ht, he);
301 _dictFree(he);
302 ht->used--;
303 he = nextHe;
304 }
305 }
306 /* Free the table and the allocated cache structure */
307 _dictFree(ht->table);
308 /* Re-initialize the table */
309 _dictReset(ht);
310 return DICT_OK; /* never fails */
311}
312
313/* Clear & Release the hash table */
314void dictRelease(dict *ht)
315{
316 _dictClear(ht);
317 _dictFree(ht);
318}
319
320dictEntry *dictFind(dict *ht, const void *key)
321{
322 dictEntry *he;
323 unsigned int h;
324
325 if (ht->size == 0) return NULL;
326 h = dictHashKey(ht, key) & ht->sizemask;
327 he = ht->table[h];
328 while(he) {
329 if (dictCompareHashKeys(ht, key, he->key))
330 return he;
331 he = he->next;
332 }
333 return NULL;
334}
335
336dictIterator *dictGetIterator(dict *ht)
337{
338 dictIterator *iter = _dictAlloc(sizeof(*iter));
339
340 iter->ht = ht;
341 iter->index = -1;
342 iter->entry = NULL;
343 iter->nextEntry = NULL;
344 return iter;
345}
346
347dictEntry *dictNext(dictIterator *iter)
348{
349 while (1) {
350 if (iter->entry == NULL) {
351 iter->index++;
352 if (iter->index >=
353 (signed)iter->ht->size) break;
354 iter->entry = iter->ht->table[iter->index];
355 } else {
356 iter->entry = iter->nextEntry;
357 }
358 if (iter->entry) {
359 /* We need to save the 'next' here, the iterator user
360 * may delete the entry we are returning. */
361 iter->nextEntry = iter->entry->next;
362 return iter->entry;
363 }
364 }
365 return NULL;
366}
367
368void dictReleaseIterator(dictIterator *iter)
369{
370 _dictFree(iter);
371}
372
373/* Return a random entry from the hash table. Useful to
374 * implement randomized algorithms */
375dictEntry *dictGetRandomKey(dict *ht)
376{
377 dictEntry *he;
378 unsigned int h;
379 int listlen, listele;
380
6f864e62 381 if (ht->used == 0) return NULL;
ed9b544e 382 do {
383 h = random() & ht->sizemask;
384 he = ht->table[h];
385 } while(he == NULL);
386
387 /* Now we found a non empty bucket, but it is a linked
388 * list and we need to get a random element from the list.
389 * The only sane way to do so is to count the element and
390 * select a random index. */
391 listlen = 0;
392 while(he) {
393 he = he->next;
394 listlen++;
395 }
396 listele = random() % listlen;
397 he = ht->table[h];
398 while(listele--) he = he->next;
399 return he;
400}
401
402/* ------------------------- private functions ------------------------------ */
403
404/* Expand the hash table if needed */
405static int _dictExpandIfNeeded(dict *ht)
406{
407 /* If the hash table is empty expand it to the intial size,
408 * if the table is "full" dobule its size. */
409 if (ht->size == 0)
410 return dictExpand(ht, DICT_HT_INITIAL_SIZE);
411 if (ht->used == ht->size)
412 return dictExpand(ht, ht->size*2);
413 return DICT_OK;
414}
415
416/* Our hash table capability is a power of two */
f2923bec 417static unsigned long _dictNextPower(unsigned long size)
ed9b544e 418{
f2923bec 419 unsigned long i = DICT_HT_INITIAL_SIZE;
ed9b544e 420
f2923bec 421 if (size >= LONG_MAX) return LONG_MAX;
ed9b544e 422 while(1) {
423 if (i >= size)
424 return i;
425 i *= 2;
426 }
427}
428
429/* Returns the index of a free slot that can be populated with
430 * an hash entry for the given 'key'.
431 * If the key already exists, -1 is returned. */
432static int _dictKeyIndex(dict *ht, const void *key)
433{
434 unsigned int h;
435 dictEntry *he;
436
437 /* Expand the hashtable if needed */
438 if (_dictExpandIfNeeded(ht) == DICT_ERR)
439 return -1;
440 /* Compute the key hash value */
441 h = dictHashKey(ht, key) & ht->sizemask;
442 /* Search if this slot does not already contain the given key */
443 he = ht->table[h];
444 while(he) {
445 if (dictCompareHashKeys(ht, key, he->key))
446 return -1;
447 he = he->next;
448 }
449 return h;
450}
451
452void dictEmpty(dict *ht) {
453 _dictClear(ht);
454}
455
456#define DICT_STATS_VECTLEN 50
457void dictPrintStats(dict *ht) {
f2923bec 458 unsigned long i, slots = 0, chainlen, maxchainlen = 0;
459 unsigned long totchainlen = 0;
460 unsigned long clvector[DICT_STATS_VECTLEN];
ed9b544e 461
462 if (ht->used == 0) {
463 printf("No stats available for empty dictionaries\n");
464 return;
465 }
466
467 for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
468 for (i = 0; i < ht->size; i++) {
469 dictEntry *he;
470
471 if (ht->table[i] == NULL) {
472 clvector[0]++;
473 continue;
474 }
475 slots++;
476 /* For each hash entry on this slot... */
477 chainlen = 0;
478 he = ht->table[i];
479 while(he) {
480 chainlen++;
481 he = he->next;
482 }
483 clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
484 if (chainlen > maxchainlen) maxchainlen = chainlen;
485 totchainlen += chainlen;
486 }
487 printf("Hash table stats:\n");
f2923bec 488 printf(" table size: %ld\n", ht->size);
489 printf(" number of elements: %ld\n", ht->used);
490 printf(" different slots: %ld\n", slots);
491 printf(" max chain length: %ld\n", maxchainlen);
ed9b544e 492 printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
493 printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
494 printf(" Chain length distribution:\n");
495 for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
496 if (clvector[i] == 0) continue;
f2923bec 497 printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
ed9b544e 498 }
499}
500
501/* ----------------------- StringCopy Hash Table Type ------------------------*/
502
503static unsigned int _dictStringCopyHTHashFunction(const void *key)
504{
505 return dictGenHashFunction(key, strlen(key));
506}
507
508static void *_dictStringCopyHTKeyDup(void *privdata, const void *key)
509{
510 int len = strlen(key);
511 char *copy = _dictAlloc(len+1);
512 DICT_NOTUSED(privdata);
513
514 memcpy(copy, key, len);
515 copy[len] = '\0';
516 return copy;
517}
518
519static void *_dictStringKeyValCopyHTValDup(void *privdata, const void *val)
520{
521 int len = strlen(val);
522 char *copy = _dictAlloc(len+1);
523 DICT_NOTUSED(privdata);
524
525 memcpy(copy, val, len);
526 copy[len] = '\0';
527 return copy;
528}
529
530static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
531 const void *key2)
532{
533 DICT_NOTUSED(privdata);
534
535 return strcmp(key1, key2) == 0;
536}
537
538static void _dictStringCopyHTKeyDestructor(void *privdata, void *key)
539{
540 DICT_NOTUSED(privdata);
541
542 _dictFree((void*)key); /* ATTENTION: const cast */
543}
544
545static void _dictStringKeyValCopyHTValDestructor(void *privdata, void *val)
546{
547 DICT_NOTUSED(privdata);
548
549 _dictFree((void*)val); /* ATTENTION: const cast */
550}
551
552dictType dictTypeHeapStringCopyKey = {
553 _dictStringCopyHTHashFunction, /* hash function */
554 _dictStringCopyHTKeyDup, /* key dup */
555 NULL, /* val dup */
556 _dictStringCopyHTKeyCompare, /* key compare */
557 _dictStringCopyHTKeyDestructor, /* key destructor */
558 NULL /* val destructor */
559};
560
561/* This is like StringCopy but does not auto-duplicate the key.
562 * It's used for intepreter's shared strings. */
563dictType dictTypeHeapStrings = {
564 _dictStringCopyHTHashFunction, /* hash function */
565 NULL, /* key dup */
566 NULL, /* val dup */
567 _dictStringCopyHTKeyCompare, /* key compare */
568 _dictStringCopyHTKeyDestructor, /* key destructor */
569 NULL /* val destructor */
570};
571
572/* This is like StringCopy but also automatically handle dynamic
573 * allocated C strings as values. */
574dictType dictTypeHeapStringCopyKeyValue = {
575 _dictStringCopyHTHashFunction, /* hash function */
576 _dictStringCopyHTKeyDup, /* key dup */
577 _dictStringKeyValCopyHTValDup, /* val dup */
578 _dictStringCopyHTKeyCompare, /* key compare */
579 _dictStringCopyHTKeyDestructor, /* key destructor */
580 _dictStringKeyValCopyHTValDestructor, /* val destructor */
581};