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 /* ---------------------------- Utility funcitons --------------------------- */
50 static void _dictPanic(const char *fmt
, ...)
55 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
56 vfprintf(stderr
, fmt
, ap
);
57 fprintf(stderr
, "\n\n");
61 /* ------------------------- Heap Management Wrappers------------------------ */
63 static void *_dictAlloc(size_t size
)
65 void *p
= zmalloc(size
);
67 _dictPanic("Out of memory");
71 static void _dictFree(void *ptr
) {
75 /* -------------------------- private prototypes ---------------------------- */
77 static int _dictExpandIfNeeded(dict
*ht
);
78 static unsigned long _dictNextPower(unsigned long size
);
79 static int _dictKeyIndex(dict
*ht
, const void *key
);
80 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
82 /* -------------------------- hash functions -------------------------------- */
84 /* Thomas Wang's 32 bit Mix Function */
85 unsigned int dictIntHashFunction(unsigned int key
)
96 /* Identity hash function for integer keys */
97 unsigned int dictIdentityHashFunction(unsigned int key
)
102 /* Generic hash function (a popular one from Bernstein).
103 * I tested a few and this was the best. */
104 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
105 unsigned int hash
= 5381;
108 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
112 /* ----------------------------- API implementation ------------------------- */
114 /* Reset an hashtable already initialized with ht_init().
115 * NOTE: This function should only called by ht_destroy(). */
116 static void _dictReset(dict
*ht
)
124 /* Create a new hash table */
125 dict
*dictCreate(dictType
*type
,
128 dict
*ht
= _dictAlloc(sizeof(*ht
));
130 _dictInit(ht
,type
,privDataPtr
);
134 /* Initialize the hash table */
135 int _dictInit(dict
*ht
, dictType
*type
,
140 ht
->privdata
= privDataPtr
;
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 */
146 int dictResize(dict
*ht
)
148 int minimal
= ht
->used
;
150 if (minimal
< DICT_HT_INITIAL_SIZE
)
151 minimal
= DICT_HT_INITIAL_SIZE
;
152 return dictExpand(ht
, minimal
);
155 /* Expand or create the hashtable */
156 int dictExpand(dict
*ht
, unsigned long size
)
158 dict n
; /* the new hashtable */
159 unsigned long realsize
= _dictNextPower(size
), i
;
161 /* the size is invalid if it is smaller than the number of
162 * elements already inside the hashtable */
166 _dictInit(&n
, ht
->type
, ht
->privdata
);
168 n
.sizemask
= realsize
-1;
169 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
171 /* Initialize all the pointers to NULL */
172 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
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. */
178 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
179 dictEntry
*he
, *nextHe
;
181 if (ht
->table
[i
] == NULL
) continue;
183 /* For each hash entry on this slot... */
189 /* Get the new element index */
190 h
= dictHashKey(ht
, he
->key
) & n
.sizemask
;
191 he
->next
= n
.table
[h
];
194 /* Pass to the next element */
198 assert(ht
->used
== 0);
199 _dictFree(ht
->table
);
201 /* Remap the new hashtable in the old */
206 /* Add an element to the target hash table */
207 int dictAdd(dict
*ht
, void *key
, void *val
)
212 /* Get the index of the new element, or -1 if
213 * the element already exists. */
214 if ((index
= _dictKeyIndex(ht
, key
)) == -1)
217 /* Allocates the memory and stores key */
218 entry
= _dictAlloc(sizeof(*entry
));
219 entry
->next
= ht
->table
[index
];
220 ht
->table
[index
] = entry
;
222 /* Set the hash entry fields. */
223 dictSetHashKey(ht
, entry
, key
);
224 dictSetHashVal(ht
, entry
, val
);
229 /* Add an element, discarding the old if the key already exists.
230 * Return 1 if the key was added from scratch, 0 if there was already an
231 * element with such key and dictReplace() just performed a value update
233 int dictReplace(dict
*ht
, void *key
, void *val
)
235 dictEntry
*entry
, auxentry
;
237 /* Try to add the element. If the key
238 * does not exists dictAdd will suceed. */
239 if (dictAdd(ht
, key
, val
) == DICT_OK
)
241 /* It already exists, get the entry */
242 entry
= dictFind(ht
, key
);
243 /* Free the old value and set the new one */
244 /* Set the new value and free the old one. Note that it is important
245 * to do that in this order, as the value may just be exactly the same
246 * as the previous one. In this context, think to reference counting,
247 * you want to increment (set), and then decrement (free), and not the
250 dictSetHashVal(ht
, entry
, val
);
251 dictFreeEntryVal(ht
, &auxentry
);
255 /* Search and remove an element */
256 static int dictGenericDelete(dict
*ht
, const void *key
, int nofree
)
259 dictEntry
*he
, *prevHe
;
263 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
268 if (dictCompareHashKeys(ht
, key
, he
->key
)) {
269 /* Unlink the element from the list */
271 prevHe
->next
= he
->next
;
273 ht
->table
[h
] = he
->next
;
275 dictFreeEntryKey(ht
, he
);
276 dictFreeEntryVal(ht
, he
);
285 return DICT_ERR
; /* not found */
288 int dictDelete(dict
*ht
, const void *key
) {
289 return dictGenericDelete(ht
,key
,0);
292 int dictDeleteNoFree(dict
*ht
, const void *key
) {
293 return dictGenericDelete(ht
,key
,1);
296 /* Destroy an entire hash table */
297 int _dictClear(dict
*ht
)
301 /* Free all the elements */
302 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
303 dictEntry
*he
, *nextHe
;
305 if ((he
= ht
->table
[i
]) == NULL
) continue;
308 dictFreeEntryKey(ht
, he
);
309 dictFreeEntryVal(ht
, he
);
315 /* Free the table and the allocated cache structure */
316 _dictFree(ht
->table
);
317 /* Re-initialize the table */
319 return DICT_OK
; /* never fails */
322 /* Clear & Release the hash table */
323 void dictRelease(dict
*ht
)
329 dictEntry
*dictFind(dict
*ht
, const void *key
)
334 if (ht
->size
== 0) return NULL
;
335 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
338 if (dictCompareHashKeys(ht
, key
, he
->key
))
345 dictIterator
*dictGetIterator(dict
*ht
)
347 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
352 iter
->nextEntry
= NULL
;
356 dictEntry
*dictNext(dictIterator
*iter
)
359 if (iter
->entry
== NULL
) {
362 (signed)iter
->ht
->size
) break;
363 iter
->entry
= iter
->ht
->table
[iter
->index
];
365 iter
->entry
= iter
->nextEntry
;
368 /* We need to save the 'next' here, the iterator user
369 * may delete the entry we are returning. */
370 iter
->nextEntry
= iter
->entry
->next
;
377 void dictReleaseIterator(dictIterator
*iter
)
382 /* Return a random entry from the hash table. Useful to
383 * implement randomized algorithms */
384 dictEntry
*dictGetRandomKey(dict
*ht
)
388 int listlen
, listele
;
390 if (ht
->used
== 0) return NULL
;
392 h
= random() & ht
->sizemask
;
396 /* Now we found a non empty bucket, but it is a linked
397 * list and we need to get a random element from the list.
398 * The only sane way to do so is to count the element and
399 * select a random index. */
405 listele
= random() % listlen
;
407 while(listele
--) he
= he
->next
;
411 /* ------------------------- private functions ------------------------------ */
413 /* Expand the hash table if needed */
414 static int _dictExpandIfNeeded(dict
*ht
)
416 /* If the hash table is empty expand it to the intial size,
417 * if the table is "full" dobule its size. */
419 return dictExpand(ht
, DICT_HT_INITIAL_SIZE
);
420 if (ht
->used
== ht
->size
)
421 return dictExpand(ht
, ht
->size
*2);
425 /* Our hash table capability is a power of two */
426 static unsigned long _dictNextPower(unsigned long size
)
428 unsigned long i
= DICT_HT_INITIAL_SIZE
;
430 if (size
>= LONG_MAX
) return LONG_MAX
;
438 /* Returns the index of a free slot that can be populated with
439 * an hash entry for the given 'key'.
440 * If the key already exists, -1 is returned. */
441 static int _dictKeyIndex(dict
*ht
, const void *key
)
446 /* Expand the hashtable if needed */
447 if (_dictExpandIfNeeded(ht
) == DICT_ERR
)
449 /* Compute the key hash value */
450 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
451 /* Search if this slot does not already contain the given key */
454 if (dictCompareHashKeys(ht
, key
, he
->key
))
461 void dictEmpty(dict
*ht
) {
465 #define DICT_STATS_VECTLEN 50
466 void dictPrintStats(dict
*ht
) {
467 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
468 unsigned long totchainlen
= 0;
469 unsigned long clvector
[DICT_STATS_VECTLEN
];
472 printf("No stats available for empty dictionaries\n");
476 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
477 for (i
= 0; i
< ht
->size
; i
++) {
480 if (ht
->table
[i
] == NULL
) {
485 /* For each hash entry on this slot... */
492 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
493 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
494 totchainlen
+= chainlen
;
496 printf("Hash table stats:\n");
497 printf(" table size: %ld\n", ht
->size
);
498 printf(" number of elements: %ld\n", ht
->used
);
499 printf(" different slots: %ld\n", slots
);
500 printf(" max chain length: %ld\n", maxchainlen
);
501 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
502 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
503 printf(" Chain length distribution:\n");
504 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
505 if (clvector
[i
] == 0) continue;
506 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
510 /* ----------------------- StringCopy Hash Table Type ------------------------*/
512 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
514 return dictGenHashFunction(key
, strlen(key
));
517 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
519 int len
= strlen(key
);
520 char *copy
= _dictAlloc(len
+1);
521 DICT_NOTUSED(privdata
);
523 memcpy(copy
, key
, len
);
528 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
530 int len
= strlen(val
);
531 char *copy
= _dictAlloc(len
+1);
532 DICT_NOTUSED(privdata
);
534 memcpy(copy
, val
, len
);
539 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
542 DICT_NOTUSED(privdata
);
544 return strcmp(key1
, key2
) == 0;
547 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
549 DICT_NOTUSED(privdata
);
551 _dictFree((void*)key
); /* ATTENTION: const cast */
554 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
556 DICT_NOTUSED(privdata
);
558 _dictFree((void*)val
); /* ATTENTION: const cast */
561 dictType dictTypeHeapStringCopyKey
= {
562 _dictStringCopyHTHashFunction
, /* hash function */
563 _dictStringCopyHTKeyDup
, /* key dup */
565 _dictStringCopyHTKeyCompare
, /* key compare */
566 _dictStringCopyHTKeyDestructor
, /* key destructor */
567 NULL
/* val destructor */
570 /* This is like StringCopy but does not auto-duplicate the key.
571 * It's used for intepreter's shared strings. */
572 dictType dictTypeHeapStrings
= {
573 _dictStringCopyHTHashFunction
, /* hash function */
576 _dictStringCopyHTKeyCompare
, /* key compare */
577 _dictStringCopyHTKeyDestructor
, /* key destructor */
578 NULL
/* val destructor */
581 /* This is like StringCopy but also automatically handle dynamic
582 * allocated C strings as values. */
583 dictType dictTypeHeapStringCopyKeyValue
= {
584 _dictStringCopyHTHashFunction
, /* hash function */
585 _dictStringCopyHTKeyDup
, /* key dup */
586 _dictStringKeyValCopyHTValDup
, /* val dup */
587 _dictStringCopyHTKeyCompare
, /* key compare */
588 _dictStringCopyHTKeyDestructor
, /* key destructor */
589 _dictStringKeyValCopyHTValDestructor
, /* val destructor */