]>
Commit | Line | Data |
---|---|---|
ed9b544e | 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 | * | |
12d090d2 | 8 | * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com> |
ed9b544e | 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 | ||
23d4709d | 36 | #include "fmacros.h" |
37 | ||
ed9b544e | 38 | #include <stdio.h> |
39 | #include <stdlib.h> | |
40 | #include <string.h> | |
41 | #include <stdarg.h> | |
42 | #include <assert.h> | |
f2923bec | 43 | #include <limits.h> |
8ca3e9d1 | 44 | #include <sys/time.h> |
1b1f47c9 | 45 | #include <ctype.h> |
ed9b544e | 46 | |
47 | #include "dict.h" | |
48 | #include "zmalloc.h" | |
49 | ||
884d4b39 | 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 | |
3856f147 | 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: an hash table is still allowed to grow if the ratio between | |
57 | * the number of elements and the buckets > dict_force_resize_ratio. */ | |
884d4b39 | 58 | static int dict_can_resize = 1; |
3856f147 | 59 | static unsigned int dict_force_resize_ratio = 5; |
884d4b39 | 60 | |
ed9b544e | 61 | /* -------------------------- private prototypes ---------------------------- */ |
62 | ||
63 | static int _dictExpandIfNeeded(dict *ht); | |
f2923bec | 64 | static unsigned long _dictNextPower(unsigned long size); |
ed9b544e | 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 | /* Generic hash function (a popular one from Bernstein). | |
89 | * I tested a few and this was the best. */ | |
90 | unsigned int dictGenHashFunction(const unsigned char *buf, int len) { | |
91 | unsigned int hash = 5381; | |
92 | ||
93 | while (len--) | |
94 | hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */ | |
95 | return hash; | |
96 | } | |
97 | ||
1b1f47c9 | 98 | /* And a case insensitive version */ |
99 | unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) { | |
100 | unsigned int hash = 5381; | |
101 | ||
102 | while (len--) | |
103 | hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */ | |
104 | return hash; | |
105 | } | |
106 | ||
ed9b544e | 107 | /* ----------------------------- API implementation ------------------------- */ |
108 | ||
109 | /* Reset an hashtable already initialized with ht_init(). | |
110 | * NOTE: This function should only called by ht_destroy(). */ | |
5413c40d | 111 | static void _dictReset(dictht *ht) |
ed9b544e | 112 | { |
113 | ht->table = NULL; | |
114 | ht->size = 0; | |
115 | ht->sizemask = 0; | |
116 | ht->used = 0; | |
117 | } | |
118 | ||
119 | /* Create a new hash table */ | |
120 | dict *dictCreate(dictType *type, | |
121 | void *privDataPtr) | |
122 | { | |
d9dd352b | 123 | dict *d = zmalloc(sizeof(*d)); |
ed9b544e | 124 | |
5413c40d | 125 | _dictInit(d,type,privDataPtr); |
126 | return d; | |
ed9b544e | 127 | } |
128 | ||
129 | /* Initialize the hash table */ | |
5413c40d | 130 | int _dictInit(dict *d, dictType *type, |
ed9b544e | 131 | void *privDataPtr) |
132 | { | |
5413c40d | 133 | _dictReset(&d->ht[0]); |
134 | _dictReset(&d->ht[1]); | |
135 | d->type = type; | |
136 | d->privdata = privDataPtr; | |
137 | d->rehashidx = -1; | |
138 | d->iterators = 0; | |
ed9b544e | 139 | return DICT_OK; |
140 | } | |
141 | ||
142 | /* Resize the table to the minimal size that contains all the elements, | |
3856f147 | 143 | * but with the invariant of a USER/BUCKETS ratio near to <= 1 */ |
5413c40d | 144 | int dictResize(dict *d) |
ed9b544e | 145 | { |
5413c40d | 146 | int minimal; |
ed9b544e | 147 | |
5413c40d | 148 | if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR; |
149 | minimal = d->ht[0].used; | |
ed9b544e | 150 | if (minimal < DICT_HT_INITIAL_SIZE) |
151 | minimal = DICT_HT_INITIAL_SIZE; | |
5413c40d | 152 | return dictExpand(d, minimal); |
ed9b544e | 153 | } |
154 | ||
155 | /* Expand or create the hashtable */ | |
5413c40d | 156 | int dictExpand(dict *d, unsigned long size) |
ed9b544e | 157 | { |
5413c40d | 158 | dictht n; /* the new hashtable */ |
159 | unsigned long realsize = _dictNextPower(size); | |
ed9b544e | 160 | |
161 | /* the size is invalid if it is smaller than the number of | |
162 | * elements already inside the hashtable */ | |
5413c40d | 163 | if (dictIsRehashing(d) || d->ht[0].used > size) |
ed9b544e | 164 | return DICT_ERR; |
165 | ||
399f2f40 | 166 | /* Allocate the new hashtable and initialize all pointers to NULL */ |
ed9b544e | 167 | n.size = realsize; |
168 | n.sizemask = realsize-1; | |
399f2f40 | 169 | n.table = zcalloc(realsize*sizeof(dictEntry*)); |
5413c40d | 170 | n.used = 0; |
ed9b544e | 171 | |
5413c40d | 172 | /* Is this the first initialization? If so it's not really a rehashing |
173 | * we just set the first hash table so that it can accept keys. */ | |
174 | if (d->ht[0].table == NULL) { | |
175 | d->ht[0] = n; | |
176 | return DICT_OK; | |
177 | } | |
ed9b544e | 178 | |
5413c40d | 179 | /* Prepare a second hash table for incremental rehashing */ |
180 | d->ht[1] = n; | |
181 | d->rehashidx = 0; | |
182 | return DICT_OK; | |
183 | } | |
184 | ||
185 | /* Performs N steps of incremental rehashing. Returns 1 if there are still | |
186 | * keys to move from the old to the new hash table, otherwise 0 is returned. | |
187 | * Note that a rehashing step consists in moving a bucket (that may have more | |
188 | * thank one key as we use chaining) from the old to the new hash table. */ | |
189 | int dictRehash(dict *d, int n) { | |
190 | if (!dictIsRehashing(d)) return 0; | |
191 | ||
192 | while(n--) { | |
193 | dictEntry *de, *nextde; | |
194 | ||
195 | /* Check if we already rehashed the whole table... */ | |
196 | if (d->ht[0].used == 0) { | |
d9dd352b | 197 | zfree(d->ht[0].table); |
5413c40d | 198 | d->ht[0] = d->ht[1]; |
199 | _dictReset(&d->ht[1]); | |
200 | d->rehashidx = -1; | |
201 | return 0; | |
202 | } | |
203 | ||
204 | /* Note that rehashidx can't overflow as we are sure there are more | |
205 | * elements because ht[0].used != 0 */ | |
05600eb8 | 206 | assert(d->ht[0].size > (unsigned)d->rehashidx); |
5413c40d | 207 | while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++; |
208 | de = d->ht[0].table[d->rehashidx]; | |
209 | /* Move all the keys in this bucket from the old to the new hash HT */ | |
210 | while(de) { | |
ed9b544e | 211 | unsigned int h; |
212 | ||
5413c40d | 213 | nextde = de->next; |
214 | /* Get the index in the new hash table */ | |
215 | h = dictHashKey(d, de->key) & d->ht[1].sizemask; | |
216 | de->next = d->ht[1].table[h]; | |
217 | d->ht[1].table[h] = de; | |
218 | d->ht[0].used--; | |
219 | d->ht[1].used++; | |
220 | de = nextde; | |
ed9b544e | 221 | } |
5413c40d | 222 | d->ht[0].table[d->rehashidx] = NULL; |
223 | d->rehashidx++; | |
ed9b544e | 224 | } |
5413c40d | 225 | return 1; |
226 | } | |
ed9b544e | 227 | |
8ca3e9d1 | 228 | long long timeInMilliseconds(void) { |
229 | struct timeval tv; | |
230 | ||
231 | gettimeofday(&tv,NULL); | |
232 | return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000); | |
233 | } | |
234 | ||
235 | /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */ | |
236 | int dictRehashMilliseconds(dict *d, int ms) { | |
237 | long long start = timeInMilliseconds(); | |
238 | int rehashes = 0; | |
239 | ||
240 | while(dictRehash(d,100)) { | |
241 | rehashes += 100; | |
242 | if (timeInMilliseconds()-start > ms) break; | |
243 | } | |
244 | return rehashes; | |
245 | } | |
246 | ||
5413c40d | 247 | /* This function performs just a step of rehashing, and only if there are |
4b53e736 | 248 | * no safe iterators bound to our hash table. When we have iterators in the |
249 | * middle of a rehashing we can't mess with the two hash tables otherwise | |
250 | * some element can be missed or duplicated. | |
5413c40d | 251 | * |
252 | * This function is called by common lookup or update operations in the | |
253 | * dictionary so that the hash table automatically migrates from H1 to H2 | |
254 | * while it is actively used. */ | |
255 | static void _dictRehashStep(dict *d) { | |
256 | if (d->iterators == 0) dictRehash(d,1); | |
ed9b544e | 257 | } |
258 | ||
259 | /* Add an element to the target hash table */ | |
5413c40d | 260 | int dictAdd(dict *d, void *key, void *val) |
71a50956 | 261 | { |
262 | dictEntry *entry = dictAddRaw(d,key); | |
263 | ||
264 | if (!entry) return DICT_ERR; | |
c0ba9ebe | 265 | dictSetVal(d, entry, val); |
71a50956 | 266 | return DICT_OK; |
267 | } | |
268 | ||
269 | /* Low level add. This function adds the entry but instead of setting | |
270 | * a value returns the dictEntry structure to the user, that will make | |
271 | * sure to fill the value field as he wishes. | |
272 | * | |
273 | * This function is also directly expoed to user API to be called | |
274 | * mainly in order to store non-pointers inside the hash value, example: | |
275 | * | |
276 | * entry = dictAddRaw(dict,mykey); | |
aa9a61cc | 277 | * if (entry != NULL) dictSetSignedIntegerVal(entry,1000); |
71a50956 | 278 | * |
279 | * Return values: | |
280 | * | |
281 | * If key already exists NULL is returned. | |
282 | * If key was added, the hash entry is returned to be manipulated by the caller. | |
283 | */ | |
284 | dictEntry *dictAddRaw(dict *d, void *key) | |
ed9b544e | 285 | { |
286 | int index; | |
287 | dictEntry *entry; | |
5413c40d | 288 | dictht *ht; |
289 | ||
290 | if (dictIsRehashing(d)) _dictRehashStep(d); | |
ed9b544e | 291 | |
292 | /* Get the index of the new element, or -1 if | |
293 | * the element already exists. */ | |
5413c40d | 294 | if ((index = _dictKeyIndex(d, key)) == -1) |
71a50956 | 295 | return NULL; |
ed9b544e | 296 | |
6a7841eb | 297 | /* Allocate the memory and store the new entry */ |
5413c40d | 298 | ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0]; |
d9dd352b | 299 | entry = zmalloc(sizeof(*entry)); |
ed9b544e | 300 | entry->next = ht->table[index]; |
301 | ht->table[index] = entry; | |
5413c40d | 302 | ht->used++; |
ed9b544e | 303 | |
304 | /* Set the hash entry fields. */ | |
c0ba9ebe | 305 | dictSetKey(d, entry, key); |
71a50956 | 306 | return entry; |
ed9b544e | 307 | } |
308 | ||
121796f7 | 309 | /* Add an element, discarding the old if the key already exists. |
310 | * Return 1 if the key was added from scratch, 0 if there was already an | |
311 | * element with such key and dictReplace() just performed a value update | |
312 | * operation. */ | |
5413c40d | 313 | int dictReplace(dict *d, void *key, void *val) |
ed9b544e | 314 | { |
2069d06a | 315 | dictEntry *entry, auxentry; |
ed9b544e | 316 | |
317 | /* Try to add the element. If the key | |
318 | * does not exists dictAdd will suceed. */ | |
5413c40d | 319 | if (dictAdd(d, key, val) == DICT_OK) |
121796f7 | 320 | return 1; |
ed9b544e | 321 | /* It already exists, get the entry */ |
5413c40d | 322 | entry = dictFind(d, key); |
2069d06a | 323 | /* Set the new value and free the old one. Note that it is important |
324 | * to do that in this order, as the value may just be exactly the same | |
325 | * as the previous one. In this context, think to reference counting, | |
326 | * you want to increment (set), and then decrement (free), and not the | |
327 | * reverse. */ | |
328 | auxentry = *entry; | |
c0ba9ebe | 329 | dictSetVal(d, entry, val); |
330 | dictFreeVal(d, &auxentry); | |
121796f7 | 331 | return 0; |
ed9b544e | 332 | } |
333 | ||
71a50956 | 334 | /* dictReplaceRaw() is simply a version of dictAddRaw() that always |
335 | * returns the hash entry of the specified key, even if the key already | |
336 | * exists and can't be added (in that case the entry of the already | |
337 | * existing key is returned.) | |
338 | * | |
339 | * See dictAddRaw() for more information. */ | |
340 | dictEntry *dictReplaceRaw(dict *d, void *key) { | |
341 | dictEntry *entry = dictFind(d,key); | |
342 | ||
343 | return entry ? entry : dictAddRaw(d,key); | |
344 | } | |
345 | ||
ed9b544e | 346 | /* Search and remove an element */ |
5413c40d | 347 | static int dictGenericDelete(dict *d, const void *key, int nofree) |
ed9b544e | 348 | { |
5413c40d | 349 | unsigned int h, idx; |
ed9b544e | 350 | dictEntry *he, *prevHe; |
5413c40d | 351 | int table; |
ed9b544e | 352 | |
5413c40d | 353 | if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */ |
354 | if (dictIsRehashing(d)) _dictRehashStep(d); | |
355 | h = dictHashKey(d, key); | |
ed9b544e | 356 | |
5413c40d | 357 | for (table = 0; table <= 1; table++) { |
358 | idx = h & d->ht[table].sizemask; | |
359 | he = d->ht[table].table[idx]; | |
360 | prevHe = NULL; | |
361 | while(he) { | |
c0ba9ebe | 362 | if (dictCompareKeys(d, key, he->key)) { |
5413c40d | 363 | /* Unlink the element from the list */ |
364 | if (prevHe) | |
365 | prevHe->next = he->next; | |
366 | else | |
367 | d->ht[table].table[idx] = he->next; | |
368 | if (!nofree) { | |
c0ba9ebe | 369 | dictFreeKey(d, he); |
370 | dictFreeVal(d, he); | |
5413c40d | 371 | } |
d9dd352b | 372 | zfree(he); |
5413c40d | 373 | d->ht[table].used--; |
374 | return DICT_OK; | |
ed9b544e | 375 | } |
5413c40d | 376 | prevHe = he; |
377 | he = he->next; | |
ed9b544e | 378 | } |
5413c40d | 379 | if (!dictIsRehashing(d)) break; |
ed9b544e | 380 | } |
381 | return DICT_ERR; /* not found */ | |
382 | } | |
383 | ||
384 | int dictDelete(dict *ht, const void *key) { | |
385 | return dictGenericDelete(ht,key,0); | |
386 | } | |
387 | ||
388 | int dictDeleteNoFree(dict *ht, const void *key) { | |
389 | return dictGenericDelete(ht,key,1); | |
390 | } | |
391 | ||
5413c40d | 392 | /* Destroy an entire dictionary */ |
393 | int _dictClear(dict *d, dictht *ht) | |
ed9b544e | 394 | { |
f2923bec | 395 | unsigned long i; |
ed9b544e | 396 | |
397 | /* Free all the elements */ | |
398 | for (i = 0; i < ht->size && ht->used > 0; i++) { | |
399 | dictEntry *he, *nextHe; | |
400 | ||
401 | if ((he = ht->table[i]) == NULL) continue; | |
402 | while(he) { | |
403 | nextHe = he->next; | |
c0ba9ebe | 404 | dictFreeKey(d, he); |
405 | dictFreeVal(d, he); | |
d9dd352b | 406 | zfree(he); |
ed9b544e | 407 | ht->used--; |
408 | he = nextHe; | |
409 | } | |
410 | } | |
411 | /* Free the table and the allocated cache structure */ | |
d9dd352b | 412 | zfree(ht->table); |
ed9b544e | 413 | /* Re-initialize the table */ |
414 | _dictReset(ht); | |
415 | return DICT_OK; /* never fails */ | |
416 | } | |
417 | ||
418 | /* Clear & Release the hash table */ | |
5413c40d | 419 | void dictRelease(dict *d) |
ed9b544e | 420 | { |
5413c40d | 421 | _dictClear(d,&d->ht[0]); |
422 | _dictClear(d,&d->ht[1]); | |
d9dd352b | 423 | zfree(d); |
ed9b544e | 424 | } |
425 | ||
5413c40d | 426 | dictEntry *dictFind(dict *d, const void *key) |
ed9b544e | 427 | { |
428 | dictEntry *he; | |
5413c40d | 429 | unsigned int h, idx, table; |
430 | ||
431 | if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */ | |
432 | if (dictIsRehashing(d)) _dictRehashStep(d); | |
433 | h = dictHashKey(d, key); | |
434 | for (table = 0; table <= 1; table++) { | |
435 | idx = h & d->ht[table].sizemask; | |
436 | he = d->ht[table].table[idx]; | |
437 | while(he) { | |
c0ba9ebe | 438 | if (dictCompareKeys(d, key, he->key)) |
5413c40d | 439 | return he; |
440 | he = he->next; | |
441 | } | |
442 | if (!dictIsRehashing(d)) return NULL; | |
ed9b544e | 443 | } |
444 | return NULL; | |
445 | } | |
446 | ||
58e1c9c1 | 447 | void *dictFetchValue(dict *d, const void *key) { |
448 | dictEntry *he; | |
449 | ||
450 | he = dictFind(d,key); | |
c0ba9ebe | 451 | return he ? dictGetVal(he) : NULL; |
58e1c9c1 | 452 | } |
453 | ||
5413c40d | 454 | dictIterator *dictGetIterator(dict *d) |
ed9b544e | 455 | { |
d9dd352b | 456 | dictIterator *iter = zmalloc(sizeof(*iter)); |
ed9b544e | 457 | |
5413c40d | 458 | iter->d = d; |
459 | iter->table = 0; | |
ed9b544e | 460 | iter->index = -1; |
4b53e736 | 461 | iter->safe = 0; |
ed9b544e | 462 | iter->entry = NULL; |
463 | iter->nextEntry = NULL; | |
464 | return iter; | |
465 | } | |
466 | ||
4b53e736 | 467 | dictIterator *dictGetSafeIterator(dict *d) { |
468 | dictIterator *i = dictGetIterator(d); | |
469 | ||
470 | i->safe = 1; | |
471 | return i; | |
472 | } | |
473 | ||
ed9b544e | 474 | dictEntry *dictNext(dictIterator *iter) |
475 | { | |
476 | while (1) { | |
477 | if (iter->entry == NULL) { | |
5413c40d | 478 | dictht *ht = &iter->d->ht[iter->table]; |
4b53e736 | 479 | if (iter->safe && iter->index == -1 && iter->table == 0) |
480 | iter->d->iterators++; | |
ed9b544e | 481 | iter->index++; |
5413c40d | 482 | if (iter->index >= (signed) ht->size) { |
483 | if (dictIsRehashing(iter->d) && iter->table == 0) { | |
484 | iter->table++; | |
485 | iter->index = 0; | |
486 | ht = &iter->d->ht[1]; | |
487 | } else { | |
488 | break; | |
489 | } | |
490 | } | |
491 | iter->entry = ht->table[iter->index]; | |
ed9b544e | 492 | } else { |
493 | iter->entry = iter->nextEntry; | |
494 | } | |
495 | if (iter->entry) { | |
496 | /* We need to save the 'next' here, the iterator user | |
497 | * may delete the entry we are returning. */ | |
498 | iter->nextEntry = iter->entry->next; | |
499 | return iter->entry; | |
500 | } | |
501 | } | |
502 | return NULL; | |
503 | } | |
504 | ||
505 | void dictReleaseIterator(dictIterator *iter) | |
506 | { | |
4b53e736 | 507 | if (iter->safe && !(iter->index == -1 && iter->table == 0)) |
508 | iter->d->iterators--; | |
d9dd352b | 509 | zfree(iter); |
ed9b544e | 510 | } |
511 | ||
512 | /* Return a random entry from the hash table. Useful to | |
513 | * implement randomized algorithms */ | |
5413c40d | 514 | dictEntry *dictGetRandomKey(dict *d) |
ed9b544e | 515 | { |
5413c40d | 516 | dictEntry *he, *orighe; |
ed9b544e | 517 | unsigned int h; |
518 | int listlen, listele; | |
519 | ||
5413c40d | 520 | if (dictSize(d) == 0) return NULL; |
521 | if (dictIsRehashing(d)) _dictRehashStep(d); | |
522 | if (dictIsRehashing(d)) { | |
523 | do { | |
524 | h = random() % (d->ht[0].size+d->ht[1].size); | |
525 | he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] : | |
526 | d->ht[0].table[h]; | |
527 | } while(he == NULL); | |
528 | } else { | |
529 | do { | |
530 | h = random() & d->ht[0].sizemask; | |
531 | he = d->ht[0].table[h]; | |
532 | } while(he == NULL); | |
533 | } | |
ed9b544e | 534 | |
535 | /* Now we found a non empty bucket, but it is a linked | |
536 | * list and we need to get a random element from the list. | |
5413c40d | 537 | * The only sane way to do so is counting the elements and |
ed9b544e | 538 | * select a random index. */ |
539 | listlen = 0; | |
5413c40d | 540 | orighe = he; |
ed9b544e | 541 | while(he) { |
542 | he = he->next; | |
543 | listlen++; | |
544 | } | |
545 | listele = random() % listlen; | |
5413c40d | 546 | he = orighe; |
ed9b544e | 547 | while(listele--) he = he->next; |
548 | return he; | |
549 | } | |
550 | ||
551 | /* ------------------------- private functions ------------------------------ */ | |
552 | ||
553 | /* Expand the hash table if needed */ | |
5413c40d | 554 | static int _dictExpandIfNeeded(dict *d) |
ed9b544e | 555 | { |
3856f147 | 556 | /* Incremental rehashing already in progress. Return. */ |
5413c40d | 557 | if (dictIsRehashing(d)) return DICT_OK; |
3856f147 | 558 | |
559 | /* If the hash table is empty expand it to the intial size. */ | |
560 | if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE); | |
561 | ||
562 | /* If we reached the 1:1 ratio, and we are allowed to resize the hash | |
563 | * table (global setting) or we should avoid it but the ratio between | |
564 | * elements/buckets is over the "safe" threshold, we resize doubling | |
565 | * the number of buckets. */ | |
566 | if (d->ht[0].used >= d->ht[0].size && | |
567 | (dict_can_resize || | |
568 | d->ht[0].used/d->ht[0].size > dict_force_resize_ratio)) | |
569 | { | |
5413c40d | 570 | return dictExpand(d, ((d->ht[0].size > d->ht[0].used) ? |
571 | d->ht[0].size : d->ht[0].used)*2); | |
3856f147 | 572 | } |
ed9b544e | 573 | return DICT_OK; |
574 | } | |
575 | ||
576 | /* Our hash table capability is a power of two */ | |
f2923bec | 577 | static unsigned long _dictNextPower(unsigned long size) |
ed9b544e | 578 | { |
f2923bec | 579 | unsigned long i = DICT_HT_INITIAL_SIZE; |
ed9b544e | 580 | |
f2923bec | 581 | if (size >= LONG_MAX) return LONG_MAX; |
ed9b544e | 582 | while(1) { |
583 | if (i >= size) | |
584 | return i; | |
585 | i *= 2; | |
586 | } | |
587 | } | |
588 | ||
589 | /* Returns the index of a free slot that can be populated with | |
590 | * an hash entry for the given 'key'. | |
5413c40d | 591 | * If the key already exists, -1 is returned. |
592 | * | |
593 | * Note that if we are in the process of rehashing the hash table, the | |
594 | * index is always returned in the context of the second (new) hash table. */ | |
595 | static int _dictKeyIndex(dict *d, const void *key) | |
ed9b544e | 596 | { |
8ca3e9d1 | 597 | unsigned int h, idx, table; |
ed9b544e | 598 | dictEntry *he; |
599 | ||
600 | /* Expand the hashtable if needed */ | |
5413c40d | 601 | if (_dictExpandIfNeeded(d) == DICT_ERR) |
ed9b544e | 602 | return -1; |
603 | /* Compute the key hash value */ | |
5413c40d | 604 | h = dictHashKey(d, key); |
8ca3e9d1 | 605 | for (table = 0; table <= 1; table++) { |
606 | idx = h & d->ht[table].sizemask; | |
607 | /* Search if this slot does not already contain the given key */ | |
608 | he = d->ht[table].table[idx]; | |
609 | while(he) { | |
c0ba9ebe | 610 | if (dictCompareKeys(d, key, he->key)) |
8ca3e9d1 | 611 | return -1; |
612 | he = he->next; | |
613 | } | |
614 | if (!dictIsRehashing(d)) break; | |
ed9b544e | 615 | } |
8ca3e9d1 | 616 | return idx; |
ed9b544e | 617 | } |
618 | ||
5413c40d | 619 | void dictEmpty(dict *d) { |
620 | _dictClear(d,&d->ht[0]); | |
621 | _dictClear(d,&d->ht[1]); | |
622 | d->rehashidx = -1; | |
623 | d->iterators = 0; | |
ed9b544e | 624 | } |
625 | ||
626 | #define DICT_STATS_VECTLEN 50 | |
5413c40d | 627 | static void _dictPrintStatsHt(dictht *ht) { |
f2923bec | 628 | unsigned long i, slots = 0, chainlen, maxchainlen = 0; |
629 | unsigned long totchainlen = 0; | |
630 | unsigned long clvector[DICT_STATS_VECTLEN]; | |
ed9b544e | 631 | |
632 | if (ht->used == 0) { | |
633 | printf("No stats available for empty dictionaries\n"); | |
634 | return; | |
635 | } | |
636 | ||
637 | for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0; | |
638 | for (i = 0; i < ht->size; i++) { | |
639 | dictEntry *he; | |
640 | ||
641 | if (ht->table[i] == NULL) { | |
642 | clvector[0]++; | |
643 | continue; | |
644 | } | |
645 | slots++; | |
646 | /* For each hash entry on this slot... */ | |
647 | chainlen = 0; | |
648 | he = ht->table[i]; | |
649 | while(he) { | |
650 | chainlen++; | |
651 | he = he->next; | |
652 | } | |
653 | clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++; | |
654 | if (chainlen > maxchainlen) maxchainlen = chainlen; | |
655 | totchainlen += chainlen; | |
656 | } | |
657 | printf("Hash table stats:\n"); | |
f2923bec | 658 | printf(" table size: %ld\n", ht->size); |
659 | printf(" number of elements: %ld\n", ht->used); | |
660 | printf(" different slots: %ld\n", slots); | |
661 | printf(" max chain length: %ld\n", maxchainlen); | |
ed9b544e | 662 | printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots); |
663 | printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots); | |
664 | printf(" Chain length distribution:\n"); | |
665 | for (i = 0; i < DICT_STATS_VECTLEN-1; i++) { | |
666 | if (clvector[i] == 0) continue; | |
f2923bec | 667 | printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100); |
ed9b544e | 668 | } |
669 | } | |
670 | ||
5413c40d | 671 | void dictPrintStats(dict *d) { |
672 | _dictPrintStatsHt(&d->ht[0]); | |
673 | if (dictIsRehashing(d)) { | |
674 | printf("-- Rehashing into ht[1]:\n"); | |
675 | _dictPrintStatsHt(&d->ht[1]); | |
676 | } | |
677 | } | |
678 | ||
884d4b39 | 679 | void dictEnableResize(void) { |
680 | dict_can_resize = 1; | |
681 | } | |
682 | ||
683 | void dictDisableResize(void) { | |
dae121d9 | 684 | dict_can_resize = 0; |
884d4b39 | 685 | } |
686 | ||
e0be2289 | 687 | #if 0 |
688 | ||
689 | /* The following are just example hash table types implementations. | |
690 | * Not useful for Redis so they are commented out. | |
691 | */ | |
692 | ||
ed9b544e | 693 | /* ----------------------- StringCopy Hash Table Type ------------------------*/ |
694 | ||
695 | static unsigned int _dictStringCopyHTHashFunction(const void *key) | |
696 | { | |
697 | return dictGenHashFunction(key, strlen(key)); | |
698 | } | |
699 | ||
b1e0bd4b | 700 | static void *_dictStringDup(void *privdata, const void *key) |
ed9b544e | 701 | { |
702 | int len = strlen(key); | |
d9dd352b | 703 | char *copy = zmalloc(len+1); |
ed9b544e | 704 | DICT_NOTUSED(privdata); |
705 | ||
706 | memcpy(copy, key, len); | |
707 | copy[len] = '\0'; | |
708 | return copy; | |
709 | } | |
710 | ||
ed9b544e | 711 | static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1, |
712 | const void *key2) | |
713 | { | |
714 | DICT_NOTUSED(privdata); | |
715 | ||
716 | return strcmp(key1, key2) == 0; | |
717 | } | |
718 | ||
b1e0bd4b | 719 | static void _dictStringDestructor(void *privdata, void *key) |
ed9b544e | 720 | { |
721 | DICT_NOTUSED(privdata); | |
722 | ||
d9dd352b | 723 | zfree(key); |
ed9b544e | 724 | } |
725 | ||
726 | dictType dictTypeHeapStringCopyKey = { | |
b1e0bd4b BK |
727 | _dictStringCopyHTHashFunction, /* hash function */ |
728 | _dictStringDup, /* key dup */ | |
729 | NULL, /* val dup */ | |
730 | _dictStringCopyHTKeyCompare, /* key compare */ | |
731 | _dictStringDestructor, /* key destructor */ | |
732 | NULL /* val destructor */ | |
ed9b544e | 733 | }; |
734 | ||
735 | /* This is like StringCopy but does not auto-duplicate the key. | |
736 | * It's used for intepreter's shared strings. */ | |
737 | dictType dictTypeHeapStrings = { | |
b1e0bd4b BK |
738 | _dictStringCopyHTHashFunction, /* hash function */ |
739 | NULL, /* key dup */ | |
740 | NULL, /* val dup */ | |
741 | _dictStringCopyHTKeyCompare, /* key compare */ | |
742 | _dictStringDestructor, /* key destructor */ | |
743 | NULL /* val destructor */ | |
ed9b544e | 744 | }; |
745 | ||
746 | /* This is like StringCopy but also automatically handle dynamic | |
747 | * allocated C strings as values. */ | |
748 | dictType dictTypeHeapStringCopyKeyValue = { | |
b1e0bd4b BK |
749 | _dictStringCopyHTHashFunction, /* hash function */ |
750 | _dictStringDup, /* key dup */ | |
751 | _dictStringDup, /* val dup */ | |
752 | _dictStringCopyHTKeyCompare, /* key compare */ | |
753 | _dictStringDestructor, /* key destructor */ | |
754 | _dictStringDestructor, /* val destructor */ | |
ed9b544e | 755 | }; |
e0be2289 | 756 | #endif |