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 /* -------------------------- private prototypes ---------------------------- */
57 static int _dictExpandIfNeeded(dict
*ht
);
58 static unsigned long _dictNextPower(unsigned long size
);
59 static int _dictKeyIndex(dict
*ht
, const void *key
);
60 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
62 /* -------------------------- hash functions -------------------------------- */
64 /* Thomas Wang's 32 bit Mix Function */
65 unsigned int dictIntHashFunction(unsigned int key
)
76 /* Identity hash function for integer keys */
77 unsigned int dictIdentityHashFunction(unsigned int key
)
82 /* Generic hash function (a popular one from Bernstein).
83 * I tested a few and this was the best. */
84 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
85 unsigned int hash
= 5381;
88 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
92 /* ----------------------------- API implementation ------------------------- */
94 /* Reset an hashtable already initialized with ht_init().
95 * NOTE: This function should only called by ht_destroy(). */
96 static void _dictReset(dictht
*ht
)
104 /* Create a new hash table */
105 dict
*dictCreate(dictType
*type
,
108 dict
*d
= zmalloc(sizeof(*d
));
110 _dictInit(d
,type
,privDataPtr
);
114 /* Initialize the hash table */
115 int _dictInit(dict
*d
, dictType
*type
,
118 _dictReset(&d
->ht
[0]);
119 _dictReset(&d
->ht
[1]);
121 d
->privdata
= privDataPtr
;
127 /* Resize the table to the minimal size that contains all the elements,
128 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
129 int dictResize(dict
*d
)
133 if (!dict_can_resize
|| dictIsRehashing(d
)) return DICT_ERR
;
134 minimal
= d
->ht
[0].used
;
135 if (minimal
< DICT_HT_INITIAL_SIZE
)
136 minimal
= DICT_HT_INITIAL_SIZE
;
137 return dictExpand(d
, minimal
);
140 /* Expand or create the hashtable */
141 int dictExpand(dict
*d
, unsigned long size
)
143 dictht n
; /* the new hashtable */
144 unsigned long realsize
= _dictNextPower(size
);
146 /* the size is invalid if it is smaller than the number of
147 * elements already inside the hashtable */
148 if (dictIsRehashing(d
) || d
->ht
[0].used
> size
)
151 /* Allocate the new hashtable and initialize all pointers to NULL */
153 n
.sizemask
= realsize
-1;
154 n
.table
= zcalloc(realsize
*sizeof(dictEntry
*));
157 /* Is this the first initialization? If so it's not really a rehashing
158 * we just set the first hash table so that it can accept keys. */
159 if (d
->ht
[0].table
== NULL
) {
164 /* Prepare a second hash table for incremental rehashing */
170 /* Performs N steps of incremental rehashing. Returns 1 if there are still
171 * keys to move from the old to the new hash table, otherwise 0 is returned.
172 * Note that a rehashing step consists in moving a bucket (that may have more
173 * thank one key as we use chaining) from the old to the new hash table. */
174 int dictRehash(dict
*d
, int n
) {
175 if (!dictIsRehashing(d
)) return 0;
178 dictEntry
*de
, *nextde
;
180 /* Check if we already rehashed the whole table... */
181 if (d
->ht
[0].used
== 0) {
182 zfree(d
->ht
[0].table
);
184 _dictReset(&d
->ht
[1]);
189 /* Note that rehashidx can't overflow as we are sure there are more
190 * elements because ht[0].used != 0 */
191 while(d
->ht
[0].table
[d
->rehashidx
] == NULL
) d
->rehashidx
++;
192 de
= d
->ht
[0].table
[d
->rehashidx
];
193 /* Move all the keys in this bucket from the old to the new hash HT */
198 /* Get the index in the new hash table */
199 h
= dictHashKey(d
, de
->key
) & d
->ht
[1].sizemask
;
200 de
->next
= d
->ht
[1].table
[h
];
201 d
->ht
[1].table
[h
] = de
;
206 d
->ht
[0].table
[d
->rehashidx
] = NULL
;
212 long long timeInMilliseconds(void) {
215 gettimeofday(&tv
,NULL
);
216 return (((long long)tv
.tv_sec
)*1000)+(tv
.tv_usec
/1000);
219 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
220 int dictRehashMilliseconds(dict
*d
, int ms
) {
221 long long start
= timeInMilliseconds();
224 while(dictRehash(d
,100)) {
226 if (timeInMilliseconds()-start
> ms
) break;
231 /* This function performs just a step of rehashing, and only if there are
232 * not iterators bound to our hash table. When we have iterators in the middle
233 * of a rehashing we can't mess with the two hash tables otherwise some element
234 * can be missed or duplicated.
236 * This function is called by common lookup or update operations in the
237 * dictionary so that the hash table automatically migrates from H1 to H2
238 * while it is actively used. */
239 static void _dictRehashStep(dict
*d
) {
240 if (d
->iterators
== 0) dictRehash(d
,1);
243 /* Add an element to the target hash table */
244 int dictAdd(dict
*d
, void *key
, void *val
)
250 if (dictIsRehashing(d
)) _dictRehashStep(d
);
252 /* Get the index of the new element, or -1 if
253 * the element already exists. */
254 if ((index
= _dictKeyIndex(d
, key
)) == -1)
257 /* Allocates the memory and stores key */
258 ht
= dictIsRehashing(d
) ? &d
->ht
[1] : &d
->ht
[0];
259 entry
= zmalloc(sizeof(*entry
));
260 entry
->next
= ht
->table
[index
];
261 ht
->table
[index
] = entry
;
264 /* Set the hash entry fields. */
265 dictSetHashKey(d
, entry
, key
);
266 dictSetHashVal(d
, entry
, val
);
270 /* Add an element, discarding the old if the key already exists.
271 * Return 1 if the key was added from scratch, 0 if there was already an
272 * element with such key and dictReplace() just performed a value update
274 int dictReplace(dict
*d
, void *key
, void *val
)
276 dictEntry
*entry
, auxentry
;
278 /* Try to add the element. If the key
279 * does not exists dictAdd will suceed. */
280 if (dictAdd(d
, key
, val
) == DICT_OK
)
282 /* It already exists, get the entry */
283 entry
= dictFind(d
, key
);
284 /* Free the old value and set the new one */
285 /* Set the new value and free the old one. Note that it is important
286 * to do that in this order, as the value may just be exactly the same
287 * as the previous one. In this context, think to reference counting,
288 * you want to increment (set), and then decrement (free), and not the
291 dictSetHashVal(d
, entry
, val
);
292 dictFreeEntryVal(d
, &auxentry
);
296 /* Search and remove an element */
297 static int dictGenericDelete(dict
*d
, const void *key
, int nofree
)
300 dictEntry
*he
, *prevHe
;
303 if (d
->ht
[0].size
== 0) return DICT_ERR
; /* d->ht[0].table is NULL */
304 if (dictIsRehashing(d
)) _dictRehashStep(d
);
305 h
= dictHashKey(d
, key
);
307 for (table
= 0; table
<= 1; table
++) {
308 idx
= h
& d
->ht
[table
].sizemask
;
309 he
= d
->ht
[table
].table
[idx
];
312 if (dictCompareHashKeys(d
, key
, he
->key
)) {
313 /* Unlink the element from the list */
315 prevHe
->next
= he
->next
;
317 d
->ht
[table
].table
[idx
] = he
->next
;
319 dictFreeEntryKey(d
, he
);
320 dictFreeEntryVal(d
, he
);
329 if (!dictIsRehashing(d
)) break;
331 return DICT_ERR
; /* not found */
334 int dictDelete(dict
*ht
, const void *key
) {
335 return dictGenericDelete(ht
,key
,0);
338 int dictDeleteNoFree(dict
*ht
, const void *key
) {
339 return dictGenericDelete(ht
,key
,1);
342 /* Destroy an entire dictionary */
343 int _dictClear(dict
*d
, dictht
*ht
)
347 /* Free all the elements */
348 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
349 dictEntry
*he
, *nextHe
;
351 if ((he
= ht
->table
[i
]) == NULL
) continue;
354 dictFreeEntryKey(d
, he
);
355 dictFreeEntryVal(d
, he
);
361 /* Free the table and the allocated cache structure */
363 /* Re-initialize the table */
365 return DICT_OK
; /* never fails */
368 /* Clear & Release the hash table */
369 void dictRelease(dict
*d
)
371 _dictClear(d
,&d
->ht
[0]);
372 _dictClear(d
,&d
->ht
[1]);
376 dictEntry
*dictFind(dict
*d
, const void *key
)
379 unsigned int h
, idx
, table
;
381 if (d
->ht
[0].size
== 0) return NULL
; /* We don't have a table at all */
382 if (dictIsRehashing(d
)) _dictRehashStep(d
);
383 h
= dictHashKey(d
, key
);
384 for (table
= 0; table
<= 1; table
++) {
385 idx
= h
& d
->ht
[table
].sizemask
;
386 he
= d
->ht
[table
].table
[idx
];
388 if (dictCompareHashKeys(d
, key
, he
->key
))
392 if (!dictIsRehashing(d
)) return NULL
;
397 void *dictFetchValue(dict
*d
, const void *key
) {
400 he
= dictFind(d
,key
);
401 return he
? dictGetEntryVal(he
) : NULL
;
404 dictIterator
*dictGetIterator(dict
*d
)
406 dictIterator
*iter
= zmalloc(sizeof(*iter
));
412 iter
->nextEntry
= NULL
;
416 dictEntry
*dictNext(dictIterator
*iter
)
419 if (iter
->entry
== NULL
) {
420 dictht
*ht
= &iter
->d
->ht
[iter
->table
];
421 if (iter
->index
== -1 && iter
->table
== 0) iter
->d
->iterators
++;
423 if (iter
->index
>= (signed) ht
->size
) {
424 if (dictIsRehashing(iter
->d
) && iter
->table
== 0) {
427 ht
= &iter
->d
->ht
[1];
432 iter
->entry
= ht
->table
[iter
->index
];
434 iter
->entry
= iter
->nextEntry
;
437 /* We need to save the 'next' here, the iterator user
438 * may delete the entry we are returning. */
439 iter
->nextEntry
= iter
->entry
->next
;
446 void dictReleaseIterator(dictIterator
*iter
)
448 if (!(iter
->index
== -1 && iter
->table
== 0)) iter
->d
->iterators
--;
452 /* Return a random entry from the hash table. Useful to
453 * implement randomized algorithms */
454 dictEntry
*dictGetRandomKey(dict
*d
)
456 dictEntry
*he
, *orighe
;
458 int listlen
, listele
;
460 if (dictSize(d
) == 0) return NULL
;
461 if (dictIsRehashing(d
)) _dictRehashStep(d
);
462 if (dictIsRehashing(d
)) {
464 h
= random() % (d
->ht
[0].size
+d
->ht
[1].size
);
465 he
= (h
>= d
->ht
[0].size
) ? d
->ht
[1].table
[h
- d
->ht
[0].size
] :
470 h
= random() & d
->ht
[0].sizemask
;
471 he
= d
->ht
[0].table
[h
];
475 /* Now we found a non empty bucket, but it is a linked
476 * list and we need to get a random element from the list.
477 * The only sane way to do so is counting the elements and
478 * select a random index. */
485 listele
= random() % listlen
;
487 while(listele
--) he
= he
->next
;
491 /* ------------------------- private functions ------------------------------ */
493 /* Expand the hash table if needed */
494 static int _dictExpandIfNeeded(dict
*d
)
496 /* If the hash table is empty expand it to the intial size,
497 * if the table is "full" dobule its size. */
498 if (dictIsRehashing(d
)) return DICT_OK
;
499 if (d
->ht
[0].size
== 0)
500 return dictExpand(d
, DICT_HT_INITIAL_SIZE
);
501 if (d
->ht
[0].used
>= d
->ht
[0].size
&& dict_can_resize
)
502 return dictExpand(d
, ((d
->ht
[0].size
> d
->ht
[0].used
) ?
503 d
->ht
[0].size
: d
->ht
[0].used
)*2);
507 /* Our hash table capability is a power of two */
508 static unsigned long _dictNextPower(unsigned long size
)
510 unsigned long i
= DICT_HT_INITIAL_SIZE
;
512 if (size
>= LONG_MAX
) return LONG_MAX
;
520 /* Returns the index of a free slot that can be populated with
521 * an hash entry for the given 'key'.
522 * If the key already exists, -1 is returned.
524 * Note that if we are in the process of rehashing the hash table, the
525 * index is always returned in the context of the second (new) hash table. */
526 static int _dictKeyIndex(dict
*d
, const void *key
)
528 unsigned int h
, idx
, table
;
531 /* Expand the hashtable if needed */
532 if (_dictExpandIfNeeded(d
) == DICT_ERR
)
534 /* Compute the key hash value */
535 h
= dictHashKey(d
, key
);
536 for (table
= 0; table
<= 1; table
++) {
537 idx
= h
& d
->ht
[table
].sizemask
;
538 /* Search if this slot does not already contain the given key */
539 he
= d
->ht
[table
].table
[idx
];
541 if (dictCompareHashKeys(d
, key
, he
->key
))
545 if (!dictIsRehashing(d
)) break;
550 void dictEmpty(dict
*d
) {
551 _dictClear(d
,&d
->ht
[0]);
552 _dictClear(d
,&d
->ht
[1]);
557 #define DICT_STATS_VECTLEN 50
558 static void _dictPrintStatsHt(dictht
*ht
) {
559 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
560 unsigned long totchainlen
= 0;
561 unsigned long clvector
[DICT_STATS_VECTLEN
];
564 printf("No stats available for empty dictionaries\n");
568 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
569 for (i
= 0; i
< ht
->size
; i
++) {
572 if (ht
->table
[i
] == NULL
) {
577 /* For each hash entry on this slot... */
584 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
585 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
586 totchainlen
+= chainlen
;
588 printf("Hash table stats:\n");
589 printf(" table size: %ld\n", ht
->size
);
590 printf(" number of elements: %ld\n", ht
->used
);
591 printf(" different slots: %ld\n", slots
);
592 printf(" max chain length: %ld\n", maxchainlen
);
593 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
594 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
595 printf(" Chain length distribution:\n");
596 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
597 if (clvector
[i
] == 0) continue;
598 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
602 void dictPrintStats(dict
*d
) {
603 _dictPrintStatsHt(&d
->ht
[0]);
604 if (dictIsRehashing(d
)) {
605 printf("-- Rehashing into ht[1]:\n");
606 _dictPrintStatsHt(&d
->ht
[1]);
610 void dictEnableResize(void) {
614 void dictDisableResize(void) {
618 /* ----------------------- StringCopy Hash Table Type ------------------------*/
620 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
622 return dictGenHashFunction(key
, strlen(key
));
625 static void *_dictStringDup(void *privdata
, const void *key
)
627 int len
= strlen(key
);
628 char *copy
= zmalloc(len
+1);
629 DICT_NOTUSED(privdata
);
631 memcpy(copy
, key
, len
);
636 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
639 DICT_NOTUSED(privdata
);
641 return strcmp(key1
, key2
) == 0;
644 static void _dictStringDestructor(void *privdata
, void *key
)
646 DICT_NOTUSED(privdata
);
651 dictType dictTypeHeapStringCopyKey
= {
652 _dictStringCopyHTHashFunction
, /* hash function */
653 _dictStringDup
, /* key dup */
655 _dictStringCopyHTKeyCompare
, /* key compare */
656 _dictStringDestructor
, /* key destructor */
657 NULL
/* val destructor */
660 /* This is like StringCopy but does not auto-duplicate the key.
661 * It's used for intepreter's shared strings. */
662 dictType dictTypeHeapStrings
= {
663 _dictStringCopyHTHashFunction
, /* hash function */
666 _dictStringCopyHTKeyCompare
, /* key compare */
667 _dictStringDestructor
, /* key destructor */
668 NULL
/* val destructor */
671 /* This is like StringCopy but also automatically handle dynamic
672 * allocated C strings as values. */
673 dictType dictTypeHeapStringCopyKeyValue
= {
674 _dictStringCopyHTHashFunction
, /* hash function */
675 _dictStringDup
, /* key dup */
676 _dictStringDup
, /* val dup */
677 _dictStringCopyHTKeyCompare
, /* key compare */
678 _dictStringDestructor
, /* key destructor */
679 _dictStringDestructor
, /* val destructor */