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