forked from xroche/coucal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coucal.c
1562 lines (1364 loc) · 51.9 KB
/
coucal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------------------------------------------------------------ */
/*
Coucal, Cuckoo hashing-based hashtable with stash area.
Copyright (C) 2013-2014 Xavier Roche (https://www.httrack.com/)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#include "coucal.h"
/* We use murmur hashing by default, even if md5 can be a good candidate,
for its quality regarding diffusion and collisions.
MD5 is slower than other hashing functions, but is known to be an excellent
hashing function. FNV-1 is generally good enough for this purpose, too, but
the performance gain is not sufficient to use it by default.
On several benchmarks, both MD5 and FNV were quite good (0.45 cuckoo moved
on average for each new item inserted in the hashtable), but FNV-1 was more
prone to mutual collisions (creating cycles requiring stash handling), and
was causing the stash area to be more filled than the MD5 variant.
Simpler hashing functions, such as rolling hashes (LCG) were also tested,
but with collision rate and diffusion were terrible.
[ On a 10M key tests, both variants acheived 0.45 cuckoo/add ration,
but the FNV-1 variant collided 11 times with a maximum stash area
filled with 4 entries ; whereas the MD5 variant did only collide
once ]
*/
#if (!defined(HTS_INTHASH_USES_MD5) \
&& !defined(HTS_INTHASH_USES_OPENSSL_MD5) \
&& !defined(HTS_INTHASH_USES_MURMUR) \
&& !defined(HTS_INTHASH_USES_FNV1) \
)
/* Temporry: fixing Invalid address alignment issues */
#if (defined(HAVE_ALIGNED_ACCESS_REQUIRED) \
|| defined(__sparc__) \
|| defined(mips) || defined(__mips__) || defined(MIPS) || defined(_MIPS_) \
|| defined(arm) || defined(__arm__) || defined(ARM) || defined(_ARM_) \
)
#ifndef LIBHTTRACK_EXPORTS
#define HTS_INTHASH_USES_OPENSSL_MD5 1
#else
#define HTS_INTHASH_USES_MD5 1
#endif
#else
#define HTS_INTHASH_USES_MURMUR 1
#endif
#endif
/* Dispatch includes */
#if (defined(HTS_INTHASH_USES_MURMUR))
#include "murmurhash3.h"
#elif (defined(HTS_INTHASH_USES_MD5))
#include "md5.h"
#define HashMD5Init(CTX, FLAG) MD5Init(CTX, FLAG)
#define HashMD5Update(CTX, DATA, SIZE) MD5Update(CTX, DATA, SIZE)
#define HashMD5Final(DIGEST, CTX) MD5Final(DIGEST, CTX)
#define HashMD5Context MD5CTX
#elif (defined(HTS_INTHASH_USES_OPENSSL_MD5))
#include <openssl/md5.h>
#define HashMD5Init(CTX, FLAG) MD5_Init(CTX)
#define HashMD5Update(CTX, DATA, SIZE) MD5_Update(CTX, DATA, SIZE)
#define HashMD5Final(DIGEST, CTX) MD5_Final(DIGEST, CTX)
#define HashMD5Context MD5_CTX
#else
#error "No hash method defined"
#endif
/** Size of auxiliary stash. **/
#define STASH_SIZE 16
/** Minimum value for lg_size. **/
#define MIN_LG_SIZE 4
/** Minimum value for pool.capacity. **/
#define MIN_POOL_CAPACITY 256
/* 64-bit constant */
#if (defined(WIN32))
#define UINT_64_CONST(X) ((uint64_t) (X))
#define UINT_64_FORMAT "I64d"
#elif (defined(_LP64) || defined(__x86_64__) \
|| defined(__powerpc64__) || defined(__64BIT__))
#define UINT_64_CONST(X) ((uint64_t) X##UL)
#define UINT_64_FORMAT "ld"
#else
#define UINT_64_CONST(X) ((uint64_t) X##ULL)
#define UINT_64_FORMAT "lld"
#endif
/** Hashtable. **/
struct struct_coucal {
/** Hashtable items. **/
coucal_item *items;
/** Log-2 of the hashtable size. **/
size_t lg_size;
/** Number of used items (<= POW2(lg_size)). **/
size_t used;
/** Stash area for collisions. **/
struct {
/** Stash items. **/
coucal_item items[STASH_SIZE];
/** Stash size (<= STASH_SIZE). **/
size_t size;
} stash;
/** String pool. **/
struct {
/** String buffer. **/
char *buffer;
/** Buffer used size (high watermark). **/
size_t size;
/** Buffer capacity. **/
size_t capacity;
/** Used chars (== size if compacted). **/
size_t used;
} pool;
/** Statistics **/
struct {
/** Highest stash.size seen. **/
size_t max_stash_size;
/** Number of writes. **/
size_t write_count;
/** Number of writes causing an add. **/
size_t add_count;
/** Number of cuckoo moved during adds. **/
size_t cuckoo_moved;
/** Number of items added to stash. **/
size_t stash_added;
/** Number of hashtable rehash/expand operations. **/
size_t rehash_count;
/** Number of pool compact operations. **/
size_t pool_compact_count;
/** Number of pool realloc operations. **/
size_t pool_realloc_count;
} stats;
/** Settings. **/
struct {
/** How to handle values (might be NULL). **/
struct {
/** free() **/
t_coucal_value_freehandler free;
/** opaque argument **/
coucal_opaque arg;
} value;
/** How to handle names (might be NULL). **/
struct {
/** strdup() **/
t_coucal_duphandler dup;
/** free() **/
t_coucal_key_freehandler free;
/** hash **/
t_coucal_hasheshandler hash;
/** comparison **/
t_coucal_cmphandler equals;
/** opaque argument **/
coucal_opaque arg;
} key;
/** How to handle fatal assertions (might be NULL). **/
struct {
/** logging **/
t_coucal_loghandler log;
/** abort() **/
t_coucal_asserthandler fatal;
/** opaque argument **/
coucal_opaque arg;
/** hashtable name for logging **/
coucal_key_const name;
} error;
/** How to handle pretty-print (debug) (might be NULL). **/
struct {
/** key print() **/
t_coucal_printkeyhandler key;
/** value print() **/
t_coucal_printvaluehandler value;
/** opaque argument **/
coucal_opaque arg;
} print;
} custom;
};
/* Assertion check. */
#define coucal_assert(HASHTABLE, EXP) \
(void)( (EXP) || (coucal_assert_failed(HASHTABLE, #EXP, __FILE__, __LINE__), 0) )
/* Compiler-specific. */
#ifdef __GNUC__
#define INTHASH_PRINTF_FUN(fmt, arg) __attribute__ ((format (printf, fmt, arg)))
#define INTHASH_INLINE __inline__
#elif (defined(_MSC_VER))
#define INTHASH_PRINTF_FUN(FMT, ARGS)
#define INTHASH_INLINE __inline
#else
#define INTHASH_PRINTF_FUN(FMT, ARGS)
#define INTHASH_INLINE
#endif
/* Logging level. */
static void coucal_log(const coucal hashtable, coucal_loglevel level,
const char *format, va_list args);
#define DECLARE_LOG_FUNCTION(NAME, LEVEL) \
static void NAME(const coucal hashtable, const char *format, ...) \
INTHASH_PRINTF_FUN(2, 3); \
static void NAME(const coucal hashtable, const char *format, ...) { \
va_list args; \
va_start(args, format); \
coucal_log(hashtable, LEVEL, format, args); \
va_end(args); \
}
#if 0
/* Verbose. */
DECLARE_LOG_FUNCTION(coucal_crit, coucal_log_critical)
DECLARE_LOG_FUNCTION(coucal_warning, coucal_log_warning)
DECLARE_LOG_FUNCTION(coucal_info, coucal_log_info)
DECLARE_LOG_FUNCTION(coucal_debug, coucal_log_debug)
DECLARE_LOG_FUNCTION(coucal_trace, coucal_log_trace)
#elif 0
/* Info. */
DECLARE_LOG_FUNCTION(coucal_crit, coucal_log_critical)
DECLARE_LOG_FUNCTION(coucal_warning, coucal_log_warning)
DECLARE_LOG_FUNCTION(coucal_info, coucal_log_info)
#define coucal_debug coucal_log
#define coucal_trace coucal_nolog
#else
/* No logging except stats and critical. */
DECLARE_LOG_FUNCTION(coucal_crit, coucal_log_critical)
DECLARE_LOG_FUNCTION(coucal_warning, coucal_log_warning)
DECLARE_LOG_FUNCTION(coucal_info, coucal_log_info)
#define coucal_debug coucal_nolog
#define coucal_trace coucal_nolog
#endif
/* 2**X */
#define POW2(X) ( (size_t) 1 << (X) )
/* the empty string for the string pool */
static char the_empty_string[1] = { 0 };
/* global assertion handler */
static t_coucal_asserthandler global_assert_handler = NULL;
/* global assertion handler */
static t_coucal_loghandler global_log_handler = NULL;
/* default assertion handler, if neither hashtable one nor global one
were defined */
static void coucal_fail(const char* exp, const char* file, int line) {
fprintf(stderr, "assertion '%s' failed at %s:%d\n", exp, file, line);
abort();
}
/* assert failed handler. */
static void coucal_assert_failed(const coucal hashtable, const char* exp, const char* file, int line) {
const char *const name = coucal_get_name(hashtable);
coucal_crit(hashtable, "hashtable %s: %s failed at %s:%d",
name != NULL ? name : "<unknown>", exp, file, line);
if (hashtable != NULL && hashtable->custom.error.fatal != NULL) {
hashtable->custom.error.fatal(hashtable->custom.error.arg, exp, file, line);
} else if (global_assert_handler != NULL) {
global_assert_handler(hashtable, exp, file, line);
} else {
coucal_fail(exp, file, line);
}
abort();
}
/* Logging */
static void coucal_log(const coucal hashtable, coucal_loglevel level,
const char *format, va_list args) {
coucal_assert(hashtable, format != NULL);
if (hashtable != NULL && hashtable->custom.error.log != NULL) {
hashtable->custom.error.log(hashtable->custom.error.arg, level, format, args);
} else if (global_log_handler != NULL) {
global_log_handler(hashtable, level, format, args);
} else {
fprintf(stderr, "[%p] ", (void*) hashtable);
(void) vfprintf(stderr, format, args);
putc('\n', stderr);
}
}
/* No logging (should be dropped by the compiler) */
static INTHASH_INLINE void coucal_nolog(const coucal hashtable,
const char *format, ...)
INTHASH_PRINTF_FUN(2, 3);
static INTHASH_INLINE void coucal_nolog(const coucal hashtable,
const char *format, ...) {
(void) hashtable;
(void) format;
}
const char* coucal_get_name(coucal hashtable) {
return hashtable->custom.error.name;
}
static void coucal_log_stats(coucal hashtable) {
const char *const name = coucal_get_name(hashtable);
coucal_info(hashtable, "hashtable %s%s%ssummary: "
"size=%"UINT_64_FORMAT" (lg2=%"UINT_64_FORMAT") "
"used=%"UINT_64_FORMAT" "
"stash-size=%"UINT_64_FORMAT" "
"pool-size=%"UINT_64_FORMAT" "
"pool-capacity=%"UINT_64_FORMAT" "
"pool-used=%"UINT_64_FORMAT" "
"writes=%"UINT_64_FORMAT" "
"(new=%"UINT_64_FORMAT") "
"moved=%"UINT_64_FORMAT " "
"stashed=%"UINT_64_FORMAT" "
"max-stash-size=%"UINT_64_FORMAT" "
"avg-moved=%g "
"rehash=%"UINT_64_FORMAT" "
"pool-compact=%"UINT_64_FORMAT" "
"pool-realloc=%"UINT_64_FORMAT" "
"memory=%"UINT_64_FORMAT,
name != NULL ? "\"" : "",
name != NULL ? name : "",
name != NULL ? "\" " : "",
(uint64_t) POW2(hashtable->lg_size),
(uint64_t) hashtable->lg_size,
(uint64_t) hashtable->used,
(uint64_t) hashtable->stash.size,
(uint64_t) hashtable->pool.size,
(uint64_t) hashtable->pool.capacity,
(uint64_t) hashtable->pool.used,
(uint64_t) hashtable->stats.write_count,
(uint64_t) hashtable->stats.add_count,
(uint64_t) hashtable->stats.cuckoo_moved,
(uint64_t) hashtable->stats.stash_added,
(uint64_t) hashtable->stats.max_stash_size,
(double) hashtable->stats.cuckoo_moved / (double) hashtable->stats.add_count,
(uint64_t) hashtable->stats.rehash_count,
(uint64_t) hashtable->stats.pool_compact_count,
(uint64_t) hashtable->stats.pool_realloc_count,
(uint64_t) coucal_memory_size(hashtable)
);
}
/* default hash function when key is a regular C-string */
coucal_hashkeys coucal_hash_data(const void *data_, size_t size) {
const unsigned char *const data = (const unsigned char *) data_;
#if (defined(HTS_INTHASH_USES_MD5) || defined(HTS_INTHASH_USES_OPENSSL_MD5))
/* compute a regular MD5 and extract two 32-bit integers */
HashMD5Context ctx;
union {
unsigned char md5digest[16];
#if (COUCAL_HASH_SIZE == 32)
coucal_hashkeys mhashes[2];
#endif
coucal_hashkeys hashes;
} u;
/* compute MD5 */
HashMD5Init(&ctx, 0);
HashMD5Update(&ctx, data, (unsigned int) size);
HashMD5Final(u.md5digest, &ctx);
#if (COUCAL_HASH_SIZE == 32)
/* mix mix mix */
u.mhashes[0].hash1 ^= u.mhashes[1].hash1;
u.mhashes[0].hash2 ^= u.mhashes[1].hash2;
#endif
/* do not keep identical hashes */
if (u.hashes.hash1 == u.hashes.hash2) {
u.hashes.hash2 = ~u.hashes.hash2;
}
return u.hashes;
#elif (defined(HTS_INTHASH_USES_MURMUR))
union {
uint32_t result[4];
coucal_hashkeys hashes;
} u;
MurmurHash3_x86_128(data, (const int) size, 42, &u.result);
#if (COUCAL_HASH_SIZE == 32)
/* mix mix mix */
u.result[0] ^= u.result[2];
u.result[1] ^= u.result[3];
#endif
/* do not keep identical hashes */
if (u.hashes.hash1 == u.hashes.hash2) {
u.hashes.hash2 = ~u.hashes.hash2;
}
return u.hashes;
#elif (defined(HTS_INTHASH_USES_FNV1))
/* compute two Fowler-Noll-Vo hashes (64-bit FNV-1 variant) ;
each 64-bit hash being XOR-folded into a single 32-bit hash. */
size_t i;
coucal_hashkeys hashes;
uint64_t h1, h2;
/* FNV-1, 64-bit. */
#define FNV1_PRIME UINT_64_CONST(1099511628211)
#define FNV1_OFFSET_BASIS UINT_64_CONST(14695981039346656037)
/* compute the hashes ; second variant is using xored data */
h1 = FNV1_OFFSET_BASIS;
h2 = ~FNV1_OFFSET_BASIS;
for(i = 0 ; i < size ; i++) {
const unsigned char c1 = data[i];
const unsigned char c2 = ~c1;
h1 = ( h1 * FNV1_PRIME ) ^ c1;
h2 = ( h2 * FNV1_PRIME ) ^ c2;
}
#if (COUCAL_HASH_SIZE == 32)
/* XOR-folding to improve diffusion (Wikipedia) */
hashes.hash1 = ( (uint32_t) h1 ^ (uint32_t) ( h1 >> 32 ) );
hashes.hash2 = ( (uint32_t) h2 ^ (uint32_t) ( h2 >> 32 ) );
#elif (COUCAL_HASH_SIZE == 64)
/* Direct hashes */
hashes.hash1 = h1;
hashes.hash2 = h2;
#else
#error "Unsupported COUCAL_HASH_SIZE"
#endif
#undef FNV1_PRIME
#undef FNV1_OFFSET_BASIS
/* do not keep identical hashes */
if (hashes.hash1 == hashes.hash2) {
hashes.hash2 = ~hashes.hash2;
}
return hashes;
#else
#error "Undefined hashing method"
#endif
}
INTHASH_INLINE coucal_hashkeys coucal_hash_string(const char *name) {
return coucal_hash_data(name, strlen(name));
}
INTHASH_INLINE coucal_hashkeys coucal_calc_hashes(coucal hashtable,
coucal_key_const value) {
return hashtable->custom.key.hash == NULL
? coucal_hash_string(value)
: hashtable->custom.key.hash(hashtable->custom.key.arg, value);
}
/* position 'pos' is free ? */
static INTHASH_INLINE int coucal_is_free(const coucal hashtable, size_t pos) {
return hashtable->items[pos].name == NULL;
}
/* compare two keys ; by default using strcmp() */
static INTHASH_INLINE int coucal_equals(coucal hashtable,
coucal_key_const a,
coucal_key_const b) {
return hashtable->custom.key.equals == NULL
? strcmp((const char*) a, (const char*) b) == 0
: hashtable->custom.key.equals(hashtable->custom.key.arg, a, b);
}
static INTHASH_INLINE int coucal_matches_(coucal hashtable,
const coucal_item *const item,
coucal_key_const name,
const coucal_hashkeys *hashes) {
return item->name != NULL
&& item->hashes.hash1 == hashes->hash1
&& item->hashes.hash2 == hashes->hash2
&& coucal_equals(hashtable, item->name, name);
}
static INTHASH_INLINE int coucal_matches(coucal hashtable, size_t pos,
coucal_key_const name,
const coucal_hashkeys *hashes) {
const coucal_item *const item = &hashtable->items[pos];
return coucal_matches_(hashtable, item, name, hashes);
}
/* compact string pool ; does not necessarily change the capacity */
static void coucal_compact_pool(coucal hashtable, size_t capacity) {
const size_t hash_size = POW2(hashtable->lg_size);
size_t i;
char*const old_pool = hashtable->pool.buffer;
const size_t old_size = hashtable->pool.size;
size_t count = 0;
/* we manage the string pool */
coucal_assert(hashtable, hashtable->custom.key.dup == NULL);
/* statistics */
hashtable->stats.pool_compact_count++;
/* change capacity now */
if (hashtable->pool.capacity != capacity) {
hashtable->pool.capacity = capacity;
}
/* realloc */
hashtable->pool.buffer = malloc(hashtable->pool.capacity);
hashtable->pool.size = 0;
hashtable->pool.used = 0;
if (hashtable->pool.buffer == NULL) {
coucal_debug(hashtable,
"** hashtable string pool compaction error: could not allocate "
"%"UINT_64_FORMAT" bytes",
(uint64_t) hashtable->pool.capacity);
coucal_assert(hashtable, ! "hashtable string pool compaction error");
}
/* relocate a string on a different pool */
#define RELOCATE_STRING(S) do { \
if (S != NULL && S != the_empty_string) { \
const char *const src = (S); \
char *const dest = \
&hashtable->pool.buffer[hashtable->pool.size]; \
const size_t capacity = hashtable->pool.capacity; \
char *const max_dest = \
&hashtable->pool.buffer[capacity]; \
/* copy string */ \
coucal_assert(hashtable, dest < max_dest); \
dest[0] = src[0]; \
{ \
size_t i; \
for(i = 1 ; src[i - 1] != '\0' ; i++) { \
coucal_assert(hashtable, &dest[i] < max_dest); \
dest[i] = src[i]; \
} \
/* update pool size */ \
hashtable->pool.size += i; \
coucal_assert(hashtable, \
hashtable->pool.size <= capacity); \
} \
/* update source */ \
S = dest; \
count++; \
} \
} while(0)
/* relocate */
for(i = 0 ; i < hash_size ; i++) {
RELOCATE_STRING(hashtable->items[i].name);
}
for(i = 0 ; i < hashtable->stash.size ; i++) {
RELOCATE_STRING(hashtable->stash.items[i].name);
}
#undef RELOCATE_STRING
/* compacted (used chars == current size) */
hashtable->pool.used = hashtable->pool.size;
/* wipe previous pool */
free(old_pool);
coucal_debug(hashtable,
"compacted string pool for %"UINT_64_FORMAT" strings: "
"%"UINT_64_FORMAT" bytes => %"UINT_64_FORMAT" bytes",
(uint64_t) count, (uint64_t) old_size,
(uint64_t) hashtable->pool.size);
}
/* realloc (expand) string pool ; does not change the compacity */
static void coucal_realloc_pool(coucal hashtable, size_t capacity) {
const size_t hash_size = POW2(hashtable->lg_size);
char *const oldbase = hashtable->pool.buffer;
size_t count = 0;
/* we manage the string pool */
coucal_assert(hashtable, hashtable->custom.key.dup == NULL);
/* compact instead ? */
if (hashtable->pool.used < ( hashtable->pool.size*3 ) / 4) {
coucal_compact_pool(hashtable, capacity);
return ;
}
/* statistics */
hashtable->stats.pool_realloc_count++;
/* change capacity now */
hashtable->pool.capacity = capacity;
/* realloc */
hashtable->pool.buffer = realloc(hashtable->pool.buffer,
hashtable->pool.capacity);
if (hashtable->pool.buffer == NULL) {
coucal_crit(hashtable,
"** hashtable string pool allocation error: could not allocate "
"%"UINT_64_FORMAT" bytes",
(uint64_t) hashtable->pool.capacity);
coucal_assert(hashtable, ! "hashtable string pool allocation error");
}
/* recompute string address */
#define RECOMPUTE_STRING(S) do { \
if (S != NULL && S != the_empty_string) { \
const size_t offset = (const char*) (S) - oldbase; \
coucal_assert(hashtable, offset < hashtable->pool.capacity); \
S = &hashtable->pool.buffer[offset]; \
count++; \
} \
} while(0)
/* recompute string addresses */
if (hashtable->pool.buffer != oldbase) {
size_t i;
for(i = 0 ; i < hash_size ; i++) {
RECOMPUTE_STRING(hashtable->items[i].name);
}
for(i = 0 ; i < hashtable->stash.size ; i++) {
RECOMPUTE_STRING(hashtable->stash.items[i].name);
}
}
#undef RECOMPUTE_STRING
coucal_debug(hashtable, "reallocated string pool for "
"%"UINT_64_FORMAT" strings: %"UINT_64_FORMAT" bytes",
(uint64_t) count, (uint64_t) hashtable->pool.capacity);
}
static coucal_key coucal_dup_name_internal(coucal hashtable,
coucal_key_const name_) {
const char *const name = (const char*) name_;
const size_t len = strlen(name) + 1;
char *s;
/* the pool does not allow empty strings for safety purpose ; handhe that
(keys are being emptied when free'd to detect duplicate free) */
if (len == 1) {
coucal_assert(hashtable, the_empty_string[0] == '\0');
return the_empty_string;
}
/* expand pool capacity */
coucal_assert(hashtable, hashtable->pool.size <= hashtable->pool.capacity);
if (hashtable->pool.capacity - hashtable->pool.size < len) {
size_t capacity;
for(capacity = MIN_POOL_CAPACITY ; capacity < hashtable->pool.size + len
; capacity <<= 1) ;
coucal_assert(hashtable, hashtable->pool.size < capacity);
coucal_realloc_pool(hashtable, capacity);
}
/* copy */
coucal_assert(hashtable, len + hashtable->pool.size <= hashtable->pool.capacity);
s = &hashtable->pool.buffer[hashtable->pool.size];
memcpy(s, name, len);
hashtable->pool.size += len;
hashtable->pool.used += len;
return s;
}
/* duplicate a key. default is to use the internal pool. */
static INTHASH_INLINE coucal_key coucal_dup_name(coucal hashtable,
coucal_key_const name) {
return hashtable->custom.key.dup == NULL
? coucal_dup_name_internal(hashtable, name)
: hashtable->custom.key.dup(hashtable->custom.key.arg, name);
}
/* internal pool free handler.
note: pointer must have been kicked from the pool first */
static void coucal_free_key_internal(coucal hashtable, coucal_key name_) {
char *const name = (char*) name_;
const size_t len = strlen(name) + 1;
/* see coucal_dup_name_internal() handling */
if (len == 1 && name == the_empty_string) {
coucal_assert(hashtable, the_empty_string[0] == '\0');
return ;
}
coucal_assert(hashtable, *name != '\0' || !"duplicate or bad string pool release");
hashtable->pool.used -= len;
*name = '\0'; /* the string is now invalidated */
/* compact the pool is too many holes */
if (hashtable->pool.used != 0
&& hashtable->pool.used < hashtable->pool.size / 2) {
size_t capacity = hashtable->pool.capacity;
/* compact and shrink */
if (hashtable->pool.used < capacity / 4) {
capacity /= 2;
}
coucal_assert(hashtable, hashtable->pool.used < capacity);
coucal_compact_pool(hashtable, capacity);
}
}
/* free a key. default is to use the internal pool.
note: pointer must have been kicked from the pool first */
static void coucal_free_key(coucal hashtable, coucal_key name) {
if (hashtable->custom.key.free == NULL) {
coucal_free_key_internal(hashtable, name);
} else {
hashtable->custom.key.free(hashtable->custom.key.arg, name);
}
}
static INTHASH_INLINE size_t coucal_hash_to_pos_(size_t lg_size,
coucal_hashkey hash) {
const coucal_hashkey mask = POW2(lg_size) - 1;
return hash & mask;
}
static INTHASH_INLINE size_t coucal_hash_to_pos(const coucal hashtable,
coucal_hashkey hash) {
return coucal_hash_to_pos_(hashtable->lg_size, hash);
}
int coucal_read_pvoid(coucal hashtable, coucal_key_const name, void **pvalue) {
coucal_value value = INTHASH_VALUE_NULL;
const int ret =
coucal_read_value(hashtable, name, (pvalue != NULL) ? &value : NULL);
if (pvalue != NULL)
*pvalue = value.ptr;
return ret;
}
void* coucal_get_pvoid(coucal hashtable, coucal_key_const name) {
void *value;
if (!coucal_read_pvoid(hashtable, name, &value)) {
return NULL;
}
return value;
}
int coucal_write_pvoid(coucal hashtable, coucal_key_const name, void *pvalue) {
coucal_value value = INTHASH_VALUE_NULL;
value.ptr = pvalue;
return coucal_write_value(hashtable, name, value);
}
void coucal_add_pvoid(coucal hashtable, coucal_key_const name, void *pvalue) {
coucal_value value = INTHASH_VALUE_NULL;
value.ptr = pvalue;
coucal_write_value(hashtable, name, value);
}
int coucal_write(coucal hashtable, coucal_key_const name, intptr_t intvalue) {
coucal_value value = INTHASH_VALUE_NULL;
value.intg = intvalue;
return coucal_write_value(hashtable, name, value);
}
static void coucal_default_free_handler(coucal_opaque arg,
coucal_value value) {
(void) arg;
if (value.ptr != NULL)
free(value.ptr);
}
static INTHASH_INLINE void coucal_del_value_(coucal hashtable, coucal_value *pvalue) {
if (pvalue->ptr != NULL) {
if (hashtable->custom.value.free != NULL)
hashtable->custom.value.free(hashtable->custom.value.arg, *pvalue);
pvalue->ptr = NULL;
}
}
static INTHASH_INLINE void coucal_del_value(coucal hashtable, size_t pos) {
coucal_del_value_(hashtable, &hashtable->items[pos].value);
}
static void coucal_del_name(coucal hashtable, coucal_item *item) {
const coucal_hashkeys nullHash = INTHASH_KEYS_NULL;
char *const name = (char*) item->name;
item->name = NULL; /* there must be no reference remaining */
item->hashes = nullHash;
/* free after detach (we may compact the pool) */
coucal_free_key(hashtable, name);
}
static void coucal_del_item(coucal hashtable, coucal_item *pitem) {
coucal_del_value_(hashtable, &pitem->value);
coucal_del_name(hashtable, pitem);
}
static int coucal_add_item_(coucal hashtable, coucal_item item);
/* Write (add or replace) a value in the hashtable. */
static int coucal_write_value_(coucal hashtable, coucal_key_const name,
coucal_value value) {
coucal_item item;
size_t pos;
const coucal_hashkeys hashes = coucal_calc_hashes(hashtable, name);
/* Statistics */
hashtable->stats.write_count++;
/* replace at position 1 ? */
pos = coucal_hash_to_pos(hashtable, hashes.hash1);
if (coucal_matches(hashtable, pos, name, &hashes)) {
coucal_del_value(hashtable, pos);
hashtable->items[pos].value = value;
return 0; /* replaced */
}
/* replace at position 2 ? */
pos = coucal_hash_to_pos(hashtable, hashes.hash2);
if (coucal_matches(hashtable, pos, name, &hashes)) {
coucal_del_value(hashtable, pos);
hashtable->items[pos].value = value;
return 0; /* replaced */
}
/* replace in the stash ? */
if (hashtable->stash.size != 0) {
size_t i;
for(i = 0 ; i < hashtable->stash.size ; i++) {
if (coucal_matches_(hashtable, &hashtable->stash.items[i], name,
&hashes)) {
coucal_del_value_(hashtable, &hashtable->stash.items[i].value);
hashtable->stash.items[i].value = value;
return 0; /* replaced */
}
}
}
/* Statistics */
hashtable->stats.add_count++;
/* otherwise we need to create a new item */
item.name = coucal_dup_name(hashtable, name);
item.value = value;
item.hashes = hashes;
return coucal_add_item_(hashtable, item);
}
/* Return the string representation of a key */
static const char* coucal_print_key(coucal hashtable,
coucal_key_const name) {
return hashtable->custom.print.key != NULL
? hashtable->custom.print.key(hashtable->custom.print.arg, name)
: (const char*) name;
}
/* Add a new item in the hashtable. The item SHALL NOT be already present. */
static int coucal_add_item_(coucal hashtable, coucal_item item) {
coucal_hashkey cuckoo_hash, initial_cuckoo_hash;
size_t loops;
size_t pos;
/* place at free position 1 ? */
pos = coucal_hash_to_pos(hashtable, item.hashes.hash1);
if (coucal_is_free(hashtable, pos)) {
hashtable->items[pos] = item;
return 1; /* added */
} else {
/* place at free position 2 ? */
pos = coucal_hash_to_pos(hashtable, item.hashes.hash2);
if (coucal_is_free(hashtable, pos)) {
hashtable->items[pos] = item;
return 1; /* added */
}
/* prepare cuckoo ; let's take position 1 */
else {
cuckoo_hash = initial_cuckoo_hash = item.hashes.hash1;
coucal_trace(hashtable,
"debug:collision with '%s' at %"UINT_64_FORMAT" (%x)",
coucal_print_key(hashtable, item.name),
(uint64_t) pos, cuckoo_hash);
}
}
/* put 'item' in place with hash 'cuckoo_hash' */
for(loops = POW2(hashtable->lg_size) ; loops != 0 ; --loops) {
const size_t pos = coucal_hash_to_pos(hashtable, cuckoo_hash);
coucal_trace(hashtable,
"\tdebug:placing cuckoo '%s' at %"UINT_64_FORMAT" (%x)",
coucal_print_key(hashtable, item.name),
(uint64_t) pos, cuckoo_hash);
/* place at alternate free position ? */
if (coucal_is_free(hashtable, pos)) {
coucal_trace(hashtable, "debug:free position");
hashtable->items[pos] = item;
return 1; /* added */
}
/* then cuckoo's place it is */
else {
/* replace */
const coucal_item backup_item = hashtable->items[pos];
hashtable->items[pos] = item;
/* statistics */
hashtable->stats.cuckoo_moved++;
/* take care of new lost item */
item = backup_item;
/* we just kicked this item from its position 1 */
if (pos == coucal_hash_to_pos(hashtable, item.hashes.hash1)) {
/* then place it on position 2 on next run */
coucal_trace(hashtable, "\tdebug:position 1");
cuckoo_hash = item.hashes.hash2;
}
/* we just kicked this item from its position 2 */
else if (pos == coucal_hash_to_pos(hashtable, item.hashes.hash2)) {
/* then place it on position 1 on next run */
coucal_trace(hashtable, "\tdebug:position 2");
cuckoo_hash = item.hashes.hash1;
}
else {
coucal_assert(hashtable, ! "hashtable internal error: unexpected position");
}
/* we are looping (back to same hash) */
/* TODO FIXME: we should actually check the positions */
if (cuckoo_hash == initial_cuckoo_hash) {
/* emergency stash */
break;
}
}
}
/* emergency stashing for the rare cases of collisions */
if (hashtable->stash.size < STASH_SIZE) {
hashtable->stash.items[hashtable->stash.size] = item;
hashtable->stash.size++;
/* for statistics */
hashtable->stats.stash_added++;
if (hashtable->stash.size > hashtable->stats.max_stash_size) {
hashtable->stats.max_stash_size = hashtable->stash.size;
}
coucal_debug(hashtable, "used stash because of collision (%d entries)",
(int) hashtable->stash.size);
return 1; /* added */
} else {
/* debugging */
if (hashtable->custom.print.key != NULL
&& hashtable->custom.print.value != NULL) {
size_t i;
for(i = 0 ; i < hashtable->stash.size ; i++) {
coucal_item *const item = &hashtable->stash.items[i];
const size_t pos1 = coucal_hash_to_pos(hashtable, item->hashes.hash1);
const size_t pos2 = coucal_hash_to_pos(hashtable, item->hashes.hash2);
coucal_crit(hashtable,
"stash[%u]: key='%s' value='%s' pos1=%d pos2=%d hash1=%04x hash2=%04x",
(int) i,
hashtable->custom.print.key(hashtable->custom.print.arg, item->name),
hashtable->custom.print.value(hashtable->custom.print.arg, item->value),
(int) pos1, (int) pos2,
item->hashes.hash1, item->hashes.hash2);
if (!coucal_is_free(hashtable, pos1)) {
coucal_item *const item = &hashtable->items[pos1];
const size_t pos1 = coucal_hash_to_pos(hashtable, item->hashes.hash1);
const size_t pos2 = coucal_hash_to_pos(hashtable, item->hashes.hash2);
coucal_crit(hashtable,
"\t.. collisionning with key='%s' value='%s' pos1=%d pos2=%d hash1=%04x hash2=%04x",
hashtable->custom.print.key(hashtable->custom.print.arg, item->name),
hashtable->custom.print.value(hashtable->custom.print.arg, item->value),
(int) pos1, (int) pos2,
item->hashes.hash1, item->hashes.hash2);