]> git.saurik.com Git - apple/icu.git/blob - icuSources/common/uhash.c
ICU-6.2.22.tar.gz
[apple/icu.git] / icuSources / common / uhash.c
1 /*
2 ******************************************************************************
3 * Copyright (C) 1997-2004, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 ******************************************************************************
6 * Date Name Description
7 * 03/22/00 aliu Adapted from original C++ ICU Hashtable.
8 * 07/06/01 aliu Modified to support int32_t keys on
9 * platforms with sizeof(void*) < 32.
10 ******************************************************************************
11 */
12
13 #include "uhash.h"
14 #include "unicode/ustring.h"
15 #include "cstring.h"
16 #include "cmemory.h"
17 #include "uassert.h"
18
19 /* This hashtable is implemented as a double hash. All elements are
20 * stored in a single array with no secondary storage for collision
21 * resolution (no linked list, etc.). When there is a hash collision
22 * (when two unequal keys have the same hashcode) we resolve this by
23 * using a secondary hash. The secondary hash is an increment
24 * computed as a hash function (a different one) of the primary
25 * hashcode. This increment is added to the initial hash value to
26 * obtain further slots assigned to the same hash code. For this to
27 * work, the length of the array and the increment must be relatively
28 * prime. The easiest way to achieve this is to have the length of
29 * the array be prime, and the increment be any value from
30 * 1..length-1.
31 *
32 * Hashcodes are 32-bit integers. We make sure all hashcodes are
33 * non-negative by masking off the top bit. This has two effects: (1)
34 * modulo arithmetic is simplified. If we allowed negative hashcodes,
35 * then when we computed hashcode % length, we could get a negative
36 * result, which we would then have to adjust back into range. It's
37 * simpler to just make hashcodes non-negative. (2) It makes it easy
38 * to check for empty vs. occupied slots in the table. We just mark
39 * empty or deleted slots with a negative hashcode.
40 *
41 * The central function is _uhash_find(). This function looks for a
42 * slot matching the given key and hashcode. If one is found, it
43 * returns a pointer to that slot. If the table is full, and no match
44 * is found, it returns NULL -- in theory. This would make the code
45 * more complicated, since all callers of _uhash_find() would then
46 * have to check for a NULL result. To keep this from happening, we
47 * don't allow the table to fill. When there is only one
48 * empty/deleted slot left, uhash_put() will refuse to increase the
49 * count, and fail. This simplifies the code. In practice, one will
50 * seldom encounter this using default UHashtables. However, if a
51 * hashtable is set to a U_FIXED resize policy, or if memory is
52 * exhausted, then the table may fill.
53 *
54 * High and low water ratios control rehashing. They establish levels
55 * of fullness (from 0 to 1) outside of which the data array is
56 * reallocated and repopulated. Setting the low water ratio to zero
57 * means the table will never shrink. Setting the high water ratio to
58 * one means the table will never grow. The ratios should be
59 * coordinated with the ratio between successive elements of the
60 * PRIMES table, so that when the primeIndex is incremented or
61 * decremented during rehashing, it brings the ratio of count / length
62 * back into the desired range (between low and high water ratios).
63 */
64
65 /********************************************************************
66 * PRIVATE Constants, Macros
67 ********************************************************************/
68
69 /* This is a list of non-consecutive primes chosen such that
70 * PRIMES[i+1] ~ 2*PRIMES[i]. (Currently, the ratio ranges from 1.81
71 * to 2.18; the inverse ratio ranges from 0.459 to 0.552.) If this
72 * ratio is changed, the low and high water ratios should also be
73 * adjusted to suit.
74 *
75 * These prime numbers were also chosen so that they are the largest
76 * prime number while being less than a power of two.
77 */
78 static const int32_t PRIMES[] = {
79 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749,
80 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593,
81 16777213, 33554393, 67108859, 134217689, 268435399, 536870909,
82 1073741789, 2147483647 /*, 4294967291 */
83 };
84
85 #define PRIMES_LENGTH (sizeof(PRIMES) / sizeof(PRIMES[0]))
86
87 /* These ratios are tuned to the PRIMES array such that a resize
88 * places the table back into the zone of non-resizing. That is,
89 * after a call to _uhash_rehash(), a subsequent call to
90 * _uhash_rehash() should do nothing (should not churn). This is only
91 * a potential problem with U_GROW_AND_SHRINK.
92 */
93 static const float RESIZE_POLICY_RATIO_TABLE[6] = {
94 /* low, high water ratio */
95 0.0F, 0.5F, /* U_GROW: Grow on demand, do not shrink */
96 0.1F, 0.5F, /* U_GROW_AND_SHRINK: Grow and shrink on demand */
97 0.0F, 1.0F /* U_FIXED: Never change size */
98 };
99
100 /*
101 Invariants for hashcode values:
102
103 * DELETED < 0
104 * EMPTY < 0
105 * Real hashes >= 0
106
107 Hashcodes may not start out this way, but internally they are
108 adjusted so that they are always positive. We assume 32-bit
109 hashcodes; adjust these constants for other hashcode sizes.
110 */
111 #define HASH_DELETED ((int32_t) 0x80000000)
112 #define HASH_EMPTY ((int32_t) HASH_DELETED + 1)
113
114 #define IS_EMPTY_OR_DELETED(x) ((x) < 0)
115
116 /* This macro expects a UHashTok.pointer as its keypointer and
117 valuepointer parameters */
118 #define HASH_DELETE_KEY_VALUE(hash, keypointer, valuepointer) \
119 if (hash->keyDeleter != NULL && keypointer != NULL) { \
120 (*hash->keyDeleter)(keypointer); \
121 } \
122 if (hash->valueDeleter != NULL && valuepointer != NULL) { \
123 (*hash->valueDeleter)(valuepointer); \
124 }
125
126 /*
127 * Constants for hinting whether a key or value is an integer
128 * or a pointer. If a hint bit is zero, then the associated
129 * token is assumed to be an integer.
130 */
131 #define HINT_KEY_POINTER (1)
132 #define HINT_VALUE_POINTER (2)
133
134 /********************************************************************
135 * Debugging
136 ********************************************************************/
137
138
139 /********************************************************************
140 * PRIVATE Prototypes
141 ********************************************************************/
142
143 static UHashtable* _uhash_create(UHashFunction *keyHash, UKeyComparator *keyComp,
144 int32_t primeIndex, UErrorCode *status);
145
146 static void _uhash_allocate(UHashtable *hash, int32_t primeIndex,
147 UErrorCode *status);
148
149 static void _uhash_rehash(UHashtable *hash);
150
151 static UHashElement* _uhash_find(const UHashtable *hash, UHashTok key,
152 int32_t hashcode);
153
154 static UHashTok _uhash_put(UHashtable *hash,
155 UHashTok key,
156 UHashTok value,
157 int8_t hint,
158 UErrorCode *status);
159
160 static UHashTok _uhash_remove(UHashtable *hash,
161 UHashTok key);
162
163 static UHashTok _uhash_internalRemoveElement(UHashtable *hash, UHashElement* e);
164
165 static UHashTok _uhash_setElement(UHashtable* hash, UHashElement* e,
166 int32_t hashcode,
167 UHashTok key, UHashTok value,
168 int8_t hint);
169
170 static void _uhash_internalSetResizePolicy(UHashtable *hash, enum UHashResizePolicy policy);
171
172 /********************************************************************
173 * PUBLIC API
174 ********************************************************************/
175
176 U_CAPI UHashtable* U_EXPORT2
177 uhash_open(UHashFunction *keyHash, UKeyComparator *keyComp,
178 UErrorCode *status) {
179
180 return _uhash_create(keyHash, keyComp, 3, status);
181 }
182
183 U_CAPI UHashtable* U_EXPORT2
184 uhash_openSize(UHashFunction *keyHash, UKeyComparator *keyComp,
185 int32_t size,
186 UErrorCode *status) {
187
188 /* Find the smallest index i for which PRIMES[i] >= size. */
189 int32_t i = 0;
190 while (i<(PRIMES_LENGTH-1) && PRIMES[i]<size) {
191 ++i;
192 }
193
194 return _uhash_create(keyHash, keyComp, i, status);
195 }
196
197 U_CAPI void U_EXPORT2
198 uhash_close(UHashtable *hash) {
199 U_ASSERT(hash != NULL);
200 if (hash->elements != NULL) {
201 if (hash->keyDeleter != NULL || hash->valueDeleter != NULL) {
202 int32_t pos=-1;
203 UHashElement *e;
204 while ((e = (UHashElement*) uhash_nextElement(hash, &pos)) != NULL) {
205 HASH_DELETE_KEY_VALUE(hash, e->key.pointer, e->value.pointer);
206 }
207 }
208 uprv_free(hash->elements);
209 hash->elements = NULL;
210 }
211 uprv_free(hash);
212 }
213
214 U_CAPI UHashFunction *U_EXPORT2
215 uhash_setKeyHasher(UHashtable *hash, UHashFunction *fn) {
216 UHashFunction *result = hash->keyHasher;
217 hash->keyHasher = fn;
218 return result;
219 }
220
221 U_CAPI UKeyComparator *U_EXPORT2
222 uhash_setKeyComparator(UHashtable *hash, UKeyComparator *fn) {
223 UKeyComparator *result = hash->keyComparator;
224 hash->keyComparator = fn;
225 return result;
226 }
227
228 U_CAPI UObjectDeleter *U_EXPORT2
229 uhash_setKeyDeleter(UHashtable *hash, UObjectDeleter *fn) {
230 UObjectDeleter *result = hash->keyDeleter;
231 hash->keyDeleter = fn;
232 return result;
233 }
234
235 U_CAPI UObjectDeleter *U_EXPORT2
236 uhash_setValueDeleter(UHashtable *hash, UObjectDeleter *fn) {
237 UObjectDeleter *result = hash->valueDeleter;
238 hash->valueDeleter = fn;
239 return result;
240 }
241
242 U_CAPI void U_EXPORT2
243 uhash_setResizePolicy(UHashtable *hash, enum UHashResizePolicy policy) {
244 _uhash_internalSetResizePolicy(hash, policy);
245 hash->lowWaterMark = (int32_t)(hash->length * hash->lowWaterRatio);
246 hash->highWaterMark = (int32_t)(hash->length * hash->highWaterRatio);
247 _uhash_rehash(hash);
248 }
249
250 U_CAPI int32_t U_EXPORT2
251 uhash_count(const UHashtable *hash) {
252 return hash->count;
253 }
254
255 U_CAPI void* U_EXPORT2
256 uhash_get(const UHashtable *hash,
257 const void* key) {
258 UHashTok keyholder;
259 keyholder.pointer = (void*) key;
260 return _uhash_find(hash, keyholder, hash->keyHasher(keyholder))->value.pointer;
261 }
262
263 U_CAPI void* U_EXPORT2
264 uhash_iget(const UHashtable *hash,
265 int32_t key) {
266 UHashTok keyholder;
267 keyholder.integer = key;
268 return _uhash_find(hash, keyholder, hash->keyHasher(keyholder))->value.pointer;
269 }
270
271 U_CAPI int32_t U_EXPORT2
272 uhash_geti(const UHashtable *hash,
273 const void* key) {
274 UHashTok keyholder;
275 keyholder.pointer = (void*) key;
276 return _uhash_find(hash, keyholder, hash->keyHasher(keyholder))->value.integer;
277 }
278
279 U_CAPI int32_t U_EXPORT2
280 uhash_igeti(const UHashtable *hash,
281 int32_t key) {
282 UHashTok keyholder;
283 keyholder.integer = key;
284 return _uhash_find(hash, keyholder, hash->keyHasher(keyholder))->value.integer;
285 }
286
287 U_CAPI void* U_EXPORT2
288 uhash_put(UHashtable *hash,
289 void* key,
290 void* value,
291 UErrorCode *status) {
292 UHashTok keyholder, valueholder;
293 keyholder.pointer = key;
294 valueholder.pointer = value;
295 return _uhash_put(hash, keyholder, valueholder,
296 HINT_KEY_POINTER | HINT_VALUE_POINTER,
297 status).pointer;
298 }
299
300 U_CAPI void* U_EXPORT2
301 uhash_iput(UHashtable *hash,
302 int32_t key,
303 void* value,
304 UErrorCode *status) {
305 UHashTok keyholder, valueholder;
306 keyholder.integer = key;
307 valueholder.pointer = value;
308 return _uhash_put(hash, keyholder, valueholder,
309 HINT_VALUE_POINTER,
310 status).pointer;
311 }
312
313 U_CAPI int32_t U_EXPORT2
314 uhash_puti(UHashtable *hash,
315 void* key,
316 int32_t value,
317 UErrorCode *status) {
318 UHashTok keyholder, valueholder;
319 keyholder.pointer = key;
320 valueholder.integer = value;
321 return _uhash_put(hash, keyholder, valueholder,
322 HINT_KEY_POINTER,
323 status).integer;
324 }
325
326
327 U_CAPI int32_t U_EXPORT2
328 uhash_iputi(UHashtable *hash,
329 int32_t key,
330 int32_t value,
331 UErrorCode *status) {
332 UHashTok keyholder, valueholder;
333 keyholder.integer = key;
334 valueholder.integer = value;
335 return _uhash_put(hash, keyholder, valueholder,
336 0, /* neither is a ptr */
337 status).integer;
338 }
339
340 U_CAPI void* U_EXPORT2
341 uhash_remove(UHashtable *hash,
342 const void* key) {
343 UHashTok keyholder;
344 keyholder.pointer = (void*) key;
345 return _uhash_remove(hash, keyholder).pointer;
346 }
347
348 U_CAPI void* U_EXPORT2
349 uhash_iremove(UHashtable *hash,
350 int32_t key) {
351 UHashTok keyholder;
352 keyholder.integer = key;
353 return _uhash_remove(hash, keyholder).pointer;
354 }
355
356 U_CAPI int32_t U_EXPORT2
357 uhash_removei(UHashtable *hash,
358 const void* key) {
359 UHashTok keyholder;
360 keyholder.pointer = (void*) key;
361 return _uhash_remove(hash, keyholder).integer;
362 }
363
364 U_CAPI int32_t U_EXPORT2
365 uhash_iremovei(UHashtable *hash,
366 int32_t key) {
367 UHashTok keyholder;
368 keyholder.integer = key;
369 return _uhash_remove(hash, keyholder).integer;
370 }
371
372 U_CAPI void U_EXPORT2
373 uhash_removeAll(UHashtable *hash) {
374 int32_t pos = -1;
375 const UHashElement *e;
376 U_ASSERT(hash != NULL);
377 if (hash->count != 0) {
378 while ((e = uhash_nextElement(hash, &pos)) != NULL) {
379 uhash_removeElement(hash, e);
380 }
381 }
382 U_ASSERT(hash->count == 0);
383 }
384
385 U_CAPI const UHashElement* U_EXPORT2
386 uhash_find(const UHashtable *hash, const void* key) {
387 UHashTok keyholder;
388 const UHashElement *e;
389 keyholder.pointer = (void*) key;
390 e = _uhash_find(hash, keyholder, hash->keyHasher(keyholder));
391 return IS_EMPTY_OR_DELETED(e->hashcode) ? NULL : e;
392 }
393
394 U_CAPI const UHashElement* U_EXPORT2
395 uhash_nextElement(const UHashtable *hash, int32_t *pos) {
396 /* Walk through the array until we find an element that is not
397 * EMPTY and not DELETED.
398 */
399 int32_t i;
400 U_ASSERT(hash != NULL);
401 for (i = *pos + 1; i < hash->length; ++i) {
402 if (!IS_EMPTY_OR_DELETED(hash->elements[i].hashcode)) {
403 *pos = i;
404 return &(hash->elements[i]);
405 }
406 }
407
408 /* No more elements */
409 return NULL;
410 }
411
412 U_CAPI void* U_EXPORT2
413 uhash_removeElement(UHashtable *hash, const UHashElement* e) {
414 U_ASSERT(hash != NULL);
415 U_ASSERT(e != NULL);
416 if (!IS_EMPTY_OR_DELETED(e->hashcode)) {
417 return _uhash_internalRemoveElement(hash, (UHashElement*) e).pointer;
418 }
419 return NULL;
420 }
421
422 /********************************************************************
423 * UHashTok convenience
424 ********************************************************************/
425
426 /**
427 * Return a UHashTok for an integer.
428 */
429 U_CAPI UHashTok U_EXPORT2
430 uhash_toki(int32_t i) {
431 UHashTok tok;
432 tok.integer = i;
433 return tok;
434 }
435
436 /**
437 * Return a UHashTok for a pointer.
438 */
439 U_CAPI UHashTok U_EXPORT2
440 uhash_tokp(void* p) {
441 UHashTok tok;
442 tok.pointer = p;
443 return tok;
444 }
445
446 /********************************************************************
447 * PUBLIC Key Hash Functions
448 ********************************************************************/
449
450 /*
451 Compute the hash by iterating sparsely over about 32 (up to 63)
452 characters spaced evenly through the string. For each character,
453 multiply the previous hash value by a prime number and add the new
454 character in, like a linear congruential random number generator,
455 producing a pseudorandom deterministic value well distributed over
456 the output range. [LIU]
457 */
458
459 #define STRING_HASH(TYPE, STR, STRLEN, DEREF) \
460 int32_t hash = 0; \
461 const TYPE *p = (const TYPE*) STR; \
462 if (p != NULL) { \
463 int32_t len = (int32_t)(STRLEN); \
464 int32_t inc = ((len - 32) / 32) + 1; \
465 const TYPE *limit = p + len; \
466 while (p<limit) { \
467 hash = (hash * 37) + DEREF; \
468 p += inc; \
469 } \
470 } \
471 return hash
472
473 U_CAPI int32_t U_EXPORT2
474 uhash_hashUChars(const UHashTok key) {
475 STRING_HASH(UChar, key.pointer, u_strlen(p), *p);
476 }
477
478 /* Used by UnicodeString to compute its hashcode - Not public API. */
479 U_CAPI int32_t U_EXPORT2
480 uhash_hashUCharsN(const UChar *str, int32_t length) {
481 STRING_HASH(UChar, str, length, *p);
482 }
483
484 U_CAPI int32_t U_EXPORT2
485 uhash_hashChars(const UHashTok key) {
486 STRING_HASH(uint8_t, key.pointer, uprv_strlen((char*)p), *p);
487 }
488
489 U_CAPI int32_t U_EXPORT2
490 uhash_hashIChars(const UHashTok key) {
491 STRING_HASH(uint8_t, key.pointer, uprv_strlen((char*)p), uprv_tolower(*p));
492 }
493
494 /********************************************************************
495 * PUBLIC Comparator Functions
496 ********************************************************************/
497
498 U_CAPI UBool U_EXPORT2
499 uhash_compareUChars(const UHashTok key1, const UHashTok key2) {
500 const UChar *p1 = (const UChar*) key1.pointer;
501 const UChar *p2 = (const UChar*) key2.pointer;
502 if (p1 == p2) {
503 return TRUE;
504 }
505 if (p1 == NULL || p2 == NULL) {
506 return FALSE;
507 }
508 while (*p1 != 0 && *p1 == *p2) {
509 ++p1;
510 ++p2;
511 }
512 return (UBool)(*p1 == *p2);
513 }
514
515 U_CAPI UBool U_EXPORT2
516 uhash_compareChars(const UHashTok key1, const UHashTok key2) {
517 const char *p1 = (const char*) key1.pointer;
518 const char *p2 = (const char*) key2.pointer;
519 if (p1 == p2) {
520 return TRUE;
521 }
522 if (p1 == NULL || p2 == NULL) {
523 return FALSE;
524 }
525 while (*p1 != 0 && *p1 == *p2) {
526 ++p1;
527 ++p2;
528 }
529 return (UBool)(*p1 == *p2);
530 }
531
532 U_CAPI UBool U_EXPORT2
533 uhash_compareIChars(const UHashTok key1, const UHashTok key2) {
534 const char *p1 = (const char*) key1.pointer;
535 const char *p2 = (const char*) key2.pointer;
536 if (p1 == p2) {
537 return TRUE;
538 }
539 if (p1 == NULL || p2 == NULL) {
540 return FALSE;
541 }
542 while (*p1 != 0 && uprv_tolower(*p1) == uprv_tolower(*p2)) {
543 ++p1;
544 ++p2;
545 }
546 return (UBool)(*p1 == *p2);
547 }
548
549 /********************************************************************
550 * PUBLIC int32_t Support Functions
551 ********************************************************************/
552
553 U_CAPI int32_t U_EXPORT2
554 uhash_hashLong(const UHashTok key) {
555 return key.integer;
556 }
557
558 U_CAPI UBool U_EXPORT2
559 uhash_compareLong(const UHashTok key1, const UHashTok key2) {
560 return (UBool)(key1.integer == key2.integer);
561 }
562
563 /********************************************************************
564 * PUBLIC Deleter Functions
565 ********************************************************************/
566
567 U_CAPI void U_EXPORT2
568 uhash_freeBlock(void *obj) {
569 uprv_free(obj);
570 }
571
572 /********************************************************************
573 * PRIVATE Implementation
574 ********************************************************************/
575
576 static UHashtable*
577 _uhash_create(UHashFunction *keyHash, UKeyComparator *keyComp,
578 int32_t primeIndex,
579 UErrorCode *status) {
580 UHashtable *result;
581
582 if (U_FAILURE(*status)) return NULL;
583 U_ASSERT(keyHash != NULL);
584 U_ASSERT(keyComp != NULL);
585
586 result = (UHashtable*) uprv_malloc(sizeof(UHashtable));
587 if (result == NULL) {
588 *status = U_MEMORY_ALLOCATION_ERROR;
589 return NULL;
590 }
591
592 result->keyHasher = keyHash;
593 result->keyComparator = keyComp;
594 result->keyDeleter = NULL;
595 result->valueDeleter = NULL;
596 _uhash_internalSetResizePolicy(result, U_GROW);
597
598 _uhash_allocate(result, primeIndex, status);
599
600 if (U_FAILURE(*status)) {
601 uprv_free(result);
602 return NULL;
603 }
604
605 return result;
606 }
607
608 /**
609 * Allocate internal data array of a size determined by the given
610 * prime index. If the index is out of range it is pinned into range.
611 * If the allocation fails the status is set to
612 * U_MEMORY_ALLOCATION_ERROR and all array storage is freed. In
613 * either case the previous array pointer is overwritten.
614 *
615 * Caller must ensure primeIndex is in range 0..PRIME_LENGTH-1.
616 */
617 static void
618 _uhash_allocate(UHashtable *hash,
619 int32_t primeIndex,
620 UErrorCode *status) {
621
622 UHashElement *p, *limit;
623 UHashTok emptytok;
624
625 if (U_FAILURE(*status)) return;
626
627 U_ASSERT(primeIndex >= 0 && primeIndex < PRIMES_LENGTH);
628
629 hash->primeIndex = primeIndex;
630 hash->length = PRIMES[primeIndex];
631
632 p = hash->elements = (UHashElement*)
633 uprv_malloc(sizeof(UHashElement) * hash->length);
634
635 if (hash->elements == NULL) {
636 *status = U_MEMORY_ALLOCATION_ERROR;
637 return;
638 }
639
640 emptytok.pointer = NULL; /* Only one of these two is needed */
641 emptytok.integer = 0; /* but we don't know which one. */
642
643 limit = p + hash->length;
644 while (p < limit) {
645 p->key = emptytok;
646 p->value = emptytok;
647 p->hashcode = HASH_EMPTY;
648 ++p;
649 }
650
651 hash->count = 0;
652 hash->lowWaterMark = (int32_t)(hash->length * hash->lowWaterRatio);
653 hash->highWaterMark = (int32_t)(hash->length * hash->highWaterRatio);
654 }
655
656 /**
657 * Attempt to grow or shrink the data arrays in order to make the
658 * count fit between the high and low water marks. hash_put() and
659 * hash_remove() call this method when the count exceeds the high or
660 * low water marks. This method may do nothing, if memory allocation
661 * fails, or if the count is already in range, or if the length is
662 * already at the low or high limit. In any case, upon return the
663 * arrays will be valid.
664 */
665 static void
666 _uhash_rehash(UHashtable *hash) {
667
668 UHashElement *old = hash->elements;
669 int32_t oldLength = hash->length;
670 int32_t newPrimeIndex = hash->primeIndex;
671 int32_t i;
672 UErrorCode status = U_ZERO_ERROR;
673
674 if (hash->count > hash->highWaterMark) {
675 if (++newPrimeIndex >= PRIMES_LENGTH) {
676 return;
677 }
678 } else if (hash->count < hash->lowWaterMark) {
679 if (--newPrimeIndex < 0) {
680 return;
681 }
682 } else {
683 return;
684 }
685
686 _uhash_allocate(hash, newPrimeIndex, &status);
687
688 if (U_FAILURE(status)) {
689 hash->elements = old;
690 hash->length = oldLength;
691 return;
692 }
693
694 for (i = oldLength - 1; i >= 0; --i) {
695 if (!IS_EMPTY_OR_DELETED(old[i].hashcode)) {
696 UHashElement *e = _uhash_find(hash, old[i].key, old[i].hashcode);
697 U_ASSERT(e != NULL);
698 U_ASSERT(e->hashcode == HASH_EMPTY);
699 e->key = old[i].key;
700 e->value = old[i].value;
701 e->hashcode = old[i].hashcode;
702 ++hash->count;
703 }
704 }
705
706 uprv_free(old);
707 }
708
709 /**
710 * Look for a key in the table, or if no such key exists, the first
711 * empty slot matching the given hashcode. Keys are compared using
712 * the keyComparator function.
713 *
714 * First find the start position, which is the hashcode modulo
715 * the length. Test it to see if it is:
716 *
717 * a. identical: First check the hash values for a quick check,
718 * then compare keys for equality using keyComparator.
719 * b. deleted
720 * c. empty
721 *
722 * Stop if it is identical or empty, otherwise continue by adding a
723 * "jump" value (moduloing by the length again to keep it within
724 * range) and retesting. For efficiency, there need enough empty
725 * values so that the searchs stop within a reasonable amount of time.
726 * This can be changed by changing the high/low water marks.
727 *
728 * In theory, this function can return NULL, if it is full (no empty
729 * or deleted slots) and if no matching key is found. In practice, we
730 * prevent this elsewhere (in uhash_put) by making sure the last slot
731 * in the table is never filled.
732 *
733 * The size of the table should be prime for this algorithm to work;
734 * otherwise we are not guaranteed that the jump value (the secondary
735 * hash) is relatively prime to the table length.
736 */
737 static UHashElement*
738 _uhash_find(const UHashtable *hash, UHashTok key,
739 int32_t hashcode) {
740
741 int32_t firstDeleted = -1; /* assume invalid index */
742 int32_t theIndex, startIndex;
743 int32_t jump = 0; /* lazy evaluate */
744 int32_t tableHash;
745
746 hashcode &= 0x7FFFFFFF; /* must be positive */
747 startIndex = theIndex = (hashcode ^ 0x4000000) % hash->length;
748
749 do {
750 tableHash = hash->elements[theIndex].hashcode;
751 if (tableHash == hashcode) { /* quick check */
752 if ((*hash->keyComparator)(key, hash->elements[theIndex].key)) {
753 return &(hash->elements[theIndex]);
754 }
755 } else if (!IS_EMPTY_OR_DELETED(tableHash)) {
756 /* We have hit a slot which contains a key-value pair,
757 * but for which the hash code does not match. Keep
758 * looking.
759 */
760 } else if (tableHash == HASH_EMPTY) { /* empty, end o' the line */
761 break;
762 } else if (firstDeleted < 0) { /* remember first deleted */
763 firstDeleted = theIndex;
764 }
765 if (jump == 0) { /* lazy compute jump */
766 /* The jump value must be relatively prime to the table
767 * length. As long as the length is prime, then any value
768 * 1..length-1 will be relatively prime to it.
769 */
770 jump = (hashcode % (hash->length - 1)) + 1;
771 }
772 theIndex = (theIndex + jump) % hash->length;
773 } while (theIndex != startIndex);
774
775 if (firstDeleted >= 0) {
776 theIndex = firstDeleted; /* reset if had deleted slot */
777 } else if (tableHash != HASH_EMPTY) {
778 /* We get to this point if the hashtable is full (no empty or
779 * deleted slots), and we've failed to find a match. THIS
780 * WILL NEVER HAPPEN as long as uhash_put() makes sure that
781 * count is always < length.
782 */
783 U_ASSERT(FALSE);
784 return NULL; /* Never happens if uhash_put() behaves */
785 }
786 return &(hash->elements[theIndex]);
787 }
788
789 static UHashTok
790 _uhash_put(UHashtable *hash,
791 UHashTok key,
792 UHashTok value,
793 int8_t hint,
794 UErrorCode *status) {
795
796 /* Put finds the position in the table for the new value. If the
797 * key is already in the table, it is deleted, if there is a
798 * non-NULL keyDeleter. Then the key, the hash and the value are
799 * all put at the position in their respective arrays.
800 */
801 int32_t hashcode;
802 UHashElement* e;
803 UHashTok emptytok;
804
805 if (U_FAILURE(*status)) {
806 goto err;
807 }
808 U_ASSERT(hash != NULL);
809 /* Cannot always check pointer here or iSeries sees NULL every time. */
810 if ((hint & HINT_VALUE_POINTER) && value.pointer == NULL) {
811 /* Disallow storage of NULL values, since NULL is returned by
812 * get() to indicate an absent key. Storing NULL == removing.
813 */
814 return _uhash_remove(hash, key);
815 }
816 if (hash->count > hash->highWaterMark) {
817 _uhash_rehash(hash);
818 }
819
820 hashcode = (*hash->keyHasher)(key);
821 e = _uhash_find(hash, key, hashcode);
822 U_ASSERT(e != NULL);
823
824 if (IS_EMPTY_OR_DELETED(e->hashcode)) {
825 /* Important: We must never actually fill the table up. If we
826 * do so, then _uhash_find() will return NULL, and we'll have
827 * to check for NULL after every call to _uhash_find(). To
828 * avoid this we make sure there is always at least one empty
829 * or deleted slot in the table. This only is a problem if we
830 * are out of memory and rehash isn't working.
831 */
832 ++hash->count;
833 if (hash->count == hash->length) {
834 /* Don't allow count to reach length */
835 --hash->count;
836 *status = U_MEMORY_ALLOCATION_ERROR;
837 goto err;
838 }
839 }
840
841 /* We must in all cases handle storage properly. If there was an
842 * old key, then it must be deleted (if the deleter != NULL).
843 * Make hashcodes stored in table positive.
844 */
845 return _uhash_setElement(hash, e, hashcode & 0x7FFFFFFF, key, value, hint);
846
847 err:
848 /* If the deleters are non-NULL, this method adopts its key and/or
849 * value arguments, and we must be sure to delete the key and/or
850 * value in all cases, even upon failure.
851 */
852 HASH_DELETE_KEY_VALUE(hash, key.pointer, value.pointer);
853 emptytok.pointer = NULL; emptytok.integer = 0;
854 return emptytok;
855 }
856
857 static UHashTok
858 _uhash_remove(UHashtable *hash,
859 UHashTok key) {
860 /* First find the position of the key in the table. If the object
861 * has not been removed already, remove it. If the user wanted
862 * keys deleted, then delete it also. We have to put a special
863 * hashcode in that position that means that something has been
864 * deleted, since when we do a find, we have to continue PAST any
865 * deleted values.
866 */
867 UHashTok result;
868 UHashElement* e = _uhash_find(hash, key, hash->keyHasher(key));
869 U_ASSERT(e != NULL);
870 result.pointer = NULL; result.integer = 0;
871 if (!IS_EMPTY_OR_DELETED(e->hashcode)) {
872 result = _uhash_internalRemoveElement(hash, e);
873 if (hash->count < hash->lowWaterMark) {
874 _uhash_rehash(hash);
875 }
876 }
877 return result;
878 }
879
880 static UHashTok
881 _uhash_setElement(UHashtable *hash, UHashElement* e,
882 int32_t hashcode,
883 UHashTok key, UHashTok value, int8_t hint) {
884
885 UHashTok oldValue = e->value;
886 if (hash->keyDeleter != NULL && e->key.pointer != NULL &&
887 e->key.pointer != key.pointer) { /* Avoid double deletion */
888 (*hash->keyDeleter)(e->key.pointer);
889 }
890 if (hash->valueDeleter != NULL) {
891 if (oldValue.pointer != NULL &&
892 oldValue.pointer != value.pointer) { /* Avoid double deletion */
893 (*hash->valueDeleter)(oldValue.pointer);
894 }
895 oldValue.pointer = NULL;
896 }
897 /* Compilers should copy the UHashTok union correctly, but even if
898 * they do, memory heap tools (e.g. BoundsChecker) can get
899 * confused when a pointer is cloaked in a union and then copied.
900 * TO ALLEVIATE THIS, we use hints (based on what API the user is
901 * calling) to copy pointers when we know the user thinks
902 * something is a pointer. */
903 if (hint & HINT_KEY_POINTER) {
904 e->key.pointer = key.pointer;
905 } else {
906 e->key = key;
907 }
908 if (hint & HINT_VALUE_POINTER) {
909 e->value.pointer = value.pointer;
910 } else {
911 e->value = value;
912 }
913 e->hashcode = hashcode;
914 return oldValue;
915 }
916
917 /**
918 * Assumes that the given element is not empty or deleted.
919 */
920 static UHashTok
921 _uhash_internalRemoveElement(UHashtable *hash, UHashElement* e) {
922 UHashTok empty;
923 U_ASSERT(!IS_EMPTY_OR_DELETED(e->hashcode));
924 --hash->count;
925 empty.pointer = NULL; empty.integer = 0;
926 return _uhash_setElement(hash, e, HASH_DELETED, empty, empty, 0);
927 }
928
929 static void
930 _uhash_internalSetResizePolicy(UHashtable *hash, enum UHashResizePolicy policy) {
931 U_ASSERT(hash != NULL);
932 U_ASSERT(((int32_t)policy) >= 0);
933 U_ASSERT(((int32_t)policy) < 3);
934 hash->lowWaterRatio = RESIZE_POLICY_RATIO_TABLE[policy * 2];
935 hash->highWaterRatio = RESIZE_POLICY_RATIO_TABLE[policy * 2 + 1];
936 }