xref: /redis-3.2.3/src/dict.c (revision 6972f18c)
1 /* Hash Tables Implementation.
2  *
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... :)
7  *
8  * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are met:
13  *
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.
22  *
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.
34  */
35 
36 #include "fmacros.h"
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <sys/time.h>
44 #include <ctype.h>
45 
46 #include "dict.h"
47 #include "zmalloc.h"
48 #include "redisassert.h"
49 
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.
54  *
55  * Note that even when dict_can_resize is set to 0, not all resizes are
56  * prevented: a 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;
60 
61 /* -------------------------- private prototypes ---------------------------- */
62 
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);
67 
68 /* -------------------------- hash functions -------------------------------- */
69 
70 /* Thomas Wang's 32 bit Mix Function */
71 unsigned int dictIntHashFunction(unsigned int key)
72 {
73     key += ~(key << 15);
74     key ^=  (key >> 10);
75     key +=  (key << 3);
76     key ^=  (key >> 6);
77     key += ~(key << 11);
78     key ^=  (key >> 16);
79     return key;
80 }
81 
82 /* Identity hash function for integer keys */
83 unsigned int dictIdentityHashFunction(unsigned int key)
84 {
85     return key;
86 }
87 
88 static uint32_t dict_hash_function_seed = 5381;
89 
90 void dictSetHashFunctionSeed(uint32_t seed) {
91     dict_hash_function_seed = seed;
92 }
93 
94 uint32_t dictGetHashFunctionSeed(void) {
95     return dict_hash_function_seed;
96 }
97 
98 /* MurmurHash2, by Austin Appleby
99  * Note - This code makes a few assumptions about how your machine behaves -
100  * 1. We can read a 4-byte value from any address without crashing
101  * 2. sizeof(int) == 4
102  *
103  * And it has a few limitations -
104  *
105  * 1. It will not work incrementally.
106  * 2. It will not produce the same results on little-endian and big-endian
107  *    machines.
108  */
109 unsigned int dictGenHashFunction(const void *key, int len) {
110     /* 'm' and 'r' are mixing constants generated offline.
111      They're not really 'magic', they just happen to work well.  */
112     uint32_t seed = dict_hash_function_seed;
113     const uint32_t m = 0x5bd1e995;
114     const int r = 24;
115 
116     /* Initialize the hash to a 'random' value */
117     uint32_t h = seed ^ len;
118 
119     /* Mix 4 bytes at a time into the hash */
120     const unsigned char *data = (const unsigned char *)key;
121 
122     while(len >= 4) {
123         uint32_t k = *(uint32_t*)data;
124 
125         k *= m;
126         k ^= k >> r;
127         k *= m;
128 
129         h *= m;
130         h ^= k;
131 
132         data += 4;
133         len -= 4;
134     }
135 
136     /* Handle the last few bytes of the input array  */
137     switch(len) {
138     case 3: h ^= data[2] << 16;
139     case 2: h ^= data[1] << 8;
140     case 1: h ^= data[0]; h *= m;
141     };
142 
143     /* Do a few final mixes of the hash to ensure the last few
144      * bytes are well-incorporated. */
145     h ^= h >> 13;
146     h *= m;
147     h ^= h >> 15;
148 
149     return (unsigned int)h;
150 }
151 
152 /* And a case insensitive hash function (based on djb hash) */
153 unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
154     unsigned int hash = (unsigned int)dict_hash_function_seed;
155 
156     while (len--)
157         hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
158     return hash;
159 }
160 
161 /* ----------------------------- API implementation ------------------------- */
162 
163 /* Reset a hash table already initialized with ht_init().
164  * NOTE: This function should only be called by ht_destroy(). */
165 static void _dictReset(dictht *ht)
166 {
167     ht->table = NULL;
168     ht->size = 0;
169     ht->sizemask = 0;
170     ht->used = 0;
171 }
172 
173 /* Create a new hash table */
174 dict *dictCreate(dictType *type,
175         void *privDataPtr)
176 {
177     dict *d = zmalloc(sizeof(*d));
178 
179     _dictInit(d,type,privDataPtr);
180     return d;
181 }
182 
183 /* Initialize the hash table */
184 int _dictInit(dict *d, dictType *type,
185         void *privDataPtr)
186 {
187     _dictReset(&d->ht[0]);
188     _dictReset(&d->ht[1]);
189     d->type = type;
190     d->privdata = privDataPtr;
191     d->rehashidx = -1;
192     d->iterators = 0;
193     return DICT_OK;
194 }
195 
196 /* Resize the table to the minimal size that contains all the elements,
197  * but with the invariant of a USED/BUCKETS ratio near to <= 1 */
198 int dictResize(dict *d)
199 {
200     int minimal;
201 
202     if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
203     minimal = d->ht[0].used;
204     if (minimal < DICT_HT_INITIAL_SIZE)
205         minimal = DICT_HT_INITIAL_SIZE;
206     return dictExpand(d, minimal);
207 }
208 
209 /* Expand or create the hash table */
210 int dictExpand(dict *d, unsigned long size)
211 {
212     dictht n; /* the new hash table */
213     unsigned long realsize = _dictNextPower(size);
214 
215     /* the size is invalid if it is smaller than the number of
216      * elements already inside the hash table */
217     if (dictIsRehashing(d) || d->ht[0].used > size)
218         return DICT_ERR;
219 
220     /* Allocate the new hash table and initialize all pointers to NULL */
221     n.size = realsize;
222     n.sizemask = realsize-1;
223     n.table = zcalloc(realsize*sizeof(dictEntry*));
224     n.used = 0;
225 
226     /* Is this the first initialization? If so it's not really a rehashing
227      * we just set the first hash table so that it can accept keys. */
228     if (d->ht[0].table == NULL) {
229         d->ht[0] = n;
230         return DICT_OK;
231     }
232 
233     /* Prepare a second hash table for incremental rehashing */
234     d->ht[1] = n;
235     d->rehashidx = 0;
236     return DICT_OK;
237 }
238 
239 /* Performs N steps of incremental rehashing. Returns 1 if there are still
240  * keys to move from the old to the new hash table, otherwise 0 is returned.
241  * Note that a rehashing step consists in moving a bucket (that may have more
242  * than one key as we use chaining) from the old to the new hash table. */
243 int dictRehash(dict *d, int n) {
244     if (!dictIsRehashing(d)) return 0;
245 
246     while(n--) {
247         dictEntry *de, *nextde;
248 
249         /* Check if we already rehashed the whole table... */
250         if (d->ht[0].used == 0) {
251             zfree(d->ht[0].table);
252             d->ht[0] = d->ht[1];
253             _dictReset(&d->ht[1]);
254             d->rehashidx = -1;
255             return 0;
256         }
257 
258         /* Note that rehashidx can't overflow as we are sure there are more
259          * elements because ht[0].used != 0 */
260         assert(d->ht[0].size > (unsigned)d->rehashidx);
261         while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
262         de = d->ht[0].table[d->rehashidx];
263         /* Move all the keys in this bucket from the old to the new hash HT */
264         while(de) {
265             unsigned int h;
266 
267             nextde = de->next;
268             /* Get the index in the new hash table */
269             h = dictHashKey(d, de->key) & d->ht[1].sizemask;
270             de->next = d->ht[1].table[h];
271             d->ht[1].table[h] = de;
272             d->ht[0].used--;
273             d->ht[1].used++;
274             de = nextde;
275         }
276         d->ht[0].table[d->rehashidx] = NULL;
277         d->rehashidx++;
278     }
279     return 1;
280 }
281 
282 long long timeInMilliseconds(void) {
283     struct timeval tv;
284 
285     gettimeofday(&tv,NULL);
286     return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
287 }
288 
289 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
290 int dictRehashMilliseconds(dict *d, int ms) {
291     long long start = timeInMilliseconds();
292     int rehashes = 0;
293 
294     while(dictRehash(d,100)) {
295         rehashes += 100;
296         if (timeInMilliseconds()-start > ms) break;
297     }
298     return rehashes;
299 }
300 
301 /* This function performs just a step of rehashing, and only if there are
302  * no safe iterators bound to our hash table. When we have iterators in the
303  * middle of a rehashing we can't mess with the two hash tables otherwise
304  * some element can be missed or duplicated.
305  *
306  * This function is called by common lookup or update operations in the
307  * dictionary so that the hash table automatically migrates from H1 to H2
308  * while it is actively used. */
309 static void _dictRehashStep(dict *d) {
310     if (d->iterators == 0) dictRehash(d,1);
311 }
312 
313 /* Add an element to the target hash table */
314 int dictAdd(dict *d, void *key, void *val)
315 {
316     dictEntry *entry = dictAddRaw(d,key);
317 
318     if (!entry) return DICT_ERR;
319     dictSetVal(d, entry, val);
320     return DICT_OK;
321 }
322 
323 /* Low level add. This function adds the entry but instead of setting
324  * a value returns the dictEntry structure to the user, that will make
325  * sure to fill the value field as he wishes.
326  *
327  * This function is also directly exposed to the user API to be called
328  * mainly in order to store non-pointers inside the hash value, example:
329  *
330  * entry = dictAddRaw(dict,mykey);
331  * if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
332  *
333  * Return values:
334  *
335  * If key already exists NULL is returned.
336  * If key was added, the hash entry is returned to be manipulated by the caller.
337  */
338 dictEntry *dictAddRaw(dict *d, void *key)
339 {
340     int index;
341     dictEntry *entry;
342     dictht *ht;
343 
344     if (dictIsRehashing(d)) _dictRehashStep(d);
345 
346     /* Get the index of the new element, or -1 if
347      * the element already exists. */
348     if ((index = _dictKeyIndex(d, key)) == -1)
349         return NULL;
350 
351     /* Allocate the memory and store the new entry */
352     ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
353     entry = zmalloc(sizeof(*entry));
354     entry->next = ht->table[index];
355     ht->table[index] = entry;
356     ht->used++;
357 
358     /* Set the hash entry fields. */
359     dictSetKey(d, entry, key);
360     return entry;
361 }
362 
363 /* Add an element, discarding the old if the key already exists.
364  * Return 1 if the key was added from scratch, 0 if there was already an
365  * element with such key and dictReplace() just performed a value update
366  * operation. */
367 int dictReplace(dict *d, void *key, void *val)
368 {
369     dictEntry *entry, auxentry;
370 
371     /* Try to add the element. If the key
372      * does not exists dictAdd will suceed. */
373     if (dictAdd(d, key, val) == DICT_OK)
374         return 1;
375     /* It already exists, get the entry */
376     entry = dictFind(d, key);
377     /* Set the new value and free the old one. Note that it is important
378      * to do that in this order, as the value may just be exactly the same
379      * as the previous one. In this context, think to reference counting,
380      * you want to increment (set), and then decrement (free), and not the
381      * reverse. */
382     auxentry = *entry;
383     dictSetVal(d, entry, val);
384     dictFreeVal(d, &auxentry);
385     return 0;
386 }
387 
388 /* dictReplaceRaw() is simply a version of dictAddRaw() that always
389  * returns the hash entry of the specified key, even if the key already
390  * exists and can't be added (in that case the entry of the already
391  * existing key is returned.)
392  *
393  * See dictAddRaw() for more information. */
394 dictEntry *dictReplaceRaw(dict *d, void *key) {
395     dictEntry *entry = dictFind(d,key);
396 
397     return entry ? entry : dictAddRaw(d,key);
398 }
399 
400 /* Search and remove an element */
401 static int dictGenericDelete(dict *d, const void *key, int nofree)
402 {
403     unsigned int h, idx;
404     dictEntry *he, *prevHe;
405     int table;
406 
407     if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
408     if (dictIsRehashing(d)) _dictRehashStep(d);
409     h = dictHashKey(d, key);
410 
411     for (table = 0; table <= 1; table++) {
412         idx = h & d->ht[table].sizemask;
413         he = d->ht[table].table[idx];
414         prevHe = NULL;
415         while(he) {
416             if (dictCompareKeys(d, key, he->key)) {
417                 /* Unlink the element from the list */
418                 if (prevHe)
419                     prevHe->next = he->next;
420                 else
421                     d->ht[table].table[idx] = he->next;
422                 if (!nofree) {
423                     dictFreeKey(d, he);
424                     dictFreeVal(d, he);
425                 }
426                 zfree(he);
427                 d->ht[table].used--;
428                 return DICT_OK;
429             }
430             prevHe = he;
431             he = he->next;
432         }
433         if (!dictIsRehashing(d)) break;
434     }
435     return DICT_ERR; /* not found */
436 }
437 
438 int dictDelete(dict *ht, const void *key) {
439     return dictGenericDelete(ht,key,0);
440 }
441 
442 int dictDeleteNoFree(dict *ht, const void *key) {
443     return dictGenericDelete(ht,key,1);
444 }
445 
446 /* Destroy an entire dictionary */
447 int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
448     unsigned long i;
449 
450     /* Free all the elements */
451     for (i = 0; i < ht->size && ht->used > 0; i++) {
452         dictEntry *he, *nextHe;
453 
454         if (callback && (i & 65535) == 0) callback(d->privdata);
455 
456         if ((he = ht->table[i]) == NULL) continue;
457         while(he) {
458             nextHe = he->next;
459             dictFreeKey(d, he);
460             dictFreeVal(d, he);
461             zfree(he);
462             ht->used--;
463             he = nextHe;
464         }
465     }
466     /* Free the table and the allocated cache structure */
467     zfree(ht->table);
468     /* Re-initialize the table */
469     _dictReset(ht);
470     return DICT_OK; /* never fails */
471 }
472 
473 /* Clear & Release the hash table */
474 void dictRelease(dict *d)
475 {
476     _dictClear(d,&d->ht[0],NULL);
477     _dictClear(d,&d->ht[1],NULL);
478     zfree(d);
479 }
480 
481 dictEntry *dictFind(dict *d, const void *key)
482 {
483     dictEntry *he;
484     unsigned int h, idx, table;
485 
486     if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */
487     if (dictIsRehashing(d)) _dictRehashStep(d);
488     h = dictHashKey(d, key);
489     for (table = 0; table <= 1; table++) {
490         idx = h & d->ht[table].sizemask;
491         he = d->ht[table].table[idx];
492         while(he) {
493             if (dictCompareKeys(d, key, he->key))
494                 return he;
495             he = he->next;
496         }
497         if (!dictIsRehashing(d)) return NULL;
498     }
499     return NULL;
500 }
501 
502 void *dictFetchValue(dict *d, const void *key) {
503     dictEntry *he;
504 
505     he = dictFind(d,key);
506     return he ? dictGetVal(he) : NULL;
507 }
508 
509 /* A fingerprint is a 64 bit number that represents the state of the dictionary
510  * at a given time, it's just a few dict properties xored together.
511  * When an unsafe iterator is initialized, we get the dict fingerprint, and check
512  * the fingerprint again when the iterator is released.
513  * If the two fingerprints are different it means that the user of the iterator
514  * performed forbidden operations against the dictionary while iterating. */
515 long long dictFingerprint(dict *d) {
516     long long integers[6], hash = 0;
517     int j;
518 
519     integers[0] = (long) d->ht[0].table;
520     integers[1] = d->ht[0].size;
521     integers[2] = d->ht[0].used;
522     integers[3] = (long) d->ht[1].table;
523     integers[4] = d->ht[1].size;
524     integers[5] = d->ht[1].used;
525 
526     /* We hash N integers by summing every successive integer with the integer
527      * hashing of the previous sum. Basically:
528      *
529      * Result = hash(hash(hash(int1)+int2)+int3) ...
530      *
531      * This way the same set of integers in a different order will (likely) hash
532      * to a different number. */
533     for (j = 0; j < 6; j++) {
534         hash += integers[j];
535         /* For the hashing step we use Tomas Wang's 64 bit integer hash. */
536         hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
537         hash = hash ^ (hash >> 24);
538         hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
539         hash = hash ^ (hash >> 14);
540         hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
541         hash = hash ^ (hash >> 28);
542         hash = hash + (hash << 31);
543     }
544     return hash;
545 }
546 
547 dictIterator *dictGetIterator(dict *d)
548 {
549     dictIterator *iter = zmalloc(sizeof(*iter));
550 
551     iter->d = d;
552     iter->table = 0;
553     iter->index = -1;
554     iter->safe = 0;
555     iter->entry = NULL;
556     iter->nextEntry = NULL;
557     return iter;
558 }
559 
560 dictIterator *dictGetSafeIterator(dict *d) {
561     dictIterator *i = dictGetIterator(d);
562 
563     i->safe = 1;
564     return i;
565 }
566 
567 dictEntry *dictNext(dictIterator *iter)
568 {
569     while (1) {
570         if (iter->entry == NULL) {
571             dictht *ht = &iter->d->ht[iter->table];
572             if (iter->index == -1 && iter->table == 0) {
573                 if (iter->safe)
574                     iter->d->iterators++;
575                 else
576                     iter->fingerprint = dictFingerprint(iter->d);
577             }
578             iter->index++;
579             if (iter->index >= (signed) ht->size) {
580                 if (dictIsRehashing(iter->d) && iter->table == 0) {
581                     iter->table++;
582                     iter->index = 0;
583                     ht = &iter->d->ht[1];
584                 } else {
585                     break;
586                 }
587             }
588             iter->entry = ht->table[iter->index];
589         } else {
590             iter->entry = iter->nextEntry;
591         }
592         if (iter->entry) {
593             /* We need to save the 'next' here, the iterator user
594              * may delete the entry we are returning. */
595             iter->nextEntry = iter->entry->next;
596             return iter->entry;
597         }
598     }
599     return NULL;
600 }
601 
602 void dictReleaseIterator(dictIterator *iter)
603 {
604     if (!(iter->index == -1 && iter->table == 0)) {
605         if (iter->safe)
606             iter->d->iterators--;
607         else
608             assert(iter->fingerprint == dictFingerprint(iter->d));
609     }
610     zfree(iter);
611 }
612 
613 /* Return a random entry from the hash table. Useful to
614  * implement randomized algorithms */
615 dictEntry *dictGetRandomKey(dict *d)
616 {
617     dictEntry *he, *orighe;
618     unsigned int h;
619     int listlen, listele;
620 
621     if (dictSize(d) == 0) return NULL;
622     if (dictIsRehashing(d)) _dictRehashStep(d);
623     if (dictIsRehashing(d)) {
624         do {
625             h = random() % (d->ht[0].size+d->ht[1].size);
626             he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
627                                       d->ht[0].table[h];
628         } while(he == NULL);
629     } else {
630         do {
631             h = random() & d->ht[0].sizemask;
632             he = d->ht[0].table[h];
633         } while(he == NULL);
634     }
635 
636     /* Now we found a non empty bucket, but it is a linked
637      * list and we need to get a random element from the list.
638      * The only sane way to do so is counting the elements and
639      * select a random index. */
640     listlen = 0;
641     orighe = he;
642     while(he) {
643         he = he->next;
644         listlen++;
645     }
646     listele = random() % listlen;
647     he = orighe;
648     while(listele--) he = he->next;
649     return he;
650 }
651 
652 /* This is a version of dictGetRandomKey() that is modified in order to
653  * return multiple entries by jumping at a random place of the hash table
654  * and scanning linearly for entries.
655  *
656  * Returned pointers to hash table entries are stored into 'des' that
657  * points to an array of dictEntry pointers. The array must have room for
658  * at least 'count' elements, that is the argument we pass to the function
659  * to tell how many random elements we need.
660  *
661  * The function returns the number of items stored into 'des', that may
662  * be less than 'count' if the hash table has less than 'count' elements
663  * inside.
664  *
665  * Note that this function is not suitable when you need a good distribution
666  * of the returned items, but only when you need to "sample" a given number
667  * of continuous elements to run some kind of algorithm or to produce
668  * statistics. However the function is much faster than dictGetRandomKey()
669  * at producing N elements, and the elements are guaranteed to be non
670  * repeating. */
671 int dictGetRandomKeys(dict *d, dictEntry **des, int count) {
672     int j; /* internal hash table id, 0 or 1. */
673     int stored = 0;
674 
675     if (dictSize(d) < count) count = dictSize(d);
676     while(stored < count) {
677         for (j = 0; j < 2; j++) {
678             /* Pick a random point inside the hash table 0 or 1. */
679             unsigned int i = random() & d->ht[j].sizemask;
680             int size = d->ht[j].size;
681 
682             /* Make sure to visit every bucket by iterating 'size' times. */
683             while(size--) {
684                 dictEntry *he = d->ht[j].table[i];
685                 while (he) {
686                     /* Collect all the elements of the buckets found non
687                      * empty while iterating. */
688                     *des = he;
689                     des++;
690                     he = he->next;
691                     stored++;
692                     if (stored == count) return stored;
693                 }
694                 i = (i+1) & d->ht[j].sizemask;
695             }
696             /* If there is only one table and we iterated it all, we should
697              * already have 'count' elements. Assert this condition. */
698             assert(dictIsRehashing(d) != 0);
699         }
700     }
701     return stored; /* Never reached. */
702 }
703 
704 /* Function to reverse bits. Algorithm from:
705  * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
706 static unsigned long rev(unsigned long v) {
707     unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
708     unsigned long mask = ~0;
709     while ((s >>= 1) > 0) {
710         mask ^= (mask << s);
711         v = ((v >> s) & mask) | ((v << s) & ~mask);
712     }
713     return v;
714 }
715 
716 /* dictScan() is used to iterate over the elements of a dictionary.
717  *
718  * Iterating works in the following way:
719  *
720  * 1) Initially you call the function using a cursor (v) value of 0.
721  * 2) The function performs one step of the iteration, and returns the
722  *    new cursor value that you must use in the next call.
723  * 3) When the returned cursor is 0, the iteration is complete.
724  *
725  * The function guarantees that all the elements that are present in the
726  * dictionary from the start to the end of the iteration are returned.
727  * However it is possible that some element is returned multiple time.
728  *
729  * For every element returned, the callback 'fn' passed as argument is
730  * called, with 'privdata' as first argument and the dictionar entry
731  * 'de' as second argument.
732  *
733  * HOW IT WORKS.
734  *
735  * The algorithm used in the iteration was designed by Pieter Noordhuis.
736  * The main idea is to increment a cursor starting from the higher order
737  * bits, that is, instead of incrementing the cursor normally, the bits
738  * of the cursor are reversed, then the cursor is incremented, and finally
739  * the bits are reversed again.
740  *
741  * This strategy is needed because the hash table may be resized from one
742  * call to the other call of the same iteration.
743  *
744  * dict.c hash tables are always power of two in size, and they
745  * use chaining, so the position of an element in a given table is given
746  * always by computing the bitwise AND between Hash(key) and SIZE-1
747  * (where SIZE-1 is always the mask that is equivalent to taking the rest
748  *  of the division between the Hash of the key and SIZE).
749  *
750  * For example if the current hash table size is 16, the mask is
751  * (in binary) 1111. The position of a key in the hash table will be always
752  * the last four bits of the hash output, and so forth.
753  *
754  * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
755  *
756  * If the hash table grows, elements can go anyway in one multiple of
757  * the old bucket: for example let's say that we already iterated with
758  * a 4 bit cursor 1100, since the mask is 1111 (hash table size = 16).
759  *
760  * If the hash table will be resized to 64 elements, and the new mask will
761  * be 111111, the new buckets that you obtain substituting in ??1100
762  * either 0 or 1, can be targeted only by keys that we already visited
763  * when scanning the bucket 1100 in the smaller hash table.
764  *
765  * By iterating the higher bits first, because of the inverted counter, the
766  * cursor does not need to restart if the table size gets bigger, and will
767  * just continue iterating with cursors that don't have '1100' at the end,
768  * nor any other combination of final 4 bits already explored.
769  *
770  * Similarly when the table size shrinks over time, for example going from
771  * 16 to 8, If a combination of the lower three bits (the mask for size 8
772  * is 111) was already completely explored, it will not be visited again
773  * as we are sure that, we tried for example, both 0111 and 1111 (all the
774  * variations of the higher bit) so we don't need to test it again.
775  *
776  * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
777  *
778  * Yes, this is true, but we always iterate the smaller one of the tables,
779  * testing also all the expansions of the current cursor into the larger
780  * table. So for example if the current cursor is 101 and we also have a
781  * larger table of size 16, we also test (0)101 and (1)101 inside the larger
782  * table. This reduces the problem back to having only one table, where
783  * the larger one, if exists, is just an expansion of the smaller one.
784  *
785  * LIMITATIONS
786  *
787  * This iterator is completely stateless, and this is a huge advantage,
788  * including no additional memory used.
789  *
790  * The disadvantages resulting from this design are:
791  *
792  * 1) It is possible that we return duplicated elements. However this is usually
793  *    easy to deal with in the application level.
794  * 2) The iterator must return multiple elements per call, as it needs to always
795  *    return all the keys chained in a given bucket, and all the expansions, so
796  *    we are sure we don't miss keys moving.
797  * 3) The reverse cursor is somewhat hard to understand at first, but this
798  *    comment is supposed to help.
799  */
800 unsigned long dictScan(dict *d,
801                        unsigned long v,
802                        dictScanFunction *fn,
803                        void *privdata)
804 {
805     dictht *t0, *t1;
806     const dictEntry *de;
807     unsigned long m0, m1;
808 
809     if (dictSize(d) == 0) return 0;
810 
811     if (!dictIsRehashing(d)) {
812         t0 = &(d->ht[0]);
813         m0 = t0->sizemask;
814 
815         /* Emit entries at cursor */
816         de = t0->table[v & m0];
817         while (de) {
818             fn(privdata, de);
819             de = de->next;
820         }
821 
822     } else {
823         t0 = &d->ht[0];
824         t1 = &d->ht[1];
825 
826         /* Make sure t0 is the smaller and t1 is the bigger table */
827         if (t0->size > t1->size) {
828             t0 = &d->ht[1];
829             t1 = &d->ht[0];
830         }
831 
832         m0 = t0->sizemask;
833         m1 = t1->sizemask;
834 
835         /* Emit entries at cursor */
836         de = t0->table[v & m0];
837         while (de) {
838             fn(privdata, de);
839             de = de->next;
840         }
841 
842         /* Iterate over indices in larger table that are the expansion
843          * of the index pointed to by the cursor in the smaller table */
844         do {
845             /* Emit entries at cursor */
846             de = t1->table[v & m1];
847             while (de) {
848                 fn(privdata, de);
849                 de = de->next;
850             }
851 
852             /* Increment bits not covered by the smaller mask */
853             v = (((v | m0) + 1) & ~m0) | (v & m0);
854 
855             /* Continue while bits covered by mask difference is non-zero */
856         } while (v & (m0 ^ m1));
857     }
858 
859     /* Set unmasked bits so incrementing the reversed cursor
860      * operates on the masked bits of the smaller table */
861     v |= ~m0;
862 
863     /* Increment the reverse cursor */
864     v = rev(v);
865     v++;
866     v = rev(v);
867 
868     return v;
869 }
870 
871 /* ------------------------- private functions ------------------------------ */
872 
873 /* Expand the hash table if needed */
874 static int _dictExpandIfNeeded(dict *d)
875 {
876     /* Incremental rehashing already in progress. Return. */
877     if (dictIsRehashing(d)) return DICT_OK;
878 
879     /* If the hash table is empty expand it to the initial size. */
880     if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
881 
882     /* If we reached the 1:1 ratio, and we are allowed to resize the hash
883      * table (global setting) or we should avoid it but the ratio between
884      * elements/buckets is over the "safe" threshold, we resize doubling
885      * the number of buckets. */
886     if (d->ht[0].used >= d->ht[0].size &&
887         (dict_can_resize ||
888          d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
889     {
890         return dictExpand(d, d->ht[0].used*2);
891     }
892     return DICT_OK;
893 }
894 
895 /* Our hash table capability is a power of two */
896 static unsigned long _dictNextPower(unsigned long size)
897 {
898     unsigned long i = DICT_HT_INITIAL_SIZE;
899 
900     if (size >= LONG_MAX) return LONG_MAX;
901     while(1) {
902         if (i >= size)
903             return i;
904         i *= 2;
905     }
906 }
907 
908 /* Returns the index of a free slot that can be populated with
909  * a hash entry for the given 'key'.
910  * If the key already exists, -1 is returned.
911  *
912  * Note that if we are in the process of rehashing the hash table, the
913  * index is always returned in the context of the second (new) hash table. */
914 static int _dictKeyIndex(dict *d, const void *key)
915 {
916     unsigned int h, idx, table;
917     dictEntry *he;
918 
919     /* Expand the hash table if needed */
920     if (_dictExpandIfNeeded(d) == DICT_ERR)
921         return -1;
922     /* Compute the key hash value */
923     h = dictHashKey(d, key);
924     for (table = 0; table <= 1; table++) {
925         idx = h & d->ht[table].sizemask;
926         /* Search if this slot does not already contain the given key */
927         he = d->ht[table].table[idx];
928         while(he) {
929             if (dictCompareKeys(d, key, he->key))
930                 return -1;
931             he = he->next;
932         }
933         if (!dictIsRehashing(d)) break;
934     }
935     return idx;
936 }
937 
938 void dictEmpty(dict *d, void(callback)(void*)) {
939     _dictClear(d,&d->ht[0],callback);
940     _dictClear(d,&d->ht[1],callback);
941     d->rehashidx = -1;
942     d->iterators = 0;
943 }
944 
945 void dictEnableResize(void) {
946     dict_can_resize = 1;
947 }
948 
949 void dictDisableResize(void) {
950     dict_can_resize = 0;
951 }
952 
953 #if 0
954 
955 /* The following is code that we don't use for Redis currently, but that is part
956 of the library. */
957 
958 /* ----------------------- Debugging ------------------------*/
959 
960 #define DICT_STATS_VECTLEN 50
961 static void _dictPrintStatsHt(dictht *ht) {
962     unsigned long i, slots = 0, chainlen, maxchainlen = 0;
963     unsigned long totchainlen = 0;
964     unsigned long clvector[DICT_STATS_VECTLEN];
965 
966     if (ht->used == 0) {
967         printf("No stats available for empty dictionaries\n");
968         return;
969     }
970 
971     for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
972     for (i = 0; i < ht->size; i++) {
973         dictEntry *he;
974 
975         if (ht->table[i] == NULL) {
976             clvector[0]++;
977             continue;
978         }
979         slots++;
980         /* For each hash entry on this slot... */
981         chainlen = 0;
982         he = ht->table[i];
983         while(he) {
984             chainlen++;
985             he = he->next;
986         }
987         clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
988         if (chainlen > maxchainlen) maxchainlen = chainlen;
989         totchainlen += chainlen;
990     }
991     printf("Hash table stats:\n");
992     printf(" table size: %ld\n", ht->size);
993     printf(" number of elements: %ld\n", ht->used);
994     printf(" different slots: %ld\n", slots);
995     printf(" max chain length: %ld\n", maxchainlen);
996     printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
997     printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
998     printf(" Chain length distribution:\n");
999     for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
1000         if (clvector[i] == 0) continue;
1001         printf("   %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
1002     }
1003 }
1004 
1005 void dictPrintStats(dict *d) {
1006     _dictPrintStatsHt(&d->ht[0]);
1007     if (dictIsRehashing(d)) {
1008         printf("-- Rehashing into ht[1]:\n");
1009         _dictPrintStatsHt(&d->ht[1]);
1010     }
1011 }
1012 
1013 /* ----------------------- StringCopy Hash Table Type ------------------------*/
1014 
1015 static unsigned int _dictStringCopyHTHashFunction(const void *key)
1016 {
1017     return dictGenHashFunction(key, strlen(key));
1018 }
1019 
1020 static void *_dictStringDup(void *privdata, const void *key)
1021 {
1022     int len = strlen(key);
1023     char *copy = zmalloc(len+1);
1024     DICT_NOTUSED(privdata);
1025 
1026     memcpy(copy, key, len);
1027     copy[len] = '\0';
1028     return copy;
1029 }
1030 
1031 static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
1032         const void *key2)
1033 {
1034     DICT_NOTUSED(privdata);
1035 
1036     return strcmp(key1, key2) == 0;
1037 }
1038 
1039 static void _dictStringDestructor(void *privdata, void *key)
1040 {
1041     DICT_NOTUSED(privdata);
1042 
1043     zfree(key);
1044 }
1045 
1046 dictType dictTypeHeapStringCopyKey = {
1047     _dictStringCopyHTHashFunction, /* hash function */
1048     _dictStringDup,                /* key dup */
1049     NULL,                          /* val dup */
1050     _dictStringCopyHTKeyCompare,   /* key compare */
1051     _dictStringDestructor,         /* key destructor */
1052     NULL                           /* val destructor */
1053 };
1054 
1055 /* This is like StringCopy but does not auto-duplicate the key.
1056  * It's used for intepreter's shared strings. */
1057 dictType dictTypeHeapStrings = {
1058     _dictStringCopyHTHashFunction, /* hash function */
1059     NULL,                          /* key dup */
1060     NULL,                          /* val dup */
1061     _dictStringCopyHTKeyCompare,   /* key compare */
1062     _dictStringDestructor,         /* key destructor */
1063     NULL                           /* val destructor */
1064 };
1065 
1066 /* This is like StringCopy but also automatically handle dynamic
1067  * allocated C strings as values. */
1068 dictType dictTypeHeapStringCopyKeyValue = {
1069     _dictStringCopyHTHashFunction, /* hash function */
1070     _dictStringDup,                /* key dup */
1071     _dictStringDup,                /* val dup */
1072     _dictStringCopyHTKeyCompare,   /* key compare */
1073     _dictStringDestructor,         /* key destructor */
1074     _dictStringDestructor,         /* val destructor */
1075 };
1076 #endif
1077