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.
50 /* Using dictEnableResize() / dictDisableResize() we make possible to
51 * enable/disable resizing of the hash table as needed. This is very important
52 * for Redis, as we use copy-on-write and don't want to move too much memory
53 * around when there is a child performing saving operations.
55 * Note that even when dict_can_resize is set to 0, not all resizes are
56 * prevented: an hash table is still allowed to grow if the ratio between
57 * the number of elements and the buckets > dict_force_resize_ratio. */
58 static int dict_can_resize
= 1;
59 static unsigned int dict_force_resize_ratio
= 5;
61 /* -------------------------- private prototypes ---------------------------- */
63 static int _dictExpandIfNeeded(dict
*ht
);
64 static unsigned long _dictNextPower(unsigned long size
);
65 static int _dictKeyIndex(dict
*ht
, const void *key
);
66 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
68 /* -------------------------- hash functions -------------------------------- */
70 /* Thomas Wang's 32 bit Mix Function */
71 unsigned int dictIntHashFunction(unsigned int key
)
82 /* Identity hash function for integer keys */
83 unsigned int dictIdentityHashFunction(unsigned int key
)
88 /* Generic hash function (a popular one from Bernstein).
89 * I tested a few and this was the best. */
90 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
91 unsigned int hash
= 5381;
94 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
98 /* And a case insensitive version */
99 unsigned int dictGenCaseHashFunction(const unsigned char *buf
, int len
) {
100 unsigned int hash
= 5381;
103 hash
= ((hash
<< 5) + hash
) + (tolower(*buf
++)); /* hash * 33 + c */
107 /* ----------------------------- API implementation ------------------------- */
109 /* Reset an hashtable already initialized with ht_init().
110 * NOTE: This function should only called by ht_destroy(). */
111 static void _dictReset(dictht
*ht
)
119 /* Create a new hash table */
120 dict
*dictCreate(dictType
*type
,
123 dict
*d
= zmalloc(sizeof(*d
));
125 _dictInit(d
,type
,privDataPtr
);
129 /* Initialize the hash table */
130 int _dictInit(dict
*d
, dictType
*type
,
133 _dictReset(&d
->ht
[0]);
134 _dictReset(&d
->ht
[1]);
136 d
->privdata
= privDataPtr
;
142 /* Resize the table to the minimal size that contains all the elements,
143 * but with the invariant of a USER/BUCKETS ratio near to <= 1 */
144 int dictResize(dict
*d
)
148 if (!dict_can_resize
|| dictIsRehashing(d
)) return DICT_ERR
;
149 minimal
= d
->ht
[0].used
;
150 if (minimal
< DICT_HT_INITIAL_SIZE
)
151 minimal
= DICT_HT_INITIAL_SIZE
;
152 return dictExpand(d
, minimal
);
155 /* Expand or create the hashtable */
156 int dictExpand(dict
*d
, unsigned long size
)
158 dictht n
; /* the new hashtable */
159 unsigned long realsize
= _dictNextPower(size
);
161 /* the size is invalid if it is smaller than the number of
162 * elements already inside the hashtable */
163 if (dictIsRehashing(d
) || d
->ht
[0].used
> size
)
166 /* Allocate the new hashtable and initialize all pointers to NULL */
168 n
.sizemask
= realsize
-1;
169 n
.table
= zcalloc(realsize
*sizeof(dictEntry
*));
172 /* Is this the first initialization? If so it's not really a rehashing
173 * we just set the first hash table so that it can accept keys. */
174 if (d
->ht
[0].table
== NULL
) {
179 /* Prepare a second hash table for incremental rehashing */
185 /* Performs N steps of incremental rehashing. Returns 1 if there are still
186 * keys to move from the old to the new hash table, otherwise 0 is returned.
187 * Note that a rehashing step consists in moving a bucket (that may have more
188 * thank one key as we use chaining) from the old to the new hash table. */
189 int dictRehash(dict
*d
, int n
) {
190 if (!dictIsRehashing(d
)) return 0;
193 dictEntry
*de
, *nextde
;
195 /* Check if we already rehashed the whole table... */
196 if (d
->ht
[0].used
== 0) {
197 zfree(d
->ht
[0].table
);
199 _dictReset(&d
->ht
[1]);
204 /* Note that rehashidx can't overflow as we are sure there are more
205 * elements because ht[0].used != 0 */
206 assert(d
->ht
[0].size
> (unsigned)d
->rehashidx
);
207 while(d
->ht
[0].table
[d
->rehashidx
] == NULL
) d
->rehashidx
++;
208 de
= d
->ht
[0].table
[d
->rehashidx
];
209 /* Move all the keys in this bucket from the old to the new hash HT */
214 /* Get the index in the new hash table */
215 h
= dictHashKey(d
, de
->key
) & d
->ht
[1].sizemask
;
216 de
->next
= d
->ht
[1].table
[h
];
217 d
->ht
[1].table
[h
] = de
;
222 d
->ht
[0].table
[d
->rehashidx
] = NULL
;
228 long long timeInMilliseconds(void) {
231 gettimeofday(&tv
,NULL
);
232 return (((long long)tv
.tv_sec
)*1000)+(tv
.tv_usec
/1000);
235 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
236 int dictRehashMilliseconds(dict
*d
, int ms
) {
237 long long start
= timeInMilliseconds();
240 while(dictRehash(d
,100)) {
242 if (timeInMilliseconds()-start
> ms
) break;
247 /* This function performs just a step of rehashing, and only if there are
248 * no safe iterators bound to our hash table. When we have iterators in the
249 * middle of a rehashing we can't mess with the two hash tables otherwise
250 * some element can be missed or duplicated.
252 * This function is called by common lookup or update operations in the
253 * dictionary so that the hash table automatically migrates from H1 to H2
254 * while it is actively used. */
255 static void _dictRehashStep(dict
*d
) {
256 if (d
->iterators
== 0) dictRehash(d
,1);
259 /* Add an element to the target hash table */
260 int dictAdd(dict
*d
, void *key
, void *val
)
266 if (dictIsRehashing(d
)) _dictRehashStep(d
);
268 /* Get the index of the new element, or -1 if
269 * the element already exists. */
270 if ((index
= _dictKeyIndex(d
, key
)) == -1)
273 /* Allocate the memory and store the new entry */
274 ht
= dictIsRehashing(d
) ? &d
->ht
[1] : &d
->ht
[0];
275 entry
= zmalloc(sizeof(*entry
));
276 entry
->next
= ht
->table
[index
];
277 ht
->table
[index
] = entry
;
280 /* Set the hash entry fields. */
281 dictSetHashKey(d
, entry
, key
);
282 dictSetHashVal(d
, entry
, val
);
286 /* Add an element, discarding the old if the key already exists.
287 * Return 1 if the key was added from scratch, 0 if there was already an
288 * element with such key and dictReplace() just performed a value update
290 int dictReplace(dict
*d
, void *key
, void *val
)
292 dictEntry
*entry
, auxentry
;
294 /* Try to add the element. If the key
295 * does not exists dictAdd will suceed. */
296 if (dictAdd(d
, key
, val
) == DICT_OK
)
298 /* It already exists, get the entry */
299 entry
= dictFind(d
, key
);
300 /* Set the new value and free the old one. Note that it is important
301 * to do that in this order, as the value may just be exactly the same
302 * as the previous one. In this context, think to reference counting,
303 * you want to increment (set), and then decrement (free), and not the
306 dictSetHashVal(d
, entry
, val
);
307 dictFreeEntryVal(d
, &auxentry
);
311 /* Search and remove an element */
312 static int dictGenericDelete(dict
*d
, const void *key
, int nofree
)
315 dictEntry
*he
, *prevHe
;
318 if (d
->ht
[0].size
== 0) return DICT_ERR
; /* d->ht[0].table is NULL */
319 if (dictIsRehashing(d
)) _dictRehashStep(d
);
320 h
= dictHashKey(d
, key
);
322 for (table
= 0; table
<= 1; table
++) {
323 idx
= h
& d
->ht
[table
].sizemask
;
324 he
= d
->ht
[table
].table
[idx
];
327 if (dictCompareHashKeys(d
, key
, he
->key
)) {
328 /* Unlink the element from the list */
330 prevHe
->next
= he
->next
;
332 d
->ht
[table
].table
[idx
] = he
->next
;
334 dictFreeEntryKey(d
, he
);
335 dictFreeEntryVal(d
, he
);
344 if (!dictIsRehashing(d
)) break;
346 return DICT_ERR
; /* not found */
349 int dictDelete(dict
*ht
, const void *key
) {
350 return dictGenericDelete(ht
,key
,0);
353 int dictDeleteNoFree(dict
*ht
, const void *key
) {
354 return dictGenericDelete(ht
,key
,1);
357 /* Destroy an entire dictionary */
358 int _dictClear(dict
*d
, dictht
*ht
)
362 /* Free all the elements */
363 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
364 dictEntry
*he
, *nextHe
;
366 if ((he
= ht
->table
[i
]) == NULL
) continue;
369 dictFreeEntryKey(d
, he
);
370 dictFreeEntryVal(d
, he
);
376 /* Free the table and the allocated cache structure */
378 /* Re-initialize the table */
380 return DICT_OK
; /* never fails */
383 /* Clear & Release the hash table */
384 void dictRelease(dict
*d
)
386 _dictClear(d
,&d
->ht
[0]);
387 _dictClear(d
,&d
->ht
[1]);
391 dictEntry
*dictFind(dict
*d
, const void *key
)
394 unsigned int h
, idx
, table
;
396 if (d
->ht
[0].size
== 0) return NULL
; /* We don't have a table at all */
397 if (dictIsRehashing(d
)) _dictRehashStep(d
);
398 h
= dictHashKey(d
, key
);
399 for (table
= 0; table
<= 1; table
++) {
400 idx
= h
& d
->ht
[table
].sizemask
;
401 he
= d
->ht
[table
].table
[idx
];
403 if (dictCompareHashKeys(d
, key
, he
->key
))
407 if (!dictIsRehashing(d
)) return NULL
;
412 void *dictFetchValue(dict
*d
, const void *key
) {
415 he
= dictFind(d
,key
);
416 return he
? dictGetEntryVal(he
) : NULL
;
419 dictIterator
*dictGetIterator(dict
*d
)
421 dictIterator
*iter
= zmalloc(sizeof(*iter
));
428 iter
->nextEntry
= NULL
;
432 dictIterator
*dictGetSafeIterator(dict
*d
) {
433 dictIterator
*i
= dictGetIterator(d
);
439 dictEntry
*dictNext(dictIterator
*iter
)
442 if (iter
->entry
== NULL
) {
443 dictht
*ht
= &iter
->d
->ht
[iter
->table
];
444 if (iter
->safe
&& iter
->index
== -1 && iter
->table
== 0)
445 iter
->d
->iterators
++;
447 if (iter
->index
>= (signed) ht
->size
) {
448 if (dictIsRehashing(iter
->d
) && iter
->table
== 0) {
451 ht
= &iter
->d
->ht
[1];
456 iter
->entry
= ht
->table
[iter
->index
];
458 iter
->entry
= iter
->nextEntry
;
461 /* We need to save the 'next' here, the iterator user
462 * may delete the entry we are returning. */
463 iter
->nextEntry
= iter
->entry
->next
;
470 void dictReleaseIterator(dictIterator
*iter
)
472 if (iter
->safe
&& !(iter
->index
== -1 && iter
->table
== 0))
473 iter
->d
->iterators
--;
477 /* Return a random entry from the hash table. Useful to
478 * implement randomized algorithms */
479 dictEntry
*dictGetRandomKey(dict
*d
)
481 dictEntry
*he
, *orighe
;
483 int listlen
, listele
;
485 if (dictSize(d
) == 0) return NULL
;
486 if (dictIsRehashing(d
)) _dictRehashStep(d
);
487 if (dictIsRehashing(d
)) {
489 h
= random() % (d
->ht
[0].size
+d
->ht
[1].size
);
490 he
= (h
>= d
->ht
[0].size
) ? d
->ht
[1].table
[h
- d
->ht
[0].size
] :
495 h
= random() & d
->ht
[0].sizemask
;
496 he
= d
->ht
[0].table
[h
];
500 /* Now we found a non empty bucket, but it is a linked
501 * list and we need to get a random element from the list.
502 * The only sane way to do so is counting the elements and
503 * select a random index. */
510 listele
= random() % listlen
;
512 while(listele
--) he
= he
->next
;
516 /* ------------------------- private functions ------------------------------ */
518 /* Expand the hash table if needed */
519 static int _dictExpandIfNeeded(dict
*d
)
521 /* Incremental rehashing already in progress. Return. */
522 if (dictIsRehashing(d
)) return DICT_OK
;
524 /* If the hash table is empty expand it to the intial size. */
525 if (d
->ht
[0].size
== 0) return dictExpand(d
, DICT_HT_INITIAL_SIZE
);
527 /* If we reached the 1:1 ratio, and we are allowed to resize the hash
528 * table (global setting) or we should avoid it but the ratio between
529 * elements/buckets is over the "safe" threshold, we resize doubling
530 * the number of buckets. */
531 if (d
->ht
[0].used
>= d
->ht
[0].size
&&
533 d
->ht
[0].used
/d
->ht
[0].size
> dict_force_resize_ratio
))
535 return dictExpand(d
, ((d
->ht
[0].size
> d
->ht
[0].used
) ?
536 d
->ht
[0].size
: d
->ht
[0].used
)*2);
541 /* Our hash table capability is a power of two */
542 static unsigned long _dictNextPower(unsigned long size
)
544 unsigned long i
= DICT_HT_INITIAL_SIZE
;
546 if (size
>= LONG_MAX
) return LONG_MAX
;
554 /* Returns the index of a free slot that can be populated with
555 * an hash entry for the given 'key'.
556 * If the key already exists, -1 is returned.
558 * Note that if we are in the process of rehashing the hash table, the
559 * index is always returned in the context of the second (new) hash table. */
560 static int _dictKeyIndex(dict
*d
, const void *key
)
562 unsigned int h
, idx
, table
;
565 /* Expand the hashtable if needed */
566 if (_dictExpandIfNeeded(d
) == DICT_ERR
)
568 /* Compute the key hash value */
569 h
= dictHashKey(d
, key
);
570 for (table
= 0; table
<= 1; table
++) {
571 idx
= h
& d
->ht
[table
].sizemask
;
572 /* Search if this slot does not already contain the given key */
573 he
= d
->ht
[table
].table
[idx
];
575 if (dictCompareHashKeys(d
, key
, he
->key
))
579 if (!dictIsRehashing(d
)) break;
584 void dictEmpty(dict
*d
) {
585 _dictClear(d
,&d
->ht
[0]);
586 _dictClear(d
,&d
->ht
[1]);
591 #define DICT_STATS_VECTLEN 50
592 static void _dictPrintStatsHt(dictht
*ht
) {
593 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
594 unsigned long totchainlen
= 0;
595 unsigned long clvector
[DICT_STATS_VECTLEN
];
598 printf("No stats available for empty dictionaries\n");
602 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
603 for (i
= 0; i
< ht
->size
; i
++) {
606 if (ht
->table
[i
] == NULL
) {
611 /* For each hash entry on this slot... */
618 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
619 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
620 totchainlen
+= chainlen
;
622 printf("Hash table stats:\n");
623 printf(" table size: %ld\n", ht
->size
);
624 printf(" number of elements: %ld\n", ht
->used
);
625 printf(" different slots: %ld\n", slots
);
626 printf(" max chain length: %ld\n", maxchainlen
);
627 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
628 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
629 printf(" Chain length distribution:\n");
630 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
631 if (clvector
[i
] == 0) continue;
632 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
636 void dictPrintStats(dict
*d
) {
637 _dictPrintStatsHt(&d
->ht
[0]);
638 if (dictIsRehashing(d
)) {
639 printf("-- Rehashing into ht[1]:\n");
640 _dictPrintStatsHt(&d
->ht
[1]);
644 void dictEnableResize(void) {
648 void dictDisableResize(void) {
654 /* The following are just example hash table types implementations.
655 * Not useful for Redis so they are commented out.
658 /* ----------------------- StringCopy Hash Table Type ------------------------*/
660 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
662 return dictGenHashFunction(key
, strlen(key
));
665 static void *_dictStringDup(void *privdata
, const void *key
)
667 int len
= strlen(key
);
668 char *copy
= zmalloc(len
+1);
669 DICT_NOTUSED(privdata
);
671 memcpy(copy
, key
, len
);
676 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
679 DICT_NOTUSED(privdata
);
681 return strcmp(key1
, key2
) == 0;
684 static void _dictStringDestructor(void *privdata
, void *key
)
686 DICT_NOTUSED(privdata
);
691 dictType dictTypeHeapStringCopyKey
= {
692 _dictStringCopyHTHashFunction
, /* hash function */
693 _dictStringDup
, /* key dup */
695 _dictStringCopyHTKeyCompare
, /* key compare */
696 _dictStringDestructor
, /* key destructor */
697 NULL
/* val destructor */
700 /* This is like StringCopy but does not auto-duplicate the key.
701 * It's used for intepreter's shared strings. */
702 dictType dictTypeHeapStrings
= {
703 _dictStringCopyHTHashFunction
, /* hash function */
706 _dictStringCopyHTKeyCompare
, /* key compare */
707 _dictStringDestructor
, /* key destructor */
708 NULL
/* val destructor */
711 /* This is like StringCopy but also automatically handle dynamic
712 * allocated C strings as values. */
713 dictType dictTypeHeapStringCopyKeyValue
= {
714 _dictStringCopyHTHashFunction
, /* hash function */
715 _dictStringDup
, /* key dup */
716 _dictStringDup
, /* val dup */
717 _dictStringCopyHTKeyCompare
, /* key compare */
718 _dictStringDestructor
, /* key destructor */
719 _dictStringDestructor
, /* val destructor */