source: tags/ms_r17q2/ARBDB/adhash.cxx

Last change on this file was 15176, checked in by westram, 8 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.6 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : adhash.cxx                                        //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "gb_data.h"
12#include "gb_tune.h"
13#include "gb_hashindex.h"
14
15#include <arb_strbuf.h>
16#include <arb_sort.h>
17
18#include <climits>
19#include <cfloat>
20#include <cctype>
21
22
23struct gbs_hash_entry {
24    char           *key;
25    long            val;
26    gbs_hash_entry *next;
27};
28struct GB_HASH {
29    size_t           size;                          // size of hashtable
30    size_t           nelem;                         // number of elements inserted
31    GB_CASE          case_sens;
32    gbs_hash_entry **entries;                       // the hash table (has 'size' entries)
33
34    void (*freefun)(long val); // function to free hash values (see GBS_create_dynaval_hash)
35
36};
37
38struct numhash_entry {
39    long           key;
40    long           val;
41    numhash_entry *next;
42};
43
44struct GB_NUMHASH {
45    long            size;                           // size of hashtable
46    size_t          nelem;                          // number of elements inserted
47    numhash_entry **entries;
48};
49
50// prime numbers
51
52#define KNOWN_PRIMES 279
53static size_t sorted_primes[KNOWN_PRIMES] = {
54    3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 47, 53, 59, 67, 71, 79, 89, 97, 103, 109, 127, 137, 149, 157, 167, 179, 191, 211, 
55    223, 239, 257, 271, 293, 311, 331, 349, 373, 397, 419, 443, 467, 499, 541, 571, 607, 641, 677, 719, 757, 797, 839, 887, 937, 
56    991, 1049, 1109, 1171, 1237, 1303, 1373, 1447, 1531, 1613, 1699, 1789, 1889, 1993, 2099, 2213, 2333, 2459, 2591, 2729, 2879, 
57    3037, 3203, 3373, 3557, 3761, 3967, 4177, 4397, 4637, 4889, 5147, 5419, 5711, 6029, 6353, 6689, 7043, 7417, 7817, 8231, 8669, 
58    9127, 9613, 10133, 10667, 11239, 11831, 12457, 13121, 13829, 14557, 15329, 16139, 16993, 17891, 18839, 19841, 20887, 21991, 23159, 
59    24379, 25667, 27031, 28463, 29983, 31567, 33247, 35023, 36871, 38821, 40867, 43019, 45289, 47681, 50207, 52859, 55661, 58601, 
60    61687, 64937, 68371, 71971, 75767, 79757, 83969, 88397, 93053, 97961, 103123, 108553, 114269, 120293, 126631, 133303, 140321, 
61    147709, 155501, 163697, 172313, 181387, 190979, 201031, 211619, 222773, 234499, 246889, 259907, 273601, 288007, 303187, 319147, 
62    335953, 353641, 372263, 391861, 412487, 434201, 457057, 481123, 506449, 533111, 561173, 590713, 621821, 654553, 689021, 725293, 
63    763471, 803659, 845969, 890501, 937373, 986717, 1038671, 1093357, 1150909, 1211489, 1275269, 1342403, 1413077, 1487459, 1565747, 
64    1648181, 1734937, 1826257, 1922383, 2023577, 2130101, 2242213, 2360243, 2484473, 2615243, 2752889, 2897789, 3050321, 3210871, 
65    3379877, 3557773, 3745051, 3942209, 4149703, 4368113, 4598063, 4840103, 5094853, 5363011, 5645279, 5942399, 6255157, 6584377, 
66    6930929, 7295719, 7679713, 8083919, 8509433, 8957309, 9428759, 9925021, 10447391, 10997279, 11576087, 12185359, 12826699, 13501819, 
67    14212447, 14960471, 15747869, 16576727, 17449207, 18367597, 19334317, 20351927, 21423107, 22550639, 23737523, 24986867, 26301967, 
68    27686291, 29143493, 30677363, 32291971, 33991597, 35780639, 37663841, 39646153, 41732809, 43929307, 46241389, 48675167, 51237019, 
69    53933713, 56772371, 59760391, 62905681, 66216511, 69701591, 73370107, 77231711, 81296543, 85575313, 90079313, 94820347, 99810899 
70};
71
72// define CALC_PRIMES only to expand the above table
73#if defined(DEBUG)
74// #define CALC_PRIMES
75#endif // DEBUG
76
77#ifdef CALC_PRIMES
78
79#define CALC_PRIMES_UP_TO 100000000U
80#define PRIME_UNDENSITY   20U   // the higher, the less primes are stored
81
82#warning "please don't define CALC_PRIMES permanently"
83
84static unsigned char bit_val[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
85
86static int bit_value(const unsigned char *eratosthenes, long num) {
87    // 'num' is odd and lowest 'num' is 3
88    long bit_num  = ((num-1) >> 1)-1; // 3->0 5->1 7->2 etc.
89    long byte_num = bit_num >> 3; // div 8
90    char byte     = eratosthenes[byte_num];
91
92    gb_assert(bit_num >= 0);
93    gb_assert((num&1) == 1);    // has to odd
94
95    bit_num = bit_num &  7;
96
97    return (byte & bit_val[bit_num]) ? 1 : 0;
98}
99static void set_bit_value(unsigned char *eratosthenes, long num, int val) {
100    // 'num' is odd and lowest 'num' is 3; val is 0 or 1
101    long bit_num  = ((num-1) >> 1)-1; // 3->0 5->1 7->2 etc.
102    long byte_num = bit_num >> 3; // div 8
103    char byte     = eratosthenes[byte_num];
104
105    gb_assert(bit_num >= 0);
106    gb_assert((num&1) == 1);    // has to odd
107
108    bit_num = bit_num &  7;
109
110    if (val) {
111        byte |= bit_val[bit_num];
112    }
113    else {
114        byte &= (0xff - bit_val[bit_num]);
115    }
116    eratosthenes[byte_num] = byte;
117}
118
119static void calculate_primes_upto() {
120    {
121        size_t         bits_needed  = CALC_PRIMES_UP_TO/2+1; // only need bits for odd numbers
122        size_t         bytes_needed = (bits_needed/8)+1;
123        unsigned char *eratosthenes = ARB_calloc<unsigned char>(bytes_needed); // bit = 1 means "is not a prime"
124        size_t         prime_count  = 0;
125        size_t         num;
126
127        printf("eratosthenes' size = %zu\n", bytes_needed);
128        GBK_dump_backtrace(stderr, "calculate_primes_upto");
129
130        for (num = 3; num <= CALC_PRIMES_UP_TO; num += 2) {
131            if (bit_value(eratosthenes, num) == 0) { // is a prime number
132                size_t num2;
133                prime_count++;
134                for (num2 = num*2; num2 <= CALC_PRIMES_UP_TO; num2 += num) { // with all multiples
135                    if ((num2&1) == 1) { // skip even numbers
136                        set_bit_value(eratosthenes, num2, 1);
137                    }
138                }
139            }
140            // otherwise it is no prime and all multiples are already set to 1
141        }
142
143        // thin out prime numbers (we don't need all of them)
144        {
145            size_t prime_count2 = 0;
146            size_t last_prime   = 1;
147            size_t printed      = 0;
148
149            for (num = 3; num <= CALC_PRIMES_UP_TO; num += 2) {
150                if (bit_value(eratosthenes, num) == 0) { // is a prime number
151                    size_t diff = num-last_prime;
152                    if ((diff*PRIME_UNDENSITY)<num) {
153                        set_bit_value(eratosthenes, num, 1); // delete unneeded prime
154                    }
155                    else {
156                        prime_count2++; // count needed primes
157                        last_prime = num;
158                    }
159                }
160            }
161
162            printf("\nUsing %zu prime numbers up to %zu:\n\n", prime_count2, CALC_PRIMES_UP_TO);
163            printf("#define KNOWN_PRIMES %zu\n", prime_count2);
164            printf("static size_t sorted_primes[KNOWN_PRIMES] = {\n    ");
165            printed = 4;
166
167            for (num = 3; num <= CALC_PRIMES_UP_TO; num += 2) {
168                if (bit_value(eratosthenes, num) == 0) { // is a prime number
169                    if (printed>128) {
170                        printf("\n    ");
171                        printed = 4;
172                    }
173
174                    if (num>INT_MAX) {
175                        printed += printf("%zuU, ", num);
176                    }
177                    else {
178                        printed += printf("%zu, ", num);
179                    }
180                }
181            }
182            printf("\n};\n\n");
183        }
184
185        free(eratosthenes);
186    }
187    fflush(stdout);
188    exit(1);
189}
190
191#endif // CALC_PRIMES
192
193size_t gbs_get_a_prime(size_t above_or_equal_this) {
194    // return a prime number above_or_equal_this
195    // NOTE: it is not necessarily the next prime number, because we don't calculate all prime numbers!
196
197#if defined(CALC_PRIMES)
198    calculate_primes_upto();
199#endif // CALC_PRIMES
200
201    if (sorted_primes[KNOWN_PRIMES-1] >= above_or_equal_this) {
202        int l = 0, h = KNOWN_PRIMES-1;
203
204        while (l < h) {
205            int m = (l+h)/2;
206#if defined(DEBUG) && 0
207            printf("l=%-3i m=%-3i h=%-3i above_or_equal_this=%li sorted_primes[%i]=%li sorted_primes[%i]=%li sorted_primes[%i]=%li\n",
208                   l, m, h, above_or_equal_this, l, sorted_primes[l], m, sorted_primes[m], h, sorted_primes[h]);
209#endif // DEBUG
210            gb_assert(l <= m);
211            gb_assert(m <= h);
212            if (sorted_primes[m] > above_or_equal_this) {
213                h = m-1;
214            }
215            else {
216                if (sorted_primes[m] < above_or_equal_this) {
217                    l = m+1;
218                }
219                else {
220                    h = l = m;
221                }
222            }
223        }
224
225        if (sorted_primes[l] < above_or_equal_this) {
226            l++;                // take next
227            gb_assert(l<KNOWN_PRIMES);
228        }
229
230        gb_assert(sorted_primes[l] >= above_or_equal_this);
231        gb_assert(l == 0 || sorted_primes[l-1] < above_or_equal_this);
232
233        return sorted_primes[l];
234    }
235
236    fprintf(stderr, "Warning: gbs_get_a_prime failed for value %zu (performance bleed)\n", above_or_equal_this);
237    gb_assert(0); // add more primes to sorted_primes[]
238
239    return above_or_equal_this; // NEED_NO_COV
240}
241
242// -----------------------------------------------
243//      Some Hash Procedures for [string,long]
244
245inline size_t hash_size(size_t estimated_elements) {
246    size_t min_hash_size = 2*estimated_elements;    // -> fill rate ~ 50% -> collisions unlikely
247    size_t next_prime    = gbs_get_a_prime(min_hash_size); // use next prime number
248
249    return next_prime;
250}
251
252
253GB_HASH *GBS_create_hash(long estimated_elements, GB_CASE case_sens) {
254    /*! Create a hash
255     * @param estimated_elements estimated number of elements added to hash (if you add more elements, hash will still work, but get slow)
256     * @param case_sens GB_IGNORE_CASE or GB_MIND_CASE
257     * Uses linked lists to avoid collisions.
258     */
259    long     size = hash_size(estimated_elements);
260    GB_HASH *hs   = ARB_calloc<GB_HASH>(1);
261
262    hs->size      = size;
263    hs->nelem     = 0;
264    hs->case_sens = case_sens;
265    ARB_calloc(hs->entries, size);
266    hs->freefun   = NULL;
267
268    return hs;
269}
270
271GB_HASH *GBS_create_dynaval_hash(long estimated_elements, GB_CASE case_sens, void (*freefun)(long)) {
272    //! like GBS_create_hash, but values stored in hash get freed using 'freefun' when hash gets destroyed
273    GB_HASH *hs = GBS_create_hash(estimated_elements, case_sens);
274    hs->freefun = freefun;
275    return hs;
276}
277
278void GBS_dynaval_free(long val) {
279    free((void*)val);
280}
281
282#if defined(DEBUG)
283inline void dump_access(const char *title, const GB_HASH *hs, double mean_access) {
284    fprintf(stderr,
285            "%s: size=%zu elements=%zu mean_access=%.2f hash-speed=%.1f%%\n",
286            title, hs->size, hs->nelem, mean_access, 100.0/mean_access);
287}
288
289static double hash_mean_access_costs(const GB_HASH *hs) {
290    /* returns the mean access costs of the hash [1.0 .. inf[
291     * 1.0 is optimal
292     * 2.0 means: hash speed is 50% (1/2.0)
293    */
294    double mean_access = 1.0;
295
296    if (hs->nelem) {
297        int    strcmps_needed = 0;
298        size_t pos;
299
300        for (pos = 0; pos<hs->size; pos++) {
301            int             strcmps = 1;
302            gbs_hash_entry *e;
303
304            for (e = hs->entries[pos]; e; e = e->next) {
305                strcmps_needed += strcmps++;
306            }
307        }
308
309        mean_access = (double)strcmps_needed/hs->nelem;
310    }
311    return mean_access;
312}
313#endif // DEBUG
314
315
316void GBS_optimize_hash(const GB_HASH *hs) {
317    if (hs->nelem > hs->size) {                     // hash is overfilled (Note: even 50% fillrate is slow)
318        size_t new_size = gbs_get_a_prime(hs->nelem*3);
319
320#if defined(DEBUG)
321        dump_access("Optimizing filled hash", hs, hash_mean_access_costs(hs));
322#endif // DEBUG
323
324        if (new_size>hs->size) { // avoid overflow
325            gbs_hash_entry **new_entries; ARB_calloc(new_entries, new_size);
326
327            for (size_t pos = 0; pos<hs->size; ++pos) {
328                gbs_hash_entry *e;
329                gbs_hash_entry *next;
330
331                for (e = hs->entries[pos]; e; e = next) {
332                    long new_idx;
333                    next = e->next;
334
335                    GB_CALC_HASH_INDEX(e->key, new_idx, new_size, hs->case_sens);
336
337                    e->next              = new_entries[new_idx];
338                    new_entries[new_idx] = e;
339                }
340            }
341
342            free(hs->entries);
343
344            {
345                GB_HASH *hs_mutable = const_cast<GB_HASH*>(hs);
346                hs_mutable->size    = new_size;
347                hs_mutable->entries = new_entries;
348            }
349        }
350#if defined(DEBUG)
351        dump_access("Optimized hash        ", hs, hash_mean_access_costs(hs));
352#endif // DEBUG
353
354    }
355}
356
357static void gbs_hash_to_strstruct(const char *key, long val, void *cd_out) {
358    const char    *p;
359    int            c;
360    GBS_strstruct *out = (GBS_strstruct*)cd_out;
361
362    for (p = key; (c=*p);  p++) {
363        GBS_chrcat(out, c);
364        if (c==':') GBS_chrcat(out, c);
365    }
366    GBS_chrcat(out, ':');
367    GBS_intcat(out, val);
368    GBS_chrcat(out, ' ');
369}
370
371char *GBS_hashtab_2_string(const GB_HASH *hash) {
372    GBS_strstruct *out = GBS_stropen(1024);
373    GBS_hash_do_const_loop(hash, gbs_hash_to_strstruct, out);
374    return GBS_strclose(out);
375}
376
377
378static gbs_hash_entry *find_hash_entry(const GB_HASH *hs, const char *key, size_t *index) {
379    gbs_hash_entry *e;
380    if (hs->case_sens == GB_IGNORE_CASE) {
381        GB_CALC_HASH_INDEX_CASE_IGNORED(key, *index, hs->size);
382        for (e=hs->entries[*index]; e; e=e->next) {
383            if (!strcasecmp(e->key, key)) return e;
384        }
385    }
386    else {
387        GB_CALC_HASH_INDEX_CASE_SENSITIVE(key, *index, hs->size);
388        for (e=hs->entries[*index]; e; e=e->next) {
389            if (!strcmp(e->key, key)) return e;
390        }
391    }
392    return 0;
393}
394
395long GBS_read_hash(const GB_HASH *hs, const char *key) {
396    size_t          i;
397    gbs_hash_entry *e = find_hash_entry(hs, key, &i);
398
399    return e ? e->val : 0;
400}
401
402static void delete_from_list(GB_HASH *hs, size_t i, gbs_hash_entry *e) {
403    // delete the hash entry 'e' from list at index 'i'
404    hs->nelem--;
405    if (hs->entries[i] == e) {
406        hs->entries[i] = e->next;
407    }
408    else {
409        gbs_hash_entry *ee;
410        for (ee = hs->entries[i]; ee->next != e; ee = ee->next) ;
411        if (ee->next == e) {
412            ee->next = e->next;
413        }
414        else {
415            GB_internal_error("Database may be corrupt, hash tables error"); // NEED_NO_COV
416        }
417    }
418    free(e->key);
419    if (hs->freefun) hs->freefun(e->val);
420    gbm_free_mem(e, sizeof(gbs_hash_entry), GBM_HASH_INDEX);
421}
422
423static long write_hash(GB_HASH *hs, char *key, bool copyKey, long val) {
424    /* returns the old value (or 0 if key had no entry)
425     * if 'copyKey' == false, 'key' will be freed (now or later) and may be invalid!
426     * if 'copyKey' == true, 'key' will not be touched in any way!
427     */
428
429    size_t          i;
430    gbs_hash_entry *e      = find_hash_entry(hs, key, &i);
431    long            oldval = 0;
432
433    if (e) {
434        oldval = e->val;
435
436        if (!val) delete_from_list(hs, i, e); // (val == 0 is not stored, cause 0 is the default value)
437        else      e->val = val;
438
439        if (!copyKey) free(key); // already had an entry -> delete unused mem
440    }
441    else if (val != 0) {        // don't store 0
442        // create new hash entry
443        e       = (gbs_hash_entry *)gbm_get_mem(sizeof(gbs_hash_entry), GBM_HASH_INDEX);
444        e->next = hs->entries[i];
445        e->key  = copyKey ? ARB_strdup(key) : key;
446        e->val  = val;
447
448        hs->entries[i] = e;
449        hs->nelem++;
450    }
451    else {
452        if (!copyKey) free(key); // don't need an entry -> delete unused mem
453    }
454    return oldval;
455}
456
457long GBS_write_hash(GB_HASH *hs, const char *key, long val) {
458    // returns the old value (or 0 if key had no entry)
459    return write_hash(hs, (char*)key, true, val);
460}
461
462long GBS_write_hash_no_strdup(GB_HASH *hs, char *key, long val) {
463    /* same as GBS_write_hash, but does no strdup. 'key' is freed later in GBS_free_hash,
464     * so the user has to 'malloc' the string and give control to the hash.
465     * Note: after calling this function 'key' may be invalid!
466     */
467    return write_hash(hs, key, false, val);
468}
469
470long GBS_incr_hash(GB_HASH *hs, const char *key) {
471    // returns new value
472    size_t          i;
473    gbs_hash_entry *e = find_hash_entry(hs, key, &i);
474    long            result;
475
476    if (e) {
477        result = ++e->val;
478        if (!result) delete_from_list(hs, i, e);
479    }
480    else {
481        e       = (gbs_hash_entry *)gbm_get_mem(sizeof(gbs_hash_entry), GBM_HASH_INDEX);
482        e->next = hs->entries[i];
483        e->key  = ARB_strdup(key);
484        e->val  = result = 1;
485
486        hs->entries[i] = e;
487        hs->nelem++;
488    }
489    return result;
490}
491
492#if defined(DEVEL_RALF)
493// #define DUMP_HASH_ENTRIES
494#endif // DEVEL_RALF
495
496static void GBS_erase_hash(GB_HASH *hs) {
497    size_t hsize = hs->size;
498
499#if defined(DUMP_HASH_ENTRIES)
500    for (size_t i = 0; i < hsize; i++) {
501        printf("hash[%zu] =", i);
502        for (gbs_hash_entry *e = hs->entries[i]; e; e = e->next) {
503            printf(" '%s'", e->key);
504        }
505        printf("\n");
506    }
507#endif // DUMP_HASH_ENTRIES
508
509    // check hash size
510    if (hsize >= 10) { // ignore small hashes
511#if defined(DEBUG)
512        double mean_access = hash_mean_access_costs(hs);
513        if (mean_access > 1.5) { // every 2nd access is a collision - increase hash size?
514            dump_access("hash-size-warning", hs, mean_access);
515#if defined(DEVEL_RALF) && !defined(UNIT_TESTS)
516            gb_assert(mean_access<2.0);             // hash with 50% speed or less
517#endif // DEVEL_RALF
518        }
519#else
520        if (hs->nelem >= (2*hsize)) {
521            GB_warningf("Performance leak - very slow hash detected (elems=%zu, size=%zu)\n", hs->nelem, hs->size);
522            GBK_dump_backtrace(stderr, "detected performance leak");
523        }
524#endif // DEBUG
525    }
526
527    for (size_t i = 0; i < hsize; i++) {
528        for (gbs_hash_entry *e = hs->entries[i]; e; ) {
529            free(e->key);
530            if (hs->freefun) hs->freefun(e->val);
531
532            gbs_hash_entry *next = e->next;
533            gbm_free_mem(e, sizeof(gbs_hash_entry), GBM_HASH_INDEX);
534            e = next;
535        }
536        hs->entries[i] = 0;
537    }
538    hs->nelem = 0;
539}
540
541void GBS_free_hash(GB_HASH *hs) {
542    gb_assert(hs);
543    GBS_erase_hash(hs);
544    free(hs->entries);
545    free(hs);
546}
547
548void GBS_hash_do_loop(GB_HASH *hs, gb_hash_loop_type func, void *client_data) {
549    size_t hsize = hs->size;
550    for (size_t i=0; i<hsize; i++) {
551        for (gbs_hash_entry *e = hs->entries[i]; e; ) {
552            gbs_hash_entry *next = e->next;
553            if (e->val) {
554                e->val = func(e->key, e->val, client_data);
555                if (!e->val) delete_from_list(hs, i, e);
556            }
557            e = next;
558        }
559    }
560}
561
562void GBS_hash_do_const_loop(const GB_HASH *hs, gb_hash_const_loop_type func, void *client_data) {
563    size_t hsize = hs->size;
564    for (size_t i=0; i<hsize; i++) {
565        for (gbs_hash_entry *e = hs->entries[i]; e; ) {
566            gbs_hash_entry *next = e->next;
567            if (e->val) func(e->key, e->val, client_data);
568            e = next;
569        }
570    }
571}
572
573size_t GBS_hash_elements(const GB_HASH *hs) {
574    return hs->nelem;
575}
576
577const char *GBS_hash_next_element_that(const GB_HASH *hs, const char *last_key, bool (*condition)(const char *key, long val, void *cd), void *cd) {
578    /* Returns the key of the next element after 'last_key' matching 'condition' (i.e. where condition returns true).
579     * If 'last_key' is NULL, the first matching element is returned.
580     * Returns NULL if no (more) elements match the 'condition'.
581     */
582
583    size_t          size = hs->size;
584    size_t          i    = 0;
585    gbs_hash_entry *e    = 0;
586
587    if (last_key) {
588        e = find_hash_entry(hs, last_key, &i);
589        if (!e) return NULL;
590
591        e = e->next;       // use next entry after 'last_key'
592        if (!e) i++;
593    }
594
595    for (; i<size && !e; ++i) e = hs->entries[i]; // search first/next entry
596
597    while (e) {
598        if ((*condition)(e->key, e->val, cd)) break;
599        e = e->next;
600        if (!e) {
601            for (i++; i<size && !e; ++i) e = hs->entries[i];
602        }
603    }
604
605    return e ? e->key : NULL;
606}
607
608static int wrap_hashCompare4gb_sort(const void *v0, const void *v1, void *sorter) {
609    const gbs_hash_entry *e0 = (const gbs_hash_entry*)v0;
610    const gbs_hash_entry *e1 = (const gbs_hash_entry*)v1;
611
612    return ((gbs_hash_compare_function)sorter)(e0->key, e0->val, e1->key, e1->val);
613}
614
615void GBS_hash_do_sorted_loop(GB_HASH *hs, gb_hash_loop_type func, gbs_hash_compare_function sorter, void *client_data) {
616    size_t           hsize = hs->size;
617    gbs_hash_entry **mtab; ARB_calloc(mtab, hs->nelem);
618
619    size_t j = 0;
620    for (size_t i = 0; i < hsize; i++) {
621        for (gbs_hash_entry *e = hs->entries[i]; e; e = e->next) {
622            if (e->val) {
623                mtab[j++] = e;
624            }
625        }
626    }
627
628    GB_sort((void**)mtab, 0, j, wrap_hashCompare4gb_sort, (void*)sorter);
629   
630    for (size_t i = 0; i < j; i++) {
631        long new_val = func(mtab[i]->key, mtab[i]->val, client_data);
632        if (new_val != mtab[i]->val) GBS_write_hash(hs, mtab[i]->key, new_val);
633    }
634   
635    free(mtab);
636}
637
638int GBS_HCF_sortedByKey(const char *k0, long /*v0*/, const char *k1, long /*v1*/) {
639    return strcmp(k0, k1);
640}
641
642// ---------------------------------------------
643//      Some Hash Procedures for [long,long]
644
645inline long gbs_numhash_index(long key, long size) {
646    long x;
647    x = (key * (long long)97)%size;     // make one multiplier a (long long) to avoid
648    if (x<0) x += size;                 // int overflow and abort if compiled with -ftrapv
649    return x;
650}
651
652
653GB_NUMHASH *GBS_create_numhash(size_t estimated_elements) {
654    size_t      size = hash_size(estimated_elements);
655    GB_NUMHASH *hs   = ARB_calloc<GB_NUMHASH>(1);
656
657    hs->size  = size;
658    hs->nelem = 0;
659    ARB_calloc(hs->entries, size);
660
661    return hs;
662}
663
664long GBS_read_numhash(GB_NUMHASH *hs, long key) {
665    size_t i = gbs_numhash_index(key, hs->size);
666    for (numhash_entry *e = hs->entries[i]; e; e = e->next) {
667        if (e->key==key) return e->val;
668    }
669    return 0;
670}
671
672long GBS_write_numhash(GB_NUMHASH *hs, long key, long val) {
673    size_t i      = gbs_numhash_index(key, hs->size);
674    long   oldval = 0;
675
676    if (val == 0) { // erase
677        numhash_entry **nextPtr = &(hs->entries[i]);
678
679        for (numhash_entry *e = hs->entries[i]; e; e = e->next) {
680            if (e->key == key) {
681                *nextPtr = e->next;                  // unlink entry
682                gbm_free_mem(e, sizeof(*e), GBM_HASH_INDEX);
683                hs->nelem--;
684                return 0;
685            }
686            nextPtr = &(e->next);
687        }
688    }
689    else {
690        for (numhash_entry *e=hs->entries[i]; e; e=e->next) {
691            if (e->key==key) {
692                oldval = e->val; gb_assert(oldval);
693                e->val = val;
694                break;
695            }
696        }
697
698        if (!oldval) {
699            numhash_entry *e = (numhash_entry *)gbm_get_mem(sizeof(*e), GBM_HASH_INDEX);
700
701            e->next = hs->entries[i];
702            e->key  = key;
703            e->val  = val;
704
705            hs->nelem++;
706            hs->entries[i] = e;
707        }
708    }
709    return oldval;
710}
711
712static void GBS_erase_numhash(GB_NUMHASH *hs) {
713    size_t hsize = hs->size;
714
715    for (size_t i=0; i<hsize; i++) {
716        for (numhash_entry *e = hs->entries[i]; e; ) {
717            numhash_entry *next = e->next;
718           
719            gbm_free_mem(e, sizeof(*e), GBM_HASH_INDEX);
720            e = next;
721        }
722    }
723
724    hs->nelem = 0;
725}
726
727void GBS_free_numhash(GB_NUMHASH *hs) {
728    GBS_erase_numhash(hs);
729    free(hs->entries);
730    free(hs);
731}
732
733// --------------------------------------------------------------------------------
734
735#ifdef UNIT_TESTS
736
737#include <test_unit.h>
738
739// determine hash quality
740
741struct gbs_hash_statistic_summary {
742    long   count;               // how many stats
743    long   min_size, max_size, sum_size;
744    long   min_nelem, max_nelem, sum_nelem;
745    long   min_collisions, max_collisions, sum_collisions;
746    double min_fill_ratio, max_fill_ratio, sum_fill_ratio;
747    double min_hash_quality, max_hash_quality, sum_hash_quality;
748
749    void init() {
750        count          = 0;
751        min_size       = min_nelem = min_collisions = LONG_MAX;
752        max_size       = max_nelem = max_collisions = LONG_MIN;
753        min_fill_ratio = min_hash_quality = DBL_MAX;
754        max_fill_ratio = max_hash_quality = DBL_MIN;
755
756        sum_size       = sum_nelem = sum_collisions = 0;
757        sum_fill_ratio = sum_hash_quality = 0.0;
758    }
759};
760
761class hash_statistic_manager : virtual Noncopyable {
762    GB_HASH *stat_hash;
763public:
764    hash_statistic_manager() : stat_hash(NULL) { }
765    ~hash_statistic_manager() {
766        if (stat_hash) GBS_free_hash(stat_hash);
767    }
768
769    gbs_hash_statistic_summary *get_stat_summary(const char *id) {
770        if (!stat_hash) stat_hash = GBS_create_dynaval_hash(10, GB_MIND_CASE, GBS_dynaval_free);
771
772        long found = GBS_read_hash(stat_hash, id);
773        if (!found) {
774            gbs_hash_statistic_summary *stat; ARB_calloc(stat, 1);
775            stat->init();
776            found = (long)stat;
777            GBS_write_hash(stat_hash, id, found);
778        }
779
780        return (gbs_hash_statistic_summary*)found;
781    }
782};
783
784static void addto_hash_statistic_summary(gbs_hash_statistic_summary *stat, long size, long nelem, long collisions, double fill_ratio, double hash_quality) {
785    stat->count++;
786
787    if (stat->min_size > size) stat->min_size = size;
788    if (stat->max_size < size) stat->max_size = size;
789
790    if (stat->min_nelem > nelem) stat->min_nelem = nelem;
791    if (stat->max_nelem < nelem) stat->max_nelem = nelem;
792
793    if (stat->min_collisions > collisions) stat->min_collisions = collisions;
794    if (stat->max_collisions < collisions) stat->max_collisions = collisions;
795
796    if (stat->min_fill_ratio > fill_ratio) stat->min_fill_ratio = fill_ratio;
797    if (stat->max_fill_ratio < fill_ratio) stat->max_fill_ratio = fill_ratio;
798
799    if (stat->min_hash_quality > hash_quality) stat->min_hash_quality = hash_quality;
800    if (stat->max_hash_quality < hash_quality) stat->max_hash_quality = hash_quality;
801
802    stat->sum_size         += size;
803    stat->sum_nelem        += nelem;
804    stat->sum_collisions   += collisions;
805    stat->sum_fill_ratio   += fill_ratio;
806    stat->sum_hash_quality += hash_quality;
807}
808
809static hash_statistic_manager hash_stat_man;
810
811static void test_clear_hash_statistic_summary(const char *id) {
812    hash_stat_man.get_stat_summary(id)->init();
813}
814
815static void test_print_hash_statistic_summary(const char *id) {
816    gbs_hash_statistic_summary *stat  = hash_stat_man.get_stat_summary(id);
817    long                        count = stat->count;
818    printf("Statistic summary for %li hashes of type '%s':\n", count, id);
819    printf("- size:          min = %6li ; max = %6li ; mean = %6.1f\n", stat->min_size, stat->max_size, (double)stat->sum_size/count);
820    printf("- nelem:         min = %6li ; max = %6li ; mean = %6.1f\n", stat->min_nelem, stat->max_nelem, (double)stat->sum_nelem/count);
821    printf("- fill_ratio:    min = %5.1f%% ; max = %5.1f%% ; mean = %5.1f%%\n", stat->min_fill_ratio*100.0, stat->max_fill_ratio*100.0, (double)stat->sum_fill_ratio/count*100.0);
822    printf("- collisions:    min = %6li ; max = %6li ; mean = %6.1f\n", stat->min_collisions, stat->max_collisions, (double)stat->sum_collisions/count);
823    printf("- hash_quality:  min = %5.1f%% ; max = %5.1f%% ; mean = %5.1f%%\n", stat->min_hash_quality*100.0, stat->max_hash_quality*100.0, (double)stat->sum_hash_quality/count*100.0);
824}
825
826static void test_calc_hash_statistic(const GB_HASH *hs, const char *id, int print) {
827    long   queues     = 0;
828    long   collisions;
829    double fill_ratio = (double)hs->nelem/hs->size;
830    double hash_quality;
831
832    for (size_t i = 0; i < hs->size; i++) {
833        if (hs->entries[i]) queues++;
834    }
835    collisions = hs->nelem - queues;
836
837    hash_quality = (double)queues/hs->nelem; // no collisions means 100% quality
838
839    if (print != 0) {
840        printf("Statistic for hash '%s':\n", id);
841        printf("- size       = %zu\n", hs->size);
842        printf("- elements   = %zu (fill ratio = %4.1f%%)\n", hs->nelem, fill_ratio*100.0);
843        printf("- collisions = %li (hash quality = %4.1f%%)\n", collisions, hash_quality*100.0);
844    }
845
846    addto_hash_statistic_summary(hash_stat_man.get_stat_summary(id), hs->size, hs->nelem, collisions, fill_ratio, hash_quality);
847}
848
849static long test_numhash_count_elems(GB_NUMHASH *hs) {
850    return hs->nelem;
851}
852
853static long insert_into_hash(const char *key, long val, void *cl_toHash) {
854    GB_HASH *toHash = (GB_HASH*)cl_toHash;
855    GBS_write_hash(toHash, key, val);
856    return val;
857}
858static long erase_from_hash(const char *key, long val, void *cl_fromHash) {
859    GB_HASH *fromHash = (GB_HASH*)cl_fromHash;
860    long     val2     = GBS_read_hash(fromHash, key);
861
862    if (val2 == val) {
863        GBS_write_hash(fromHash, key, 0);
864    }
865    else {
866        printf("value mismatch in hashes_are_equal(): key='%s' val: %li != %li\n", key, val2, val); // NEED_NO_COV
867    }
868    return val;
869}
870
871static bool hashes_are_equal(GB_HASH *h1, GB_HASH *h2) {
872    size_t count1 = GBS_hash_elements(h1);
873    size_t count2 = GBS_hash_elements(h2);
874
875    bool equal = (count1 == count2);
876    if (equal) {
877        GB_HASH *copy = GBS_create_hash(count1, GB_MIND_CASE);
878       
879        GBS_hash_do_loop(h1, insert_into_hash, copy);
880        GBS_hash_do_loop(h2, erase_from_hash, copy);
881
882        equal = (GBS_hash_elements(copy) == 0);
883        GBS_free_hash(copy);
884    }
885    return equal;
886}
887
888struct TestData : virtual Noncopyable {
889    GB_HASH    *mind;
890    GB_HASH    *ignore;
891    GB_NUMHASH *num;
892
893    TestData() {
894        mind   = GBS_create_hash(100, GB_MIND_CASE);
895        ignore = GBS_create_hash(100, GB_IGNORE_CASE);
896        num    = GBS_create_numhash(100);
897    }
898    ~TestData() {
899        GBS_free_numhash(num);
900        GBS_free_hash(ignore);
901        GBS_free_hash(mind);
902    }
903
904    void reset() {
905        GBS_erase_hash(mind);
906        GBS_erase_hash(ignore);
907        GBS_erase_numhash(num);
908    }
909
910    GB_HASH *get_hash(bool case_sens) {
911        return case_sens ? mind : ignore;
912    }
913};
914
915static TestData TEST;
916
917static size_t test_hash_count_value(GB_HASH *hs, long val) {
918    size_t hsize    = hs->size;
919    size_t count = 0;
920
921    gb_assert(val != 0); // counting zero values makes no sense (cause these are not stored in the hash)
922
923    for (size_t i = 0; i<hsize; ++i) {
924        for (gbs_hash_entry *e=hs->entries[i]; e; e=e->next) {
925            if (e->val == val) {
926                ++count;
927            }
928        }
929    }
930
931    return count;
932}
933
934void TEST_GBS_write_hash() {
935    TEST.reset();
936
937    for (int case_sens = 0; case_sens <= 1; ++case_sens) {
938        GB_HASH *hash = TEST.get_hash(case_sens);
939
940        GBS_write_hash(hash, "foo", 1);
941        TEST_EXPECT_EQUAL(GBS_hash_elements(hash), 1);
942        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 1);
943
944        GBS_write_hash(hash, "foo", 2);
945        TEST_EXPECT_EQUAL(GBS_hash_elements(hash), 1);
946        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 2);
947       
948        GBS_write_hash(hash, "foo", 0);
949        TEST_EXPECT_ZERO(GBS_hash_elements(hash));
950        TEST_EXPECT_ZERO(GBS_read_hash(hash, "foo"));
951
952        GBS_write_hash(hash, "foo", 1);
953        GBS_write_hash(hash, "FOO", 2);
954        GBS_write_hash(hash, "BAR", 1);
955        GBS_write_hash(hash, "bar", 2);
956
957        if (case_sens) {
958            TEST_EXPECT_EQUAL(GBS_hash_elements(hash), 4);
959
960            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 1);
961            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "FOO"), 2);
962            TEST_EXPECT_ZERO(GBS_read_hash(hash, "Foo"));
963           
964            TEST_EXPECT_EQUAL(test_hash_count_value(hash, 1), 2);
965            TEST_EXPECT_EQUAL(test_hash_count_value(hash, 2), 2);
966        }
967        else {
968            TEST_EXPECT_EQUAL(GBS_hash_elements(hash), 2);
969
970            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 2);
971            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "FOO"), 2);
972            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "Foo"), 2);
973
974            TEST_EXPECT_ZERO(test_hash_count_value(hash, 1));
975            TEST_EXPECT_EQUAL(test_hash_count_value(hash, 2), 2);
976        }
977
978        if (case_sens) {
979            TEST_EXPECT_ZERO(GBS_read_hash(hash, "foobar"));
980            GBS_write_hash_no_strdup(hash, ARB_strdup("foobar"), 0);
981            TEST_EXPECT_ZERO(GBS_read_hash(hash, "foobar"));
982            GBS_write_hash_no_strdup(hash, ARB_strdup("foobar"), 3);
983            TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foobar"), 3);
984            GBS_write_hash_no_strdup(hash, ARB_strdup("foobar"), 0);
985            TEST_EXPECT_ZERO(GBS_read_hash(hash, "foobar"));
986        }
987    }
988}
989
990void TEST_GBS_incr_hash() {
991    TEST.reset();
992
993    for (int case_sens = 0; case_sens <= 1; ++case_sens) {
994        GB_HASH *hash = TEST.get_hash(case_sens);
995
996        GBS_incr_hash(hash, "foo");
997        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 1);
998
999        GBS_incr_hash(hash, "foo");
1000        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), 2);
1001
1002        GBS_incr_hash(hash, "FOO");
1003        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "foo"), case_sens ? 2 : 3);
1004        TEST_EXPECT_EQUAL(GBS_read_hash(hash, "FOO"), case_sens ? 1 : 3);
1005    }
1006}
1007
1008static void test_string_2_hashtab(GB_HASH *hash, char *data) {
1009    // modifies data
1010    char *p, *d, *dp;
1011    int   c;
1012    char *nextp;
1013    char *str;
1014    int   strlen;
1015    long  val;
1016
1017    for (p = data; p;   p = nextp) {
1018        strlen = 0;
1019        for (dp = p; (c = *dp); dp++) {
1020            if (c==':') {
1021                if (dp[1] == ':') dp++;
1022                else break;
1023            }
1024            strlen++;
1025        }
1026        if (*dp) {
1027            nextp = strchr(dp, ' ');
1028            if (nextp) nextp++;
1029        }
1030        else break;
1031
1032        str = ARB_calloc<char>(strlen+1);
1033        for (dp = p, d = str; (c = *dp);  dp++) {
1034            if (c==':') {
1035                if (dp[1] == ':') {
1036                    *(d++) = c;
1037                    dp++;
1038                }
1039                else break;
1040            }
1041            else {
1042                *(d++) = c;
1043            }
1044        }
1045        val = atoi(dp+1);
1046        GBS_write_hash_no_strdup(hash, str, val);
1047    }
1048}
1049
1050void TEST_GBS_hashtab_2_string() {
1051    TEST.reset();
1052
1053    for (int case_sens = 0; case_sens <= 1; ++case_sens) {
1054        GB_HASH *hash = TEST.get_hash(case_sens);
1055
1056        GBS_write_hash(hash, "foo", 1);
1057        GBS_write_hash(hash, "bar", 2);
1058        GBS_write_hash(hash, "FOO", 3);
1059        GBS_write_hash(hash, "BAR", 4);
1060        GBS_write_hash(hash, "foo:bar", 3);
1061        GBS_write_hash(hash, "FOO:bar", 4);
1062    }
1063    for (int case_sens = 0; case_sens <= 1; ++case_sens) {
1064        GB_HASH *hash = TEST.get_hash(case_sens);
1065       
1066        char *as_string = GBS_hashtab_2_string(hash);
1067        TEST_REJECT_NULL(as_string);
1068
1069        GB_HASH *hash2 = GBS_create_hash(1000, case_sens ? GB_MIND_CASE : GB_IGNORE_CASE);
1070        test_string_2_hashtab(hash2, as_string);
1071        TEST_EXPECT(hashes_are_equal(hash, hash2));
1072        TEST_EXPECT(hashes_are_equal(hash, hash2));
1073
1074        free(as_string);
1075        GBS_free_hash(hash2);
1076    }
1077
1078    {
1079        GB_HASH *hash      = TEST.get_hash(true);
1080        char    *as_string = GBS_hashtab_2_string(hash);
1081
1082        GB_HASH *hash2 = GBS_create_hash(21, GB_MIND_CASE);
1083        GBS_hash_do_sorted_loop(hash, insert_into_hash, GBS_HCF_sortedByKey, hash2);
1084       
1085        GB_HASH *hash3 = GBS_create_hash(100, GB_MIND_CASE);
1086        GBS_hash_do_sorted_loop(hash, insert_into_hash, GBS_HCF_sortedByKey, hash3);
1087
1088        char *as_string2 = GBS_hashtab_2_string(hash2); 
1089        char *as_string3 = GBS_hashtab_2_string(hash3); 
1090
1091        TEST_EXPECT_EQUAL__BROKEN(as_string, as_string2, "FOO::bar:4 BAR:4 bar:2 foo:1 FOO:3 foo::bar:3 ");
1092        TEST_EXPECT_EQUAL        (as_string, as_string3);
1093
1094        GBS_free_hash(hash3);
1095        GBS_free_hash(hash2);
1096
1097        free(as_string3);
1098        free(as_string2);
1099        free(as_string);
1100    }
1101}
1102
1103inline long key2val(long key, int pass) {
1104    long val;
1105    switch (pass) {
1106        case 1:
1107            val = key/3;
1108            break;
1109        case 2:
1110            val = key*17461;
1111            break;
1112        default :
1113            val = LONG_MIN;
1114            TEST_EXPECT(0); // NEED_NO_COV
1115            break;
1116    }
1117    return val;
1118}
1119
1120void TEST_numhash() {
1121    GB_NUMHASH *numhash  = GBS_create_numhash(10);
1122    GB_NUMHASH *numhash2 = GBS_create_numhash(10);
1123
1124    const long LOW  = -200;
1125    const long HIGH = 200;
1126    const long STEP = 17;
1127
1128    long added = 0;
1129    for (int pass = 1; pass <= 2; ++pass) {
1130        added = 0;
1131        for (long key = LOW; key <= HIGH; key += STEP) {
1132            long val = key2val(key, pass);
1133            GBS_write_numhash(numhash, key, val);
1134            added++;
1135        }
1136
1137        TEST_EXPECT_EQUAL(test_numhash_count_elems(numhash), added);
1138
1139        for (long key = LOW; key <= HIGH; key += STEP) {
1140            TEST_EXPECT_EQUAL(key2val(key, pass), GBS_read_numhash(numhash, key));
1141        }
1142    }
1143
1144    TEST_EXPECT_ZERO(GBS_read_numhash(numhash, -4711)); // not-existing entry
1145
1146    // erase by overwrite:
1147    for (long key = LOW; key <= HIGH; key += STEP) {
1148        GBS_write_numhash(numhash2, key, GBS_read_numhash(numhash, key)); // copy numhash->numhash2
1149        GBS_write_numhash(numhash, key, (long)NULL);
1150    }
1151    TEST_EXPECT_EQUAL(test_numhash_count_elems(numhash2), added);
1152    TEST_EXPECT_ZERO(test_numhash_count_elems(numhash));
1153
1154    GBS_free_numhash(numhash2);                     // free filled hash
1155    GBS_free_numhash(numhash);                      // free empty hash
1156}
1157
1158
1159static int freeCounter;
1160static void freeDynamicHashElem(long cl_ptr) {
1161    GBS_dynaval_free(cl_ptr);
1162    freeCounter++;
1163}
1164
1165void TEST_GBS_dynaval_hash() {
1166    const int SIZE  = 10;
1167    const int ELEMS = 30;
1168
1169    GB_HASH *dynahash = GBS_create_dynaval_hash(SIZE, GB_MIND_CASE, freeDynamicHashElem);
1170
1171    for (int pass = 1; pass <= 2; ++pass) {
1172        freeCounter = 0;
1173
1174        for (int i = 0; i<ELEMS; ++i) {
1175            char *val    = GBS_global_string_copy("value %i", i);
1176            char *oldval = (char*)GBS_write_hash(dynahash, GBS_global_string("key %i", i), (long)val);
1177            free(oldval);
1178        }
1179
1180        TEST_EXPECT_ZERO(freeCounter); // overwriting values shall not automatically free them
1181    }
1182
1183    freeCounter = 0;
1184    GBS_free_hash(dynahash);
1185    TEST_EXPECT_EQUAL(freeCounter, ELEMS);
1186}
1187
1188void TEST_GBS_optimize_hash_and_stats() {
1189    const int SIZE = 10;
1190    const int FILL = 70;
1191
1192    test_clear_hash_statistic_summary("test");
1193    for (int pass = 1; pass <= 3; ++pass) {
1194        GB_HASH *hash = GBS_create_hash(SIZE, GB_MIND_CASE);
1195
1196        for (int i = 1; i <= FILL; ++i) {
1197            const char *key =  GBS_global_string("%i", i);
1198            GBS_write_hash(hash, key, i);
1199        }
1200        TEST_EXPECT(hash->nelem > hash->size); // ensure hash is overfilled!
1201
1202        switch (pass) {
1203            case 1:                                 // nothing, only free overfilled hash below
1204                break;
1205            case 2:                                 // test overwrite overfilled hash
1206                for (int i = 1; i <= FILL; ++i) {
1207                    const char *key = GBS_global_string("%i", i);
1208                   
1209                    TEST_EXPECT_EQUAL(GBS_read_hash(hash, key), i);
1210                    GBS_write_hash(hash, key, 0);
1211                    TEST_EXPECT_ZERO(GBS_read_hash(hash, key));
1212                }
1213                break;
1214            case 3:                                 // test optimize
1215                GBS_optimize_hash(hash);
1216                TEST_EXPECT_LESS_EQUAL(hash->nelem, hash->size);
1217                break;
1218            default :
1219                TEST_EXPECT(0);                     // NEED_NO_COV
1220                break;
1221        }
1222
1223        test_calc_hash_statistic(hash, "test", 1);
1224        GBS_free_hash(hash);
1225    }
1226
1227    test_print_hash_statistic_summary("test");
1228}
1229
1230static bool has_value(const char *, long val, void *cd) { return val == (long)cd; }
1231static bool has_value_greater(const char *, long val, void *cd) { return val > (long)cd; }
1232
1233void TEST_GBS_hash_next_element_that() {
1234    TEST.reset();
1235
1236    for (int case_sens = 0; case_sens <= 1; ++case_sens) {
1237        GB_HASH *hash = TEST.get_hash(case_sens);
1238
1239        GBS_write_hash(hash, "foo", 0);
1240        GBS_write_hash(hash, "bar", 1);
1241        GBS_write_hash(hash, "foobar", 2);
1242        GBS_write_hash(hash, "barfoo", 3);
1243
1244#define READ_REVERSE(value) GBS_hash_next_element_that(hash, NULL, has_value, (void*)value)
1245#define ASSERT_READ_REVERSE_RETURNS(value, expected) TEST_EXPECT_EQUAL((const char *)expected, READ_REVERSE(value));
1246
1247        ASSERT_READ_REVERSE_RETURNS(0, NULL);
1248        ASSERT_READ_REVERSE_RETURNS(1, "bar");
1249        ASSERT_READ_REVERSE_RETURNS(2, "foobar");
1250        ASSERT_READ_REVERSE_RETURNS(3, "barfoo");
1251        ASSERT_READ_REVERSE_RETURNS(4, NULL);
1252
1253        const char *key = NULL;
1254        long        sum = 0;
1255
1256        for (int iter = 1; iter <= 3; ++iter) {
1257            key = GBS_hash_next_element_that(hash, key, has_value_greater, (void*)1);
1258            if (iter == 3) TEST_REJECT(key);
1259            else {
1260                TEST_REJECT_NULL(key);
1261                sum += GBS_read_hash(hash, key);
1262            }
1263        }
1264        TEST_EXPECT_EQUAL(sum, 5); // sum of all values > 1
1265    }
1266}
1267
1268const size_t MAX_PRIME  = sorted_primes[KNOWN_PRIMES-1];
1269
1270static size_t get_overflown_prime() { return gbs_get_a_prime(MAX_PRIME+1); }
1271#if defined(ASSERTION_USED)
1272static void detect_prime_overflow() { get_overflown_prime(); }
1273#endif // ASSERTION_USED
1274
1275void TEST_hash_specials() {
1276    const size_t SOME_PRIME = 434201;
1277    TEST_EXPECT_EQUAL(gbs_get_a_prime(SOME_PRIME), SOME_PRIME);
1278    TEST_EXPECT_EQUAL(gbs_get_a_prime(MAX_PRIME), MAX_PRIME);
1279
1280#if defined(ASSERTION_USED)
1281    TEST_EXPECT_CODE_ASSERTION_FAILS(detect_prime_overflow);
1282#else
1283    TEST_EXPECT_EQUAL(get_overflown_prime(), MAX_PRIME+1);
1284#endif // ASSERTION_USED
1285}
1286
1287#endif // UNIT_TESTS
1288
1289
1290
Note: See TracBrowser for help on using the repository browser.