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.
49 /* Using dictEnableResize() / dictDisableResize() we make possible to
50 * enable/disable resizing of the hash table as needed. This is very important
51 * for Redis, as we use copy-on-write and don't want to move too much memory
52 * around when there is a child performing saving operations. */
53 static int dict_can_resize
= 1;
55 /* ---------------------------- Utility funcitons --------------------------- */
57 static void _dictPanic(const char *fmt
, ...)
62 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
63 vfprintf(stderr
, fmt
, ap
);
64 fprintf(stderr
, "\n\n");
68 /* ------------------------- Heap Management Wrappers------------------------ */
70 static void *_dictAlloc(size_t size
)
72 void *p
= zmalloc(size
);
74 _dictPanic("Out of memory");
78 static void _dictFree(void *ptr
) {
82 /* -------------------------- private prototypes ---------------------------- */
84 static int _dictExpandIfNeeded(dict
*ht
);
85 static unsigned long _dictNextPower(unsigned long size
);
86 static int _dictKeyIndex(dict
*ht
, const void *key
);
87 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
89 /* -------------------------- hash functions -------------------------------- */
91 /* Thomas Wang's 32 bit Mix Function */
92 unsigned int dictIntHashFunction(unsigned int key
)
103 /* Identity hash function for integer keys */
104 unsigned int dictIdentityHashFunction(unsigned int key
)
109 /* Generic hash function (a popular one from Bernstein).
110 * I tested a few and this was the best. */
111 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
112 unsigned int hash
= 5381;
115 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
119 /* ----------------------------- API implementation ------------------------- */
121 /* Reset an hashtable already initialized with ht_init().
122 * NOTE: This function should only called by ht_destroy(). */
123 static void _dictReset(dictht
*ht
)
131 /* Create a new hash table */
132 dict
*dictCreate(dictType
*type
,
135 dict
*d
= _dictAlloc(sizeof(*d
));
137 _dictInit(d
,type
,privDataPtr
);
141 /* Initialize the hash table */
142 int _dictInit(dict
*d
, dictType
*type
,
145 _dictReset(&d
->ht
[0]);
146 _dictReset(&d
->ht
[1]);
148 d
->privdata
= privDataPtr
;
154 /* Resize the table to the minimal size that contains all the elements,
155 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
156 int dictResize(dict
*d
)
160 if (!dict_can_resize
|| dictIsRehashing(d
)) return DICT_ERR
;
161 minimal
= d
->ht
[0].used
;
162 if (minimal
< DICT_HT_INITIAL_SIZE
)
163 minimal
= DICT_HT_INITIAL_SIZE
;
164 return dictExpand(d
, minimal
);
167 /* Expand or create the hashtable */
168 int dictExpand(dict
*d
, unsigned long size
)
170 dictht n
; /* the new hashtable */
171 unsigned long realsize
= _dictNextPower(size
);
173 /* the size is invalid if it is smaller than the number of
174 * elements already inside the hashtable */
175 if (dictIsRehashing(d
) || d
->ht
[0].used
> size
)
179 n
.sizemask
= realsize
-1;
180 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
183 /* Initialize all the pointers to NULL */
184 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
186 /* Is this the first initialization? If so it's not really a rehashing
187 * we just set the first hash table so that it can accept keys. */
188 if (d
->ht
[0].table
== NULL
) {
193 /* Prepare a second hash table for incremental rehashing */
199 /* Performs N steps of incremental rehashing. Returns 1 if there are still
200 * keys to move from the old to the new hash table, otherwise 0 is returned.
201 * Note that a rehashing step consists in moving a bucket (that may have more
202 * thank one key as we use chaining) from the old to the new hash table. */
203 int dictRehash(dict
*d
, int n
) {
204 if (!dictIsRehashing(d
)) return 0;
207 dictEntry
*de
, *nextde
;
209 /* Check if we already rehashed the whole table... */
210 if (d
->ht
[0].used
== 0) {
211 _dictFree(d
->ht
[0].table
);
213 _dictReset(&d
->ht
[1]);
218 /* Note that rehashidx can't overflow as we are sure there are more
219 * elements because ht[0].used != 0 */
220 while(d
->ht
[0].table
[d
->rehashidx
] == NULL
) d
->rehashidx
++;
221 de
= d
->ht
[0].table
[d
->rehashidx
];
222 /* Move all the keys in this bucket from the old to the new hash HT */
227 /* Get the index in the new hash table */
228 h
= dictHashKey(d
, de
->key
) & d
->ht
[1].sizemask
;
229 de
->next
= d
->ht
[1].table
[h
];
230 d
->ht
[1].table
[h
] = de
;
235 d
->ht
[0].table
[d
->rehashidx
] = NULL
;
241 long long timeInMilliseconds(void) {
244 gettimeofday(&tv
,NULL
);
245 return (((long long)tv
.tv_sec
)*1000)+(tv
.tv_usec
/1000);
248 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
249 int dictRehashMilliseconds(dict
*d
, int ms
) {
250 long long start
= timeInMilliseconds();
253 while(dictRehash(d
,100)) {
255 if (timeInMilliseconds()-start
> ms
) break;
260 /* This function performs just a step of rehashing, and only if there are
261 * not iterators bound to our hash table. When we have iterators in the middle
262 * of a rehashing we can't mess with the two hash tables otherwise some element
263 * can be missed or duplicated.
265 * This function is called by common lookup or update operations in the
266 * dictionary so that the hash table automatically migrates from H1 to H2
267 * while it is actively used. */
268 static void _dictRehashStep(dict
*d
) {
269 if (d
->iterators
== 0) dictRehash(d
,1);
272 /* Add an element to the target hash table */
273 int dictAdd(dict
*d
, void *key
, void *val
)
279 if (dictIsRehashing(d
)) _dictRehashStep(d
);
281 /* Get the index of the new element, or -1 if
282 * the element already exists. */
283 if ((index
= _dictKeyIndex(d
, key
)) == -1)
286 /* Allocates the memory and stores key */
287 ht
= dictIsRehashing(d
) ? &d
->ht
[1] : &d
->ht
[0];
288 entry
= _dictAlloc(sizeof(*entry
));
289 entry
->next
= ht
->table
[index
];
290 ht
->table
[index
] = entry
;
293 /* Set the hash entry fields. */
294 dictSetHashKey(d
, entry
, key
);
295 dictSetHashVal(d
, entry
, val
);
299 /* Add an element, discarding the old if the key already exists.
300 * Return 1 if the key was added from scratch, 0 if there was already an
301 * element with such key and dictReplace() just performed a value update
303 int dictReplace(dict
*d
, void *key
, void *val
)
305 dictEntry
*entry
, auxentry
;
307 /* Try to add the element. If the key
308 * does not exists dictAdd will suceed. */
309 if (dictAdd(d
, key
, val
) == DICT_OK
)
311 /* It already exists, get the entry */
312 entry
= dictFind(d
, key
);
313 /* Free the old value and set the new one */
314 /* Set the new value and free the old one. Note that it is important
315 * to do that in this order, as the value may just be exactly the same
316 * as the previous one. In this context, think to reference counting,
317 * you want to increment (set), and then decrement (free), and not the
320 dictSetHashVal(d
, entry
, val
);
321 dictFreeEntryVal(d
, &auxentry
);
325 /* Search and remove an element */
326 static int dictGenericDelete(dict
*d
, const void *key
, int nofree
)
329 dictEntry
*he
, *prevHe
;
332 if (d
->ht
[0].size
== 0) return DICT_ERR
; /* d->ht[0].table is NULL */
333 if (dictIsRehashing(d
)) _dictRehashStep(d
);
334 h
= dictHashKey(d
, key
);
336 for (table
= 0; table
<= 1; table
++) {
337 idx
= h
& d
->ht
[table
].sizemask
;
338 he
= d
->ht
[table
].table
[idx
];
341 if (dictCompareHashKeys(d
, key
, he
->key
)) {
342 /* Unlink the element from the list */
344 prevHe
->next
= he
->next
;
346 d
->ht
[table
].table
[idx
] = he
->next
;
348 dictFreeEntryKey(d
, he
);
349 dictFreeEntryVal(d
, he
);
358 if (!dictIsRehashing(d
)) break;
360 return DICT_ERR
; /* not found */
363 int dictDelete(dict
*ht
, const void *key
) {
364 return dictGenericDelete(ht
,key
,0);
367 int dictDeleteNoFree(dict
*ht
, const void *key
) {
368 return dictGenericDelete(ht
,key
,1);
371 /* Destroy an entire dictionary */
372 int _dictClear(dict
*d
, dictht
*ht
)
376 /* Free all the elements */
377 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
378 dictEntry
*he
, *nextHe
;
380 if ((he
= ht
->table
[i
]) == NULL
) continue;
383 dictFreeEntryKey(d
, he
);
384 dictFreeEntryVal(d
, he
);
390 /* Free the table and the allocated cache structure */
391 _dictFree(ht
->table
);
392 /* Re-initialize the table */
394 return DICT_OK
; /* never fails */
397 /* Clear & Release the hash table */
398 void dictRelease(dict
*d
)
400 _dictClear(d
,&d
->ht
[0]);
401 _dictClear(d
,&d
->ht
[1]);
405 dictEntry
*dictFind(dict
*d
, const void *key
)
408 unsigned int h
, idx
, table
;
410 if (d
->ht
[0].size
== 0) return NULL
; /* We don't have a table at all */
411 if (dictIsRehashing(d
)) _dictRehashStep(d
);
412 h
= dictHashKey(d
, key
);
413 for (table
= 0; table
<= 1; table
++) {
414 idx
= h
& d
->ht
[table
].sizemask
;
415 he
= d
->ht
[table
].table
[idx
];
417 if (dictCompareHashKeys(d
, key
, he
->key
))
421 if (!dictIsRehashing(d
)) return NULL
;
426 void *dictFetchValue(dict
*d
, const void *key
) {
429 he
= dictFind(d
,key
);
430 return he
? dictGetEntryVal(he
) : NULL
;
433 dictIterator
*dictGetIterator(dict
*d
)
435 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
441 iter
->nextEntry
= NULL
;
445 dictEntry
*dictNext(dictIterator
*iter
)
448 if (iter
->entry
== NULL
) {
449 dictht
*ht
= &iter
->d
->ht
[iter
->table
];
450 if (iter
->index
== -1 && iter
->table
== 0) iter
->d
->iterators
++;
452 if (iter
->index
>= (signed) ht
->size
) {
453 if (dictIsRehashing(iter
->d
) && iter
->table
== 0) {
456 ht
= &iter
->d
->ht
[1];
461 iter
->entry
= ht
->table
[iter
->index
];
463 iter
->entry
= iter
->nextEntry
;
466 /* We need to save the 'next' here, the iterator user
467 * may delete the entry we are returning. */
468 iter
->nextEntry
= iter
->entry
->next
;
475 void dictReleaseIterator(dictIterator
*iter
)
477 if (!(iter
->index
== -1 && iter
->table
== 0)) iter
->d
->iterators
--;
481 /* Return a random entry from the hash table. Useful to
482 * implement randomized algorithms */
483 dictEntry
*dictGetRandomKey(dict
*d
)
485 dictEntry
*he
, *orighe
;
487 int listlen
, listele
;
489 if (dictSize(d
) == 0) return NULL
;
490 if (dictIsRehashing(d
)) _dictRehashStep(d
);
491 if (dictIsRehashing(d
)) {
493 h
= random() % (d
->ht
[0].size
+d
->ht
[1].size
);
494 he
= (h
>= d
->ht
[0].size
) ? d
->ht
[1].table
[h
- d
->ht
[0].size
] :
499 h
= random() & d
->ht
[0].sizemask
;
500 he
= d
->ht
[0].table
[h
];
504 /* Now we found a non empty bucket, but it is a linked
505 * list and we need to get a random element from the list.
506 * The only sane way to do so is counting the elements and
507 * select a random index. */
514 listele
= random() % listlen
;
516 while(listele
--) he
= he
->next
;
520 /* ------------------------- private functions ------------------------------ */
522 /* Expand the hash table if needed */
523 static int _dictExpandIfNeeded(dict
*d
)
525 /* If the hash table is empty expand it to the intial size,
526 * if the table is "full" dobule its size. */
527 if (dictIsRehashing(d
)) return DICT_OK
;
528 if (d
->ht
[0].size
== 0)
529 return dictExpand(d
, DICT_HT_INITIAL_SIZE
);
530 if (d
->ht
[0].used
>= d
->ht
[0].size
&& dict_can_resize
)
531 return dictExpand(d
, ((d
->ht
[0].size
> d
->ht
[0].used
) ?
532 d
->ht
[0].size
: d
->ht
[0].used
)*2);
536 /* Our hash table capability is a power of two */
537 static unsigned long _dictNextPower(unsigned long size
)
539 unsigned long i
= DICT_HT_INITIAL_SIZE
;
541 if (size
>= LONG_MAX
) return LONG_MAX
;
549 /* Returns the index of a free slot that can be populated with
550 * an hash entry for the given 'key'.
551 * If the key already exists, -1 is returned.
553 * Note that if we are in the process of rehashing the hash table, the
554 * index is always returned in the context of the second (new) hash table. */
555 static int _dictKeyIndex(dict
*d
, const void *key
)
557 unsigned int h
, idx
, table
;
560 /* Expand the hashtable if needed */
561 if (_dictExpandIfNeeded(d
) == DICT_ERR
)
563 /* Compute the key hash value */
564 h
= dictHashKey(d
, key
);
565 for (table
= 0; table
<= 1; table
++) {
566 idx
= h
& d
->ht
[table
].sizemask
;
567 /* Search if this slot does not already contain the given key */
568 he
= d
->ht
[table
].table
[idx
];
570 if (dictCompareHashKeys(d
, key
, he
->key
))
574 if (!dictIsRehashing(d
)) break;
579 void dictEmpty(dict
*d
) {
580 _dictClear(d
,&d
->ht
[0]);
581 _dictClear(d
,&d
->ht
[1]);
586 #define DICT_STATS_VECTLEN 50
587 static void _dictPrintStatsHt(dictht
*ht
) {
588 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
589 unsigned long totchainlen
= 0;
590 unsigned long clvector
[DICT_STATS_VECTLEN
];
593 printf("No stats available for empty dictionaries\n");
597 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
598 for (i
= 0; i
< ht
->size
; i
++) {
601 if (ht
->table
[i
] == NULL
) {
606 /* For each hash entry on this slot... */
613 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
614 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
615 totchainlen
+= chainlen
;
617 printf("Hash table stats:\n");
618 printf(" table size: %ld\n", ht
->size
);
619 printf(" number of elements: %ld\n", ht
->used
);
620 printf(" different slots: %ld\n", slots
);
621 printf(" max chain length: %ld\n", maxchainlen
);
622 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
623 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
624 printf(" Chain length distribution:\n");
625 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
626 if (clvector
[i
] == 0) continue;
627 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
631 void dictPrintStats(dict
*d
) {
632 _dictPrintStatsHt(&d
->ht
[0]);
633 if (dictIsRehashing(d
)) {
634 printf("-- Rehashing into ht[1]:\n");
635 _dictPrintStatsHt(&d
->ht
[1]);
639 void dictEnableResize(void) {
643 void dictDisableResize(void) {
647 /* ----------------------- StringCopy Hash Table Type ------------------------*/
649 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
651 return dictGenHashFunction(key
, strlen(key
));
654 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
656 int len
= strlen(key
);
657 char *copy
= _dictAlloc(len
+1);
658 DICT_NOTUSED(privdata
);
660 memcpy(copy
, key
, len
);
665 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
667 int len
= strlen(val
);
668 char *copy
= _dictAlloc(len
+1);
669 DICT_NOTUSED(privdata
);
671 memcpy(copy
, val
, len
);
676 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
679 DICT_NOTUSED(privdata
);
681 return strcmp(key1
, key2
) == 0;
684 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
686 DICT_NOTUSED(privdata
);
688 _dictFree((void*)key
); /* ATTENTION: const cast */
691 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
693 DICT_NOTUSED(privdata
);
695 _dictFree((void*)val
); /* ATTENTION: const cast */
698 dictType dictTypeHeapStringCopyKey
= {
699 _dictStringCopyHTHashFunction
, /* hash function */
700 _dictStringCopyHTKeyDup
, /* key dup */
702 _dictStringCopyHTKeyCompare
, /* key compare */
703 _dictStringCopyHTKeyDestructor
, /* key destructor */
704 NULL
/* val destructor */
707 /* This is like StringCopy but does not auto-duplicate the key.
708 * It's used for intepreter's shared strings. */
709 dictType dictTypeHeapStrings
= {
710 _dictStringCopyHTHashFunction
, /* hash function */
713 _dictStringCopyHTKeyCompare
, /* key compare */
714 _dictStringCopyHTKeyDestructor
, /* key destructor */
715 NULL
/* val destructor */
718 /* This is like StringCopy but also automatically handle dynamic
719 * allocated C strings as values. */
720 dictType dictTypeHeapStringCopyKeyValue
= {
721 _dictStringCopyHTHashFunction
, /* hash function */
722 _dictStringCopyHTKeyDup
, /* key dup */
723 _dictStringKeyValCopyHTValDup
, /* val dup */
724 _dictStringCopyHTKeyCompare
, /* key compare */
725 _dictStringCopyHTKeyDestructor
, /* key destructor */
726 _dictStringKeyValCopyHTValDestructor
, /* val destructor */