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.
47 /* ---------------------------- Utility funcitons --------------------------- */
49 static void _dictPanic(const char *fmt
, ...)
54 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
55 vfprintf(stderr
, fmt
, ap
);
56 fprintf(stderr
, "\n\n");
60 /* ------------------------- Heap Management Wrappers------------------------ */
62 static void *_dictAlloc(int size
)
64 void *p
= zmalloc(size
);
66 _dictPanic("Out of memory");
70 static void _dictFree(void *ptr
) {
74 /* -------------------------- private prototypes ---------------------------- */
76 static int _dictExpandIfNeeded(dict
*ht
);
77 static unsigned int _dictNextPower(unsigned int size
);
78 static int _dictKeyIndex(dict
*ht
, const void *key
);
79 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
81 /* -------------------------- hash functions -------------------------------- */
83 /* Thomas Wang's 32 bit Mix Function */
84 unsigned int dictIntHashFunction(unsigned int key
)
95 /* Identity hash function for integer keys */
96 unsigned int dictIdentityHashFunction(unsigned int key
)
101 /* Generic hash function (a popular one from Bernstein).
102 * I tested a few and this was the best. */
103 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
104 unsigned int hash
= 5381;
107 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
111 /* ----------------------------- API implementation ------------------------- */
113 /* Reset an hashtable already initialized with ht_init().
114 * NOTE: This function should only called by ht_destroy(). */
115 static void _dictReset(dict
*ht
)
123 /* Create a new hash table */
124 dict
*dictCreate(dictType
*type
,
127 dict
*ht
= _dictAlloc(sizeof(*ht
));
129 _dictInit(ht
,type
,privDataPtr
);
133 /* Initialize the hash table */
134 int _dictInit(dict
*ht
, dictType
*type
,
139 ht
->privdata
= privDataPtr
;
143 /* Resize the table to the minimal size that contains all the elements,
144 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
145 int dictResize(dict
*ht
)
147 int minimal
= ht
->used
;
149 if (minimal
< DICT_HT_INITIAL_SIZE
)
150 minimal
= DICT_HT_INITIAL_SIZE
;
151 return dictExpand(ht
, minimal
);
154 /* Expand or create the hashtable */
155 int dictExpand(dict
*ht
, unsigned int size
)
157 dict n
; /* the new hashtable */
158 unsigned int realsize
= _dictNextPower(size
), i
;
160 /* the size is invalid if it is smaller than the number of
161 * elements already inside the hashtable */
165 _dictInit(&n
, ht
->type
, ht
->privdata
);
167 n
.sizemask
= realsize
-1;
168 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
170 /* Initialize all the pointers to NULL */
171 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
173 /* Copy all the elements from the old to the new table:
174 * note that if the old hash table is empty ht->size is zero,
175 * so dictExpand just creates an hash table. */
177 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
178 dictEntry
*he
, *nextHe
;
180 if (ht
->table
[i
] == NULL
) continue;
182 /* For each hash entry on this slot... */
188 /* Get the new element index */
189 h
= dictHashKey(ht
, he
->key
) & n
.sizemask
;
190 he
->next
= n
.table
[h
];
193 /* Pass to the next element */
197 assert(ht
->used
== 0);
198 _dictFree(ht
->table
);
200 /* Remap the new hashtable in the old */
205 /* Add an element to the target hash table */
206 int dictAdd(dict
*ht
, void *key
, void *val
)
211 /* Get the index of the new element, or -1 if
212 * the element already exists. */
213 if ((index
= _dictKeyIndex(ht
, key
)) == -1)
216 /* Allocates the memory and stores key */
217 entry
= _dictAlloc(sizeof(*entry
));
218 entry
->next
= ht
->table
[index
];
219 ht
->table
[index
] = entry
;
221 /* Set the hash entry fields. */
222 dictSetHashKey(ht
, entry
, key
);
223 dictSetHashVal(ht
, entry
, val
);
228 /* Add an element, discarding the old if the key already exists */
229 int dictReplace(dict
*ht
, void *key
, void *val
)
233 /* Try to add the element. If the key
234 * does not exists dictAdd will suceed. */
235 if (dictAdd(ht
, key
, val
) == DICT_OK
)
237 /* It already exists, get the entry */
238 entry
= dictFind(ht
, key
);
239 /* Free the old value and set the new one */
240 dictFreeEntryVal(ht
, entry
);
241 dictSetHashVal(ht
, entry
, val
);
245 /* Search and remove an element */
246 static int dictGenericDelete(dict
*ht
, const void *key
, int nofree
)
249 dictEntry
*he
, *prevHe
;
253 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
258 if (dictCompareHashKeys(ht
, key
, he
->key
)) {
259 /* Unlink the element from the list */
261 prevHe
->next
= he
->next
;
263 ht
->table
[h
] = he
->next
;
265 dictFreeEntryKey(ht
, he
);
266 dictFreeEntryVal(ht
, he
);
275 return DICT_ERR
; /* not found */
278 int dictDelete(dict
*ht
, const void *key
) {
279 return dictGenericDelete(ht
,key
,0);
282 int dictDeleteNoFree(dict
*ht
, const void *key
) {
283 return dictGenericDelete(ht
,key
,1);
286 /* Destroy an entire hash table */
287 int _dictClear(dict
*ht
)
291 /* Free all the elements */
292 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
293 dictEntry
*he
, *nextHe
;
295 if ((he
= ht
->table
[i
]) == NULL
) continue;
298 dictFreeEntryKey(ht
, he
);
299 dictFreeEntryVal(ht
, he
);
305 /* Free the table and the allocated cache structure */
306 _dictFree(ht
->table
);
307 /* Re-initialize the table */
309 return DICT_OK
; /* never fails */
312 /* Clear & Release the hash table */
313 void dictRelease(dict
*ht
)
319 dictEntry
*dictFind(dict
*ht
, const void *key
)
324 if (ht
->size
== 0) return NULL
;
325 h
= dictHashKey(ht
, key
) & ht
->sizemask
;
328 if (dictCompareHashKeys(ht
, key
, he
->key
))
335 dictIterator
*dictGetIterator(dict
*ht
)
337 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
342 iter
->nextEntry
= NULL
;
346 dictEntry
*dictNext(dictIterator
*iter
)
349 if (iter
->entry
== NULL
) {
352 (signed)iter
->ht
->size
) break;
353 iter
->entry
= iter
->ht
->table
[iter
->index
];
355 iter
->entry
= iter
->nextEntry
;
358 /* We need to save the 'next' here, the iterator user
359 * may delete the entry we are returning. */
360 iter
->nextEntry
= iter
->entry
->next
;
367 void dictReleaseIterator(dictIterator
*iter
)
372 /* Return a random entry from the hash table. Useful to
373 * implement randomized algorithms */
374 dictEntry
*dictGetRandomKey(dict
*ht
)
378 int listlen
, listele
;
380 if (ht
->size
== 0) return NULL
;
382 h
= random() & ht
->sizemask
;
386 /* Now we found a non empty bucket, but it is a linked
387 * list and we need to get a random element from the list.
388 * The only sane way to do so is to count the element and
389 * select a random index. */
395 listele
= random() % listlen
;
397 while(listele
--) he
= he
->next
;
401 /* ------------------------- private functions ------------------------------ */
403 /* Expand the hash table if needed */
404 static int _dictExpandIfNeeded(dict
*ht
)
406 /* If the hash table is empty expand it to the intial size,
407 * if the table is "full" dobule its size. */
409 return dictExpand(ht
, DICT_HT_INITIAL_SIZE
);
410 if (ht
->used
== ht
->size
)
411 return dictExpand(ht
, ht
->size
*2);
415 /* Our hash table capability is a power of two */
416 static unsigned int _dictNextPower(unsigned int size
)
418 unsigned int i
= DICT_HT_INITIAL_SIZE
;
420 if (size
>= 2147483648U)
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. */
432 static int _dictKeyIndex(dict
*ht
, const void *key
)
437 /* Expand the hashtable if needed */
438 if (_dictExpandIfNeeded(ht
) == DICT_ERR
)
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 */
445 if (dictCompareHashKeys(ht
, key
, he
->key
))
452 void dictEmpty(dict
*ht
) {
456 #define DICT_STATS_VECTLEN 50
457 void dictPrintStats(dict
*ht
) {
458 unsigned int i
, slots
= 0, chainlen
, maxchainlen
= 0;
459 unsigned int totchainlen
= 0;
460 unsigned int clvector
[DICT_STATS_VECTLEN
];
463 printf("No stats available for empty dictionaries\n");
467 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
468 for (i
= 0; i
< ht
->size
; i
++) {
471 if (ht
->table
[i
] == NULL
) {
476 /* For each hash entry on this slot... */
483 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
484 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
485 totchainlen
+= chainlen
;
487 printf("Hash table stats:\n");
488 printf(" table size: %d\n", ht
->size
);
489 printf(" number of elements: %d\n", ht
->used
);
490 printf(" different slots: %d\n", slots
);
491 printf(" max chain length: %d\n", maxchainlen
);
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;
497 printf(" %s%d: %d (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
501 /* ----------------------- StringCopy Hash Table Type ------------------------*/
503 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
505 return dictGenHashFunction(key
, strlen(key
));
508 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
510 int len
= strlen(key
);
511 char *copy
= _dictAlloc(len
+1);
512 DICT_NOTUSED(privdata
);
514 memcpy(copy
, key
, len
);
519 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
521 int len
= strlen(val
);
522 char *copy
= _dictAlloc(len
+1);
523 DICT_NOTUSED(privdata
);
525 memcpy(copy
, val
, len
);
530 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
533 DICT_NOTUSED(privdata
);
535 return strcmp(key1
, key2
) == 0;
538 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
540 DICT_NOTUSED(privdata
);
542 _dictFree((void*)key
); /* ATTENTION: const cast */
545 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
547 DICT_NOTUSED(privdata
);
549 _dictFree((void*)val
); /* ATTENTION: const cast */
552 dictType dictTypeHeapStringCopyKey
= {
553 _dictStringCopyHTHashFunction
, /* hash function */
554 _dictStringCopyHTKeyDup
, /* key dup */
556 _dictStringCopyHTKeyCompare
, /* key compare */
557 _dictStringCopyHTKeyDestructor
, /* key destructor */
558 NULL
/* val destructor */
561 /* This is like StringCopy but does not auto-duplicate the key.
562 * It's used for intepreter's shared strings. */
563 dictType dictTypeHeapStrings
= {
564 _dictStringCopyHTHashFunction
, /* hash function */
567 _dictStringCopyHTKeyCompare
, /* key compare */
568 _dictStringCopyHTKeyDestructor
, /* key destructor */
569 NULL
/* val destructor */
572 /* This is like StringCopy but also automatically handle dynamic
573 * allocated C strings as values. */
574 dictType 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 */