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-2009, 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.
45 /* ---------------------------- Utility funcitons --------------------------- */
47 static void _dictPanic(const char *fmt
, ...)
52 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
53 vfprintf(stderr
, fmt
, ap
);
54 fprintf(stderr
, "\n\n");
58 /* ------------------------- Heap Management Wrappers------------------------ */
60 static void *_dictAlloc(int size
)
62 void *p
= zmalloc(size
);
64 _dictPanic("Out of memory");
68 static void _dictFree(void *ptr
) {
72 /* -------------------------- private prototypes ---------------------------- */
74 static int _dictExpandIfNeeded(dict
*ht
);
75 static unsigned int _dictNextPower(unsigned int size
);
76 static int _dictKeyIndex(dict
*ht
, const void *key
);
77 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
79 /* -------------------------- hash functions -------------------------------- */
81 /* Thomas Wang's 32 bit Mix Function */
82 unsigned int dictIntHashFunction(unsigned int key
)
93 /* Identity hash function for integer keys */
94 unsigned int dictIdentityHashFunction(unsigned int key
)
99 /* Generic hash function (a popular one from Bernstein).
100 * I tested a few and this was the best. */
101 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
102 unsigned int hash
= 5381;
105 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
109 /* ----------------------------- API implementation ------------------------- */
111 /* Reset an hashtable already initialized with ht_init().
112 * NOTE: This function should only called by ht_destroy(). */
113 static void _dictReset(dict
*ht
)
121 /* Create a new hash table */
122 dict
*dictCreate(dictType
*type
,
125 dict
*ht
= _dictAlloc(sizeof(*ht
));
127 _dictInit(ht
,type
,privDataPtr
);
131 /* Initialize the hash table */
132 int _dictInit(dict
*ht
, dictType
*type
,
137 ht
->privdata
= privDataPtr
;
141 /* Resize the table to the minimal size that contains all the elements,
142 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
143 int dictResize(dict
*ht
)
145 int minimal
= ht
->used
;
147 if (minimal
< DICT_HT_INITIAL_SIZE
)
148 minimal
= DICT_HT_INITIAL_SIZE
;
149 return dictExpand(ht
, minimal
);
152 /* Expand or create the hashtable */
153 int dictExpand(dict
*ht
, unsigned int size
)
155 dict n
; /* the new hashtable */
156 unsigned int realsize
= _dictNextPower(size
), i
;
158 /* the size is invalid if it is smaller than the number of
159 * elements already inside the hashtable */
163 _dictInit(&n
, ht
->type
, ht
->privdata
);
165 n
.sizemask
= realsize
-1;
166 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
168 /* Initialize all the pointers to NULL */
169 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
171 /* Copy all the elements from the old to the new table:
172 * note that if the old hash table is empty ht->size is zero,
173 * so dictExpand just creates an hash table. */
175 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
176 dictEntry
*he
, *nextHe
;
178 if (ht
->table
[i
] == NULL
) continue;
180 /* For each hash entry on this slot... */
186 /* Get the new element index */
187 h
= dictHashKey(ht
, he
->key
) & n
.sizemask
;
188 he
->next
= n
.table
[h
];
191 /* Pass to the next element */
195 assert(ht
->used
== 0);
196 _dictFree(ht
->table
);
198 /* Remap the new hashtable in the old */
203 /* Add an element to the target hash table */
204 int dictAdd(dict
*ht
, void *key
, void *val
)
209 /* Get the index of the new element, or -1 if
210 * the element already exists. */
211 if ((index
= _dictKeyIndex(ht
, key
)) == -1)
214 /* Allocates the memory and stores key */
215 entry
= _dictAlloc(sizeof(*entry
));
216 entry
->next
= ht
->table
[index
];
217 ht
->table
[index
] = entry
;
219 /* Set the hash entry fields. */
220 dictSetHashKey(ht
, entry
, key
);
221 dictSetHashVal(ht
, entry
, val
);
226 /* Add an element, discarding the old if the key already exists */
227 int dictReplace(dict
*ht
, void *key
, void *val
)
231 /* Try to add the element. If the key
232 * does not exists dictAdd will suceed. */
233 if (dictAdd(ht
, key
, val
) == DICT_OK
)
235 /* It already exists, get the entry */
236 entry
= dictFind(ht
, key
);
237 /* Free the old value and set the new one */
238 dictFreeEntryVal(ht
, entry
);
239 dictSetHashVal(ht
, entry
, val
);
243 /* Search and remove an element */
244 static int dictGenericDelete(dict
*ht
, const void *key
, int nofree
)
247 dictEntry
*he
, *prevHe
;
251 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
256 if (dictCompareHashKeys(ht
, key
, he
->key
)) {
257 /* Unlink the element from the list */
259 prevHe
->next
= he
->next
;
261 ht
->table
[h
] = he
->next
;
263 dictFreeEntryKey(ht
, he
);
264 dictFreeEntryVal(ht
, he
);
273 return DICT_ERR
; /* not found */
276 int dictDelete(dict
*ht
, const void *key
) {
277 return dictGenericDelete(ht
,key
,0);
280 int dictDeleteNoFree(dict
*ht
, const void *key
) {
281 return dictGenericDelete(ht
,key
,1);
284 /* Destroy an entire hash table */
285 int _dictClear(dict
*ht
)
289 /* Free all the elements */
290 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
291 dictEntry
*he
, *nextHe
;
293 if ((he
= ht
->table
[i
]) == NULL
) continue;
296 dictFreeEntryKey(ht
, he
);
297 dictFreeEntryVal(ht
, he
);
303 /* Free the table and the allocated cache structure */
304 _dictFree(ht
->table
);
305 /* Re-initialize the table */
307 return DICT_OK
; /* never fails */
310 /* Clear & Release the hash table */
311 void dictRelease(dict
*ht
)
317 dictEntry
*dictFind(dict
*ht
, const void *key
)
322 if (ht
->size
== 0) return NULL
;
323 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
326 if (dictCompareHashKeys(ht
, key
, he
->key
))
333 dictIterator
*dictGetIterator(dict
*ht
)
335 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
340 iter
->nextEntry
= NULL
;
344 dictEntry
*dictNext(dictIterator
*iter
)
347 if (iter
->entry
== NULL
) {
350 (signed)iter
->ht
->size
) break;
351 iter
->entry
= iter
->ht
->table
[iter
->index
];
353 iter
->entry
= iter
->nextEntry
;
356 /* We need to save the 'next' here, the iterator user
357 * may delete the entry we are returning. */
358 iter
->nextEntry
= iter
->entry
->next
;
365 void dictReleaseIterator(dictIterator
*iter
)
370 /* Return a random entry from the hash table. Useful to
371 * implement randomized algorithms */
372 dictEntry
*dictGetRandomKey(dict
*ht
)
376 int listlen
, listele
;
378 if (ht
->size
== 0) return NULL
;
380 h
= random() & ht
->sizemask
;
384 /* Now we found a non empty bucket, but it is a linked
385 * list and we need to get a random element from the list.
386 * The only sane way to do so is to count the element and
387 * select a random index. */
393 listele
= random() % listlen
;
395 while(listele
--) he
= he
->next
;
399 /* ------------------------- private functions ------------------------------ */
401 /* Expand the hash table if needed */
402 static int _dictExpandIfNeeded(dict
*ht
)
404 /* If the hash table is empty expand it to the intial size,
405 * if the table is "full" dobule its size. */
407 return dictExpand(ht
, DICT_HT_INITIAL_SIZE
);
408 if (ht
->used
== ht
->size
)
409 return dictExpand(ht
, ht
->size
*2);
413 /* Our hash table capability is a power of two */
414 static unsigned int _dictNextPower(unsigned int size
)
416 unsigned int i
= DICT_HT_INITIAL_SIZE
;
418 if (size
>= 2147483648U)
427 /* Returns the index of a free slot that can be populated with
428 * an hash entry for the given 'key'.
429 * If the key already exists, -1 is returned. */
430 static int _dictKeyIndex(dict
*ht
, const void *key
)
435 /* Expand the hashtable if needed */
436 if (_dictExpandIfNeeded(ht
) == DICT_ERR
)
438 /* Compute the key hash value */
439 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
440 /* Search if this slot does not already contain the given key */
443 if (dictCompareHashKeys(ht
, key
, he
->key
))
450 void dictEmpty(dict
*ht
) {
454 #define DICT_STATS_VECTLEN 50
455 void dictPrintStats(dict
*ht
) {
456 unsigned int i
, slots
= 0, chainlen
, maxchainlen
= 0;
457 unsigned int totchainlen
= 0;
458 unsigned int clvector
[DICT_STATS_VECTLEN
];
461 printf("No stats available for empty dictionaries\n");
465 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
466 for (i
= 0; i
< ht
->size
; i
++) {
469 if (ht
->table
[i
] == NULL
) {
474 /* For each hash entry on this slot... */
481 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
482 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
483 totchainlen
+= chainlen
;
485 printf("Hash table stats:\n");
486 printf(" table size: %d\n", ht
->size
);
487 printf(" number of elements: %d\n", ht
->used
);
488 printf(" different slots: %d\n", slots
);
489 printf(" max chain length: %d\n", maxchainlen
);
490 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
491 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
492 printf(" Chain length distribution:\n");
493 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
494 if (clvector
[i
] == 0) continue;
495 printf(" %s%d: %d (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
499 /* ----------------------- StringCopy Hash Table Type ------------------------*/
501 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
503 return dictGenHashFunction(key
, strlen(key
));
506 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
508 int len
= strlen(key
);
509 char *copy
= _dictAlloc(len
+1);
510 DICT_NOTUSED(privdata
);
512 memcpy(copy
, key
, len
);
517 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
519 int len
= strlen(val
);
520 char *copy
= _dictAlloc(len
+1);
521 DICT_NOTUSED(privdata
);
523 memcpy(copy
, val
, len
);
528 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
531 DICT_NOTUSED(privdata
);
533 return strcmp(key1
, key2
) == 0;
536 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
538 DICT_NOTUSED(privdata
);
540 _dictFree((void*)key
); /* ATTENTION: const cast */
543 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
545 DICT_NOTUSED(privdata
);
547 _dictFree((void*)val
); /* ATTENTION: const cast */
550 dictType dictTypeHeapStringCopyKey
= {
551 _dictStringCopyHTHashFunction
, /* hash function */
552 _dictStringCopyHTKeyDup
, /* key dup */
554 _dictStringCopyHTKeyCompare
, /* key compare */
555 _dictStringCopyHTKeyDestructor
, /* key destructor */
556 NULL
/* val destructor */
559 /* This is like StringCopy but does not auto-duplicate the key.
560 * It's used for intepreter's shared strings. */
561 dictType dictTypeHeapStrings
= {
562 _dictStringCopyHTHashFunction
, /* hash function */
565 _dictStringCopyHTKeyCompare
, /* key compare */
566 _dictStringCopyHTKeyDestructor
, /* key destructor */
567 NULL
/* val destructor */
570 /* This is like StringCopy but also automatically handle dynamic
571 * allocated C strings as values. */
572 dictType dictTypeHeapStringCopyKeyValue
= {
573 _dictStringCopyHTHashFunction
, /* hash function */
574 _dictStringCopyHTKeyDup
, /* key dup */
575 _dictStringKeyValCopyHTValDup
, /* val dup */
576 _dictStringCopyHTKeyCompare
, /* key compare */
577 _dictStringCopyHTKeyDestructor
, /* key destructor */
578 _dictStringKeyValCopyHTValDestructor
, /* val destructor */