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 dictIterator
*dictGetIterator(dict
*d
)
428 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
434 iter
->nextEntry
= NULL
;
438 dictEntry
*dictNext(dictIterator
*iter
)
441 if (iter
->entry
== NULL
) {
442 dictht
*ht
= &iter
->d
->ht
[iter
->table
];
443 if (iter
->index
== -1 && iter
->table
== 0) iter
->d
->iterators
++;
445 if (iter
->index
>= (signed) ht
->size
) {
446 if (dictIsRehashing(iter
->d
) && iter
->table
== 0) {
449 ht
= &iter
->d
->ht
[1];
454 iter
->entry
= ht
->table
[iter
->index
];
456 iter
->entry
= iter
->nextEntry
;
459 /* We need to save the 'next' here, the iterator user
460 * may delete the entry we are returning. */
461 iter
->nextEntry
= iter
->entry
->next
;
468 void dictReleaseIterator(dictIterator
*iter
)
470 if (!(iter
->index
== -1 && iter
->table
== 0)) iter
->d
->iterators
--;
474 /* Return a random entry from the hash table. Useful to
475 * implement randomized algorithms */
476 dictEntry
*dictGetRandomKey(dict
*d
)
478 dictEntry
*he
, *orighe
;
480 int listlen
, listele
;
482 if (dictSize(d
) == 0) return NULL
;
483 if (dictIsRehashing(d
)) _dictRehashStep(d
);
484 if (dictIsRehashing(d
)) {
486 h
= random() % (d
->ht
[0].size
+d
->ht
[1].size
);
487 he
= (h
>= d
->ht
[0].size
) ? d
->ht
[1].table
[h
- d
->ht
[0].size
] :
492 h
= random() & d
->ht
[0].sizemask
;
493 he
= d
->ht
[0].table
[h
];
497 /* Now we found a non empty bucket, but it is a linked
498 * list and we need to get a random element from the list.
499 * The only sane way to do so is counting the elements and
500 * select a random index. */
507 listele
= random() % listlen
;
509 while(listele
--) he
= he
->next
;
513 /* ------------------------- private functions ------------------------------ */
515 /* Expand the hash table if needed */
516 static int _dictExpandIfNeeded(dict
*d
)
518 /* If the hash table is empty expand it to the intial size,
519 * if the table is "full" dobule its size. */
520 if (dictIsRehashing(d
)) return DICT_OK
;
521 if (d
->ht
[0].size
== 0)
522 return dictExpand(d
, DICT_HT_INITIAL_SIZE
);
523 if (d
->ht
[0].used
>= d
->ht
[0].size
&& dict_can_resize
)
524 return dictExpand(d
, ((d
->ht
[0].size
> d
->ht
[0].used
) ?
525 d
->ht
[0].size
: d
->ht
[0].used
)*2);
529 /* Our hash table capability is a power of two */
530 static unsigned long _dictNextPower(unsigned long size
)
532 unsigned long i
= DICT_HT_INITIAL_SIZE
;
534 if (size
>= LONG_MAX
) return LONG_MAX
;
542 /* Returns the index of a free slot that can be populated with
543 * an hash entry for the given 'key'.
544 * If the key already exists, -1 is returned.
546 * Note that if we are in the process of rehashing the hash table, the
547 * index is always returned in the context of the second (new) hash table. */
548 static int _dictKeyIndex(dict
*d
, const void *key
)
550 unsigned int h
, idx
, table
;
553 /* Expand the hashtable if needed */
554 if (_dictExpandIfNeeded(d
) == DICT_ERR
)
556 /* Compute the key hash value */
557 h
= dictHashKey(d
, key
);
558 for (table
= 0; table
<= 1; table
++) {
559 idx
= h
& d
->ht
[table
].sizemask
;
560 /* Search if this slot does not already contain the given key */
561 he
= d
->ht
[table
].table
[idx
];
563 if (dictCompareHashKeys(d
, key
, he
->key
))
567 if (!dictIsRehashing(d
)) break;
572 void dictEmpty(dict
*d
) {
573 _dictClear(d
,&d
->ht
[0]);
574 _dictClear(d
,&d
->ht
[1]);
579 #define DICT_STATS_VECTLEN 50
580 static void _dictPrintStatsHt(dictht
*ht
) {
581 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
582 unsigned long totchainlen
= 0;
583 unsigned long clvector
[DICT_STATS_VECTLEN
];
586 printf("No stats available for empty dictionaries\n");
590 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
591 for (i
= 0; i
< ht
->size
; i
++) {
594 if (ht
->table
[i
] == NULL
) {
599 /* For each hash entry on this slot... */
606 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
607 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
608 totchainlen
+= chainlen
;
610 printf("Hash table stats:\n");
611 printf(" table size: %ld\n", ht
->size
);
612 printf(" number of elements: %ld\n", ht
->used
);
613 printf(" different slots: %ld\n", slots
);
614 printf(" max chain length: %ld\n", maxchainlen
);
615 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
616 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
617 printf(" Chain length distribution:\n");
618 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
619 if (clvector
[i
] == 0) continue;
620 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
624 void dictPrintStats(dict
*d
) {
625 _dictPrintStatsHt(&d
->ht
[0]);
626 if (dictIsRehashing(d
)) {
627 printf("-- Rehashing into ht[1]:\n");
628 _dictPrintStatsHt(&d
->ht
[1]);
632 void dictEnableResize(void) {
636 void dictDisableResize(void) {
640 /* ----------------------- StringCopy Hash Table Type ------------------------*/
642 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
644 return dictGenHashFunction(key
, strlen(key
));
647 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
649 int len
= strlen(key
);
650 char *copy
= _dictAlloc(len
+1);
651 DICT_NOTUSED(privdata
);
653 memcpy(copy
, key
, len
);
658 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
660 int len
= strlen(val
);
661 char *copy
= _dictAlloc(len
+1);
662 DICT_NOTUSED(privdata
);
664 memcpy(copy
, val
, len
);
669 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
672 DICT_NOTUSED(privdata
);
674 return strcmp(key1
, key2
) == 0;
677 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
679 DICT_NOTUSED(privdata
);
681 _dictFree((void*)key
); /* ATTENTION: const cast */
684 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
686 DICT_NOTUSED(privdata
);
688 _dictFree((void*)val
); /* ATTENTION: const cast */
691 dictType dictTypeHeapStringCopyKey
= {
692 _dictStringCopyHTHashFunction
, /* hash function */
693 _dictStringCopyHTKeyDup
, /* key dup */
695 _dictStringCopyHTKeyCompare
, /* key compare */
696 _dictStringCopyHTKeyDestructor
, /* 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 _dictStringCopyHTKeyDestructor
, /* 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 _dictStringCopyHTKeyDup
, /* key dup */
716 _dictStringKeyValCopyHTValDup
, /* val dup */
717 _dictStringCopyHTKeyCompare
, /* key compare */
718 _dictStringCopyHTKeyDestructor
, /* key destructor */
719 _dictStringKeyValCopyHTValDestructor
, /* val destructor */