1 /* Hash Tables Implementation.
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... :)
8 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions are met:
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.
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.
48 /* Using dictEnableResize() / dictDisableResize() we make possible to
49 * enable/disable resizing of the hash table as needed. This is very important
50 * for Redis, as we use copy-on-write and don't want to move too much memory
51 * around when there is a child performing saving operations. */
52 static int dict_can_resize
= 1;
54 /* ---------------------------- Utility funcitons --------------------------- */
56 static void _dictPanic(const char *fmt
, ...)
61 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
62 vfprintf(stderr
, fmt
, ap
);
63 fprintf(stderr
, "\n\n");
67 /* ------------------------- Heap Management Wrappers------------------------ */
69 static void *_dictAlloc(size_t size
)
71 void *p
= zmalloc(size
);
73 _dictPanic("Out of memory");
77 static void _dictFree(void *ptr
) {
81 /* -------------------------- private prototypes ---------------------------- */
83 static int _dictExpandIfNeeded(dict
*ht
);
84 static unsigned long _dictNextPower(unsigned long size
);
85 static int _dictKeyIndex(dict
*ht
, const void *key
);
86 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
88 /* -------------------------- hash functions -------------------------------- */
90 /* Thomas Wang's 32 bit Mix Function */
91 unsigned int dictIntHashFunction(unsigned int key
)
102 /* Identity hash function for integer keys */
103 unsigned int dictIdentityHashFunction(unsigned int key
)
108 /* Generic hash function (a popular one from Bernstein).
109 * I tested a few and this was the best. */
110 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
111 unsigned int hash
= 5381;
114 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
118 /* ----------------------------- API implementation ------------------------- */
120 /* Reset an hashtable already initialized with ht_init().
121 * NOTE: This function should only called by ht_destroy(). */
122 static void _dictReset(dict
*ht
)
130 /* Create a new hash table */
131 dict
*dictCreate(dictType
*type
,
134 dict
*ht
= _dictAlloc(sizeof(*ht
));
136 _dictInit(ht
,type
,privDataPtr
);
140 /* Initialize the hash table */
141 int _dictInit(dict
*ht
, dictType
*type
,
146 ht
->privdata
= privDataPtr
;
150 /* Resize the table to the minimal size that contains all the elements,
151 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
152 int dictResize(dict
*ht
)
154 int minimal
= ht
->used
;
156 if (!dict_can_resize
) return DICT_ERR
;
157 if (minimal
< DICT_HT_INITIAL_SIZE
)
158 minimal
= DICT_HT_INITIAL_SIZE
;
159 return dictExpand(ht
, minimal
);
162 /* Expand or create the hashtable */
163 int dictExpand(dict
*ht
, unsigned long size
)
165 dict n
; /* the new hashtable */
166 unsigned long realsize
= _dictNextPower(size
), i
;
168 /* the size is invalid if it is smaller than the number of
169 * elements already inside the hashtable */
173 _dictInit(&n
, ht
->type
, ht
->privdata
);
175 n
.sizemask
= realsize
-1;
176 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
178 /* Initialize all the pointers to NULL */
179 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
181 /* Copy all the elements from the old to the new table:
182 * note that if the old hash table is empty ht->size is zero,
183 * so dictExpand just creates an hash table. */
185 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
186 dictEntry
*he
, *nextHe
;
188 if (ht
->table
[i
] == NULL
) continue;
190 /* For each hash entry on this slot... */
196 /* Get the new element index */
197 h
= dictHashKey(ht
, he
->key
) & n
.sizemask
;
198 he
->next
= n
.table
[h
];
201 /* Pass to the next element */
205 assert(ht
->used
== 0);
206 _dictFree(ht
->table
);
208 /* Remap the new hashtable in the old */
213 /* Add an element to the target hash table */
214 int dictAdd(dict
*ht
, void *key
, void *val
)
219 /* Get the index of the new element, or -1 if
220 * the element already exists. */
221 if ((index
= _dictKeyIndex(ht
, key
)) == -1)
224 /* Allocates the memory and stores key */
225 entry
= _dictAlloc(sizeof(*entry
));
226 entry
->next
= ht
->table
[index
];
227 ht
->table
[index
] = entry
;
229 /* Set the hash entry fields. */
230 dictSetHashKey(ht
, entry
, key
);
231 dictSetHashVal(ht
, entry
, val
);
236 /* Add an element, discarding the old if the key already exists.
237 * Return 1 if the key was added from scratch, 0 if there was already an
238 * element with such key and dictReplace() just performed a value update
240 int dictReplace(dict
*ht
, void *key
, void *val
)
242 dictEntry
*entry
, auxentry
;
244 /* Try to add the element. If the key
245 * does not exists dictAdd will suceed. */
246 if (dictAdd(ht
, key
, val
) == DICT_OK
)
248 /* It already exists, get the entry */
249 entry
= dictFind(ht
, key
);
250 /* Free the old value and set the new one */
251 /* Set the new value and free the old one. Note that it is important
252 * to do that in this order, as the value may just be exactly the same
253 * as the previous one. In this context, think to reference counting,
254 * you want to increment (set), and then decrement (free), and not the
257 dictSetHashVal(ht
, entry
, val
);
258 dictFreeEntryVal(ht
, &auxentry
);
262 /* Search and remove an element */
263 static int dictGenericDelete(dict
*ht
, const void *key
, int nofree
)
266 dictEntry
*he
, *prevHe
;
270 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
275 if (dictCompareHashKeys(ht
, key
, he
->key
)) {
276 /* Unlink the element from the list */
278 prevHe
->next
= he
->next
;
280 ht
->table
[h
] = he
->next
;
282 dictFreeEntryKey(ht
, he
);
283 dictFreeEntryVal(ht
, he
);
292 return DICT_ERR
; /* not found */
295 int dictDelete(dict
*ht
, const void *key
) {
296 return dictGenericDelete(ht
,key
,0);
299 int dictDeleteNoFree(dict
*ht
, const void *key
) {
300 return dictGenericDelete(ht
,key
,1);
303 /* Destroy an entire hash table */
304 int _dictClear(dict
*ht
)
308 /* Free all the elements */
309 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
310 dictEntry
*he
, *nextHe
;
312 if ((he
= ht
->table
[i
]) == NULL
) continue;
315 dictFreeEntryKey(ht
, he
);
316 dictFreeEntryVal(ht
, he
);
322 /* Free the table and the allocated cache structure */
323 _dictFree(ht
->table
);
324 /* Re-initialize the table */
326 return DICT_OK
; /* never fails */
329 /* Clear & Release the hash table */
330 void dictRelease(dict
*ht
)
336 dictEntry
*dictFind(dict
*ht
, const void *key
)
341 if (ht
->size
== 0) return NULL
;
342 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
345 if (dictCompareHashKeys(ht
, key
, he
->key
))
352 dictIterator
*dictGetIterator(dict
*ht
)
354 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
359 iter
->nextEntry
= NULL
;
363 dictEntry
*dictNext(dictIterator
*iter
)
366 if (iter
->entry
== NULL
) {
369 (signed)iter
->ht
->size
) break;
370 iter
->entry
= iter
->ht
->table
[iter
->index
];
372 iter
->entry
= iter
->nextEntry
;
375 /* We need to save the 'next' here, the iterator user
376 * may delete the entry we are returning. */
377 iter
->nextEntry
= iter
->entry
->next
;
384 void dictReleaseIterator(dictIterator
*iter
)
389 /* Return a random entry from the hash table. Useful to
390 * implement randomized algorithms */
391 dictEntry
*dictGetRandomKey(dict
*ht
)
395 int listlen
, listele
;
397 if (ht
->used
== 0) return NULL
;
399 h
= random() & ht
->sizemask
;
403 /* Now we found a non empty bucket, but it is a linked
404 * list and we need to get a random element from the list.
405 * The only sane way to do so is to count the element and
406 * select a random index. */
412 listele
= random() % listlen
;
414 while(listele
--) he
= he
->next
;
418 /* ------------------------- private functions ------------------------------ */
420 /* Expand the hash table if needed */
421 static int _dictExpandIfNeeded(dict
*ht
)
423 /* If the hash table is empty expand it to the intial size,
424 * if the table is "full" dobule its size. */
426 return dictExpand(ht
, DICT_HT_INITIAL_SIZE
);
427 if (ht
->used
>= ht
->size
&& dict_can_resize
)
428 return dictExpand(ht
, ht
->size
*2);
432 /* Our hash table capability is a power of two */
433 static unsigned long _dictNextPower(unsigned long size
)
435 unsigned long i
= DICT_HT_INITIAL_SIZE
;
437 if (size
>= LONG_MAX
) return LONG_MAX
;
445 /* Returns the index of a free slot that can be populated with
446 * an hash entry for the given 'key'.
447 * If the key already exists, -1 is returned. */
448 static int _dictKeyIndex(dict
*ht
, const void *key
)
453 /* Expand the hashtable if needed */
454 if (_dictExpandIfNeeded(ht
) == DICT_ERR
)
456 /* Compute the key hash value */
457 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
458 /* Search if this slot does not already contain the given key */
461 if (dictCompareHashKeys(ht
, key
, he
->key
))
468 void dictEmpty(dict
*ht
) {
472 #define DICT_STATS_VECTLEN 50
473 void dictPrintStats(dict
*ht
) {
474 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
475 unsigned long totchainlen
= 0;
476 unsigned long clvector
[DICT_STATS_VECTLEN
];
479 printf("No stats available for empty dictionaries\n");
483 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
484 for (i
= 0; i
< ht
->size
; i
++) {
487 if (ht
->table
[i
] == NULL
) {
492 /* For each hash entry on this slot... */
499 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
500 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
501 totchainlen
+= chainlen
;
503 printf("Hash table stats:\n");
504 printf(" table size: %ld\n", ht
->size
);
505 printf(" number of elements: %ld\n", ht
->used
);
506 printf(" different slots: %ld\n", slots
);
507 printf(" max chain length: %ld\n", maxchainlen
);
508 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
509 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
510 printf(" Chain length distribution:\n");
511 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
512 if (clvector
[i
] == 0) continue;
513 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
517 void dictEnableResize(void) {
521 void dictDisableResize(void) {
525 /* ----------------------- StringCopy Hash Table Type ------------------------*/
527 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
529 return dictGenHashFunction(key
, strlen(key
));
532 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
534 int len
= strlen(key
);
535 char *copy
= _dictAlloc(len
+1);
536 DICT_NOTUSED(privdata
);
538 memcpy(copy
, key
, len
);
543 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
545 int len
= strlen(val
);
546 char *copy
= _dictAlloc(len
+1);
547 DICT_NOTUSED(privdata
);
549 memcpy(copy
, val
, len
);
554 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
557 DICT_NOTUSED(privdata
);
559 return strcmp(key1
, key2
) == 0;
562 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
564 DICT_NOTUSED(privdata
);
566 _dictFree((void*)key
); /* ATTENTION: const cast */
569 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
571 DICT_NOTUSED(privdata
);
573 _dictFree((void*)val
); /* ATTENTION: const cast */
576 dictType dictTypeHeapStringCopyKey
= {
577 _dictStringCopyHTHashFunction
, /* hash function */
578 _dictStringCopyHTKeyDup
, /* key dup */
580 _dictStringCopyHTKeyCompare
, /* key compare */
581 _dictStringCopyHTKeyDestructor
, /* key destructor */
582 NULL
/* val destructor */
585 /* This is like StringCopy but does not auto-duplicate the key.
586 * It's used for intepreter's shared strings. */
587 dictType dictTypeHeapStrings
= {
588 _dictStringCopyHTHashFunction
, /* hash function */
591 _dictStringCopyHTKeyCompare
, /* key compare */
592 _dictStringCopyHTKeyDestructor
, /* key destructor */
593 NULL
/* val destructor */
596 /* This is like StringCopy but also automatically handle dynamic
597 * allocated C strings as values. */
598 dictType dictTypeHeapStringCopyKeyValue
= {
599 _dictStringCopyHTHashFunction
, /* hash function */
600 _dictStringCopyHTKeyDup
, /* key dup */
601 _dictStringKeyValCopyHTValDup
, /* val dup */
602 _dictStringCopyHTKeyCompare
, /* key compare */
603 _dictStringCopyHTKeyDestructor
, /* key destructor */
604 _dictStringKeyValCopyHTValDestructor
, /* val destructor */