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.
48 /* Using dictEnableResize() / dictDisableResize() we make possible to
49 * enable/disable resizing of the hash table as needed. This is very important
50 * for Redis, as we use copy-on-write and don't want to move too much memory
51 * around when there is a child performing saving operations. */
52 static int dict_can_resize
= 1;
54 /* ---------------------------- Utility funcitons --------------------------- */
56 static void _dictPanic(const char *fmt
, ...)
61 fprintf(stderr
, "\nDICT LIBRARY PANIC: ");
62 vfprintf(stderr
, fmt
, ap
);
63 fprintf(stderr
, "\n\n");
67 /* ------------------------- Heap Management Wrappers------------------------ */
69 static void *_dictAlloc(size_t size
)
71 void *p
= zmalloc(size
);
73 _dictPanic("Out of memory");
77 static void _dictFree(void *ptr
) {
81 /* -------------------------- private prototypes ---------------------------- */
83 static int _dictExpandIfNeeded(dict
*ht
);
84 static unsigned long _dictNextPower(unsigned long size
);
85 static int _dictKeyIndex(dict
*ht
, const void *key
);
86 static int _dictInit(dict
*ht
, dictType
*type
, void *privDataPtr
);
88 /* -------------------------- hash functions -------------------------------- */
90 /* Thomas Wang's 32 bit Mix Function */
91 unsigned int dictIntHashFunction(unsigned int key
)
102 /* Identity hash function for integer keys */
103 unsigned int dictIdentityHashFunction(unsigned int key
)
108 /* Generic hash function (a popular one from Bernstein).
109 * I tested a few and this was the best. */
110 unsigned int dictGenHashFunction(const unsigned char *buf
, int len
) {
111 unsigned int hash
= 5381;
114 hash
= ((hash
<< 5) + hash
) + (*buf
++); /* hash * 33 + c */
118 /* ----------------------------- API implementation ------------------------- */
120 /* Reset an hashtable already initialized with ht_init().
121 * NOTE: This function should only called by ht_destroy(). */
122 static void _dictReset(dictht
*ht
)
130 /* Create a new hash table */
131 dict
*dictCreate(dictType
*type
,
134 dict
*d
= _dictAlloc(sizeof(*d
));
136 _dictInit(d
,type
,privDataPtr
);
140 /* Initialize the hash table */
141 int _dictInit(dict
*d
, dictType
*type
,
144 _dictReset(&d
->ht
[0]);
145 _dictReset(&d
->ht
[1]);
147 d
->privdata
= privDataPtr
;
153 /* Resize the table to the minimal size that contains all the elements,
154 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
155 int dictResize(dict
*d
)
159 if (!dict_can_resize
|| dictIsRehashing(d
)) return DICT_ERR
;
160 minimal
= d
->ht
[0].used
;
161 if (minimal
< DICT_HT_INITIAL_SIZE
)
162 minimal
= DICT_HT_INITIAL_SIZE
;
163 return dictExpand(d
, minimal
);
166 /* Expand or create the hashtable */
167 int dictExpand(dict
*d
, unsigned long size
)
169 dictht n
; /* the new hashtable */
170 unsigned long realsize
= _dictNextPower(size
);
172 /* the size is invalid if it is smaller than the number of
173 * elements already inside the hashtable */
174 if (dictIsRehashing(d
) || d
->ht
[0].used
> size
)
178 n
.sizemask
= realsize
-1;
179 n
.table
= _dictAlloc(realsize
*sizeof(dictEntry
*));
182 /* Initialize all the pointers to NULL */
183 memset(n
.table
, 0, realsize
*sizeof(dictEntry
*));
185 /* Is this the first initialization? If so it's not really a rehashing
186 * we just set the first hash table so that it can accept keys. */
187 if (d
->ht
[0].table
== NULL
) {
192 /* Prepare a second hash table for incremental rehashing */
198 /* Performs N steps of incremental rehashing. Returns 1 if there are still
199 * keys to move from the old to the new hash table, otherwise 0 is returned.
200 * Note that a rehashing step consists in moving a bucket (that may have more
201 * thank one key as we use chaining) from the old to the new hash table. */
202 int dictRehash(dict
*d
, int n
) {
203 if (!dictIsRehashing(d
)) return 0;
206 dictEntry
*de
, *nextde
;
208 /* Check if we already rehashed the whole table... */
209 if (d
->ht
[0].used
== 0) {
210 _dictFree(d
->ht
[0].table
);
212 _dictReset(&d
->ht
[1]);
217 /* Note that rehashidx can't overflow as we are sure there are more
218 * elements because ht[0].used != 0 */
219 while(d
->ht
[0].table
[d
->rehashidx
] == NULL
) d
->rehashidx
++;
220 de
= d
->ht
[0].table
[d
->rehashidx
];
221 /* Move all the keys in this bucket from the old to the new hash HT */
226 /* Get the index in the new hash table */
227 h
= dictHashKey(d
, de
->key
) & d
->ht
[1].sizemask
;
228 de
->next
= d
->ht
[1].table
[h
];
229 d
->ht
[1].table
[h
] = de
;
234 d
->ht
[0].table
[d
->rehashidx
] = NULL
;
240 /* This function performs just a step of rehashing, and only if there are
241 * not iterators bound to our hash table. When we have iterators in the middle
242 * of a rehashing we can't mess with the two hash tables otherwise some element
243 * can be missed or duplicated.
245 * This function is called by common lookup or update operations in the
246 * dictionary so that the hash table automatically migrates from H1 to H2
247 * while it is actively used. */
248 static void _dictRehashStep(dict
*d
) {
249 if (d
->iterators
== 0) dictRehash(d
,1);
252 /* Add an element to the target hash table */
253 int dictAdd(dict
*d
, void *key
, void *val
)
259 if (dictIsRehashing(d
)) _dictRehashStep(d
);
261 /* Get the index of the new element, or -1 if
262 * the element already exists. */
263 if ((index
= _dictKeyIndex(d
, key
)) == -1)
266 /* Allocates the memory and stores key */
267 ht
= dictIsRehashing(d
) ? &d
->ht
[1] : &d
->ht
[0];
268 entry
= _dictAlloc(sizeof(*entry
));
269 entry
->next
= ht
->table
[index
];
270 ht
->table
[index
] = entry
;
273 /* Set the hash entry fields. */
274 dictSetHashKey(d
, entry
, key
);
275 dictSetHashVal(d
, entry
, val
);
279 /* Add an element, discarding the old if the key already exists.
280 * Return 1 if the key was added from scratch, 0 if there was already an
281 * element with such key and dictReplace() just performed a value update
283 int dictReplace(dict
*d
, void *key
, void *val
)
285 dictEntry
*entry
, auxentry
;
287 /* Try to add the element. If the key
288 * does not exists dictAdd will suceed. */
289 if (dictAdd(d
, key
, val
) == DICT_OK
)
291 /* It already exists, get the entry */
292 entry
= dictFind(d
, key
);
293 /* Free the old value and set the new one */
294 /* Set the new value and free the old one. Note that it is important
295 * to do that in this order, as the value may just be exactly the same
296 * as the previous one. In this context, think to reference counting,
297 * you want to increment (set), and then decrement (free), and not the
300 dictSetHashVal(d
, entry
, val
);
301 dictFreeEntryVal(d
, &auxentry
);
305 /* Search and remove an element */
306 static int dictGenericDelete(dict
*d
, const void *key
, int nofree
)
309 dictEntry
*he
, *prevHe
;
312 if (d
->ht
[0].size
== 0) return DICT_ERR
; /* d->ht[0].table is NULL */
313 if (dictIsRehashing(d
)) _dictRehashStep(d
);
314 h
= dictHashKey(d
, key
);
316 for (table
= 0; table
<= 1; table
++) {
317 idx
= h
& d
->ht
[table
].sizemask
;
318 he
= d
->ht
[table
].table
[idx
];
321 if (dictCompareHashKeys(d
, key
, he
->key
)) {
322 /* Unlink the element from the list */
324 prevHe
->next
= he
->next
;
326 d
->ht
[table
].table
[idx
] = he
->next
;
328 dictFreeEntryKey(d
, he
);
329 dictFreeEntryVal(d
, he
);
338 if (!dictIsRehashing(d
)) break;
340 return DICT_ERR
; /* not found */
343 int dictDelete(dict
*ht
, const void *key
) {
344 return dictGenericDelete(ht
,key
,0);
347 int dictDeleteNoFree(dict
*ht
, const void *key
) {
348 return dictGenericDelete(ht
,key
,1);
351 /* Destroy an entire dictionary */
352 int _dictClear(dict
*d
, dictht
*ht
)
356 /* Free all the elements */
357 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
358 dictEntry
*he
, *nextHe
;
360 if ((he
= ht
->table
[i
]) == NULL
) continue;
363 dictFreeEntryKey(d
, he
);
364 dictFreeEntryVal(d
, he
);
370 /* Free the table and the allocated cache structure */
371 _dictFree(ht
->table
);
372 /* Re-initialize the table */
374 return DICT_OK
; /* never fails */
377 /* Clear & Release the hash table */
378 void dictRelease(dict
*d
)
380 _dictClear(d
,&d
->ht
[0]);
381 _dictClear(d
,&d
->ht
[1]);
385 dictEntry
*dictFind(dict
*d
, const void *key
)
388 unsigned int h
, idx
, table
;
390 if (d
->ht
[0].size
== 0) return NULL
; /* We don't have a table at all */
391 if (dictIsRehashing(d
)) _dictRehashStep(d
);
392 h
= dictHashKey(d
, key
);
393 for (table
= 0; table
<= 1; table
++) {
394 idx
= h
& d
->ht
[table
].sizemask
;
395 he
= d
->ht
[table
].table
[idx
];
397 if (dictCompareHashKeys(d
, key
, he
->key
))
401 if (!dictIsRehashing(d
)) return NULL
;
406 dictIterator
*dictGetIterator(dict
*d
)
408 dictIterator
*iter
= _dictAlloc(sizeof(*iter
));
414 iter
->nextEntry
= NULL
;
418 dictEntry
*dictNext(dictIterator
*iter
)
421 if (iter
->entry
== NULL
) {
422 dictht
*ht
= &iter
->d
->ht
[iter
->table
];
423 if (iter
->index
== -1 && iter
->table
== 0) iter
->d
->iterators
++;
425 if (iter
->index
>= (signed) ht
->size
) {
426 if (dictIsRehashing(iter
->d
) && iter
->table
== 0) {
429 ht
= &iter
->d
->ht
[1];
434 iter
->entry
= ht
->table
[iter
->index
];
436 iter
->entry
= iter
->nextEntry
;
439 /* We need to save the 'next' here, the iterator user
440 * may delete the entry we are returning. */
441 iter
->nextEntry
= iter
->entry
->next
;
448 void dictReleaseIterator(dictIterator
*iter
)
450 if (!(iter
->index
== -1 && iter
->table
== 0)) iter
->d
->iterators
--;
454 /* Return a random entry from the hash table. Useful to
455 * implement randomized algorithms */
456 dictEntry
*dictGetRandomKey(dict
*d
)
458 dictEntry
*he
, *orighe
;
460 int listlen
, listele
;
462 if (dictSize(d
) == 0) return NULL
;
463 if (dictIsRehashing(d
)) _dictRehashStep(d
);
464 if (dictIsRehashing(d
)) {
466 h
= random() % (d
->ht
[0].size
+d
->ht
[1].size
);
467 he
= (h
>= d
->ht
[0].size
) ? d
->ht
[1].table
[h
- d
->ht
[0].size
] :
472 h
= random() & d
->ht
[0].sizemask
;
473 he
= d
->ht
[0].table
[h
];
477 /* Now we found a non empty bucket, but it is a linked
478 * list and we need to get a random element from the list.
479 * The only sane way to do so is counting the elements and
480 * select a random index. */
487 listele
= random() % listlen
;
489 while(listele
--) he
= he
->next
;
493 /* ------------------------- private functions ------------------------------ */
495 /* Expand the hash table if needed */
496 static int _dictExpandIfNeeded(dict
*d
)
498 /* If the hash table is empty expand it to the intial size,
499 * if the table is "full" dobule its size. */
500 if (dictIsRehashing(d
)) return DICT_OK
;
501 if (d
->ht
[0].size
== 0)
502 return dictExpand(d
, DICT_HT_INITIAL_SIZE
);
503 if (d
->ht
[0].used
>= d
->ht
[0].size
&& dict_can_resize
)
504 return dictExpand(d
, ((d
->ht
[0].size
> d
->ht
[0].used
) ?
505 d
->ht
[0].size
: d
->ht
[0].used
)*2);
509 /* Our hash table capability is a power of two */
510 static unsigned long _dictNextPower(unsigned long size
)
512 unsigned long i
= DICT_HT_INITIAL_SIZE
;
514 if (size
>= LONG_MAX
) return LONG_MAX
;
522 /* Returns the index of a free slot that can be populated with
523 * an hash entry for the given 'key'.
524 * If the key already exists, -1 is returned.
526 * Note that if we are in the process of rehashing the hash table, the
527 * index is always returned in the context of the second (new) hash table. */
528 static int _dictKeyIndex(dict
*d
, const void *key
)
530 unsigned int h
, h1
, h2
;
533 /* Expand the hashtable if needed */
534 if (_dictExpandIfNeeded(d
) == DICT_ERR
)
536 /* Compute the key hash value */
537 h
= dictHashKey(d
, key
);
538 h1
= h
& d
->ht
[0].sizemask
;
539 h2
= h
& d
->ht
[1].sizemask
;
540 /* Search if this slot does not already contain the given key */
541 he
= d
->ht
[0].table
[h1
];
543 if (dictCompareHashKeys(d
, key
, he
->key
))
547 if (!dictIsRehashing(d
)) return h1
;
548 /* Check the second hash table */
549 he
= d
->ht
[1].table
[h2
];
551 if (dictCompareHashKeys(d
, key
, he
->key
))
558 void dictEmpty(dict
*d
) {
559 _dictClear(d
,&d
->ht
[0]);
560 _dictClear(d
,&d
->ht
[1]);
565 #define DICT_STATS_VECTLEN 50
566 static void _dictPrintStatsHt(dictht
*ht
) {
567 unsigned long i
, slots
= 0, chainlen
, maxchainlen
= 0;
568 unsigned long totchainlen
= 0;
569 unsigned long clvector
[DICT_STATS_VECTLEN
];
572 printf("No stats available for empty dictionaries\n");
576 for (i
= 0; i
< DICT_STATS_VECTLEN
; i
++) clvector
[i
] = 0;
577 for (i
= 0; i
< ht
->size
; i
++) {
580 if (ht
->table
[i
] == NULL
) {
585 /* For each hash entry on this slot... */
592 clvector
[(chainlen
< DICT_STATS_VECTLEN
) ? chainlen
: (DICT_STATS_VECTLEN
-1)]++;
593 if (chainlen
> maxchainlen
) maxchainlen
= chainlen
;
594 totchainlen
+= chainlen
;
596 printf("Hash table stats:\n");
597 printf(" table size: %ld\n", ht
->size
);
598 printf(" number of elements: %ld\n", ht
->used
);
599 printf(" different slots: %ld\n", slots
);
600 printf(" max chain length: %ld\n", maxchainlen
);
601 printf(" avg chain length (counted): %.02f\n", (float)totchainlen
/slots
);
602 printf(" avg chain length (computed): %.02f\n", (float)ht
->used
/slots
);
603 printf(" Chain length distribution:\n");
604 for (i
= 0; i
< DICT_STATS_VECTLEN
-1; i
++) {
605 if (clvector
[i
] == 0) continue;
606 printf(" %s%ld: %ld (%.02f%%)\n",(i
== DICT_STATS_VECTLEN
-1)?">= ":"", i
, clvector
[i
], ((float)clvector
[i
]/ht
->size
)*100);
610 void dictPrintStats(dict
*d
) {
611 _dictPrintStatsHt(&d
->ht
[0]);
612 if (dictIsRehashing(d
)) {
613 printf("-- Rehashing into ht[1]:\n");
614 _dictPrintStatsHt(&d
->ht
[1]);
618 void dictEnableResize(void) {
622 void dictDisableResize(void) {
626 /* ----------------------- StringCopy Hash Table Type ------------------------*/
628 static unsigned int _dictStringCopyHTHashFunction(const void *key
)
630 return dictGenHashFunction(key
, strlen(key
));
633 static void *_dictStringCopyHTKeyDup(void *privdata
, const void *key
)
635 int len
= strlen(key
);
636 char *copy
= _dictAlloc(len
+1);
637 DICT_NOTUSED(privdata
);
639 memcpy(copy
, key
, len
);
644 static void *_dictStringKeyValCopyHTValDup(void *privdata
, const void *val
)
646 int len
= strlen(val
);
647 char *copy
= _dictAlloc(len
+1);
648 DICT_NOTUSED(privdata
);
650 memcpy(copy
, val
, len
);
655 static int _dictStringCopyHTKeyCompare(void *privdata
, const void *key1
,
658 DICT_NOTUSED(privdata
);
660 return strcmp(key1
, key2
) == 0;
663 static void _dictStringCopyHTKeyDestructor(void *privdata
, void *key
)
665 DICT_NOTUSED(privdata
);
667 _dictFree((void*)key
); /* ATTENTION: const cast */
670 static void _dictStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
672 DICT_NOTUSED(privdata
);
674 _dictFree((void*)val
); /* ATTENTION: const cast */
677 dictType dictTypeHeapStringCopyKey
= {
678 _dictStringCopyHTHashFunction
, /* hash function */
679 _dictStringCopyHTKeyDup
, /* key dup */
681 _dictStringCopyHTKeyCompare
, /* key compare */
682 _dictStringCopyHTKeyDestructor
, /* key destructor */
683 NULL
/* val destructor */
686 /* This is like StringCopy but does not auto-duplicate the key.
687 * It's used for intepreter's shared strings. */
688 dictType dictTypeHeapStrings
= {
689 _dictStringCopyHTHashFunction
, /* hash function */
692 _dictStringCopyHTKeyCompare
, /* key compare */
693 _dictStringCopyHTKeyDestructor
, /* key destructor */
694 NULL
/* val destructor */
697 /* This is like StringCopy but also automatically handle dynamic
698 * allocated C strings as values. */
699 dictType dictTypeHeapStringCopyKeyValue
= {
700 _dictStringCopyHTHashFunction
, /* hash function */
701 _dictStringCopyHTKeyDup
, /* key dup */
702 _dictStringKeyValCopyHTValDup
, /* val dup */
703 _dictStringCopyHTKeyCompare
, /* key compare */
704 _dictStringCopyHTKeyDestructor
, /* key destructor */
705 _dictStringKeyValCopyHTValDestructor
, /* val destructor */