-
Notifications
You must be signed in to change notification settings - Fork 9
/
minialign.c
6484 lines (5845 loc) · 196 KB
/
minialign.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
/**
* @file minialign.c
*
* @brief minialign core implementation
*
* @author Hajime Suzuki (original files by Heng Li)
* @license MIT
*/
/* configurations */
/**
* @macro MM_VERSION
*/
#ifndef MM_VERSION
# define MM_VERSION "minialign-0.6.0-devel"
#endif
/**
* @macro MAX_THREADS
* @brief max #threads, set larger value if needed
*/
#define MAX_THREADS ( 128 )
/**
* @macro MAX_FRQ_CNT
* @brief max #frq in seed filtering
*/
#define MAX_FRQ_CNT ( 7 )
/**
* @macro UNITTEST
* @brief set zero to disable unittests
*/
#ifndef UNITTEST
# define UNITTEST ( 1 )
#endif
/* make sure POSIX APIs are properly activated */
#if defined(__linux__) && !defined(_POSIX_C_SOURCE)
# define _POSIX_C_SOURCE 200112L
#endif
#if defined(__darwin__) && !defined(_DARWIN_C_FULL)
# define _DARWIN_C_SOURCE _DARWIN_C_FULL
#endif
#include <math.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
/* utils.h */
/* max, min, roundup */
#define MAX2(x,y) ( (x) > (y) ? (x) : (y) )
#define MIN2(x,y) ( (x) < (y) ? (x) : (y) )
#define _roundup(x, base) ( ((x) + (base) - 1) & ~((base) - 1) )
/* _likely, _unlikely */
#define _likely(x) __builtin_expect(!!(x), 1)
#define _unlikely(x) __builtin_expect(!!(x), 0)
/* _force_inline */
#define _force_inline inline
/* add namespace */
#ifndef _export
# ifdef NAMESPACE
# define _export_cat(x, y) x##_##y
# define _export_cat2(x, y) _export_cat(x, y)
# define _export(_base) _export_cat2(_base, NAMESPACE)
# else
# define _export(_base) _base
# endif
#endif
/* utils.h */
#include "sassert.h"
#include "log.h"
/* mm_malloc.c: malloc wrappers */
/**
* @fn oom_abort
* @brief called when malloc / realloc failed. dump thread information and exit (noreturn).
*/
static
void oom_abort(
char const *name,
size_t req)
{
struct rusage r;
getrusage(RUSAGE_SELF, &r);
fprintf(stderr, "[E::%s] Out of memory. (required: %zu MB, maxrss: %ld MB)\n", name, req / 1024, r.ru_maxrss);
*((volatile uint8_t *)NULL);
trap(); /* segv trap for debugging; see log.h */
exit(128); /* 128 reserved for out of memory */
}
/**
* @macro mm_malloc
*/
#define mm_malloc(_x) ({ \
void *_ptr = malloc((size_t)(_x)); \
if(_unlikely(_ptr == NULL)) { \
oom_abort(__func__, (_x)); \
} \
_ptr; \
})
#define mm_new(type_t, _content) ({ \
type_t *_ptr = mm_malloc(sizeof(type_t)); \
*_ptr = (type_t)_content; \
_ptr; \
})
#define malloc(_x) mm_malloc(_x)
/**
* @macro mm_realloc
*/
#define mm_realloc(_x, _y) ({ \
void *_ptr = realloc((void *)(_x), (size_t)(_y)); \
if(_unlikely(_ptr == NULL)) { \
oom_abort(__func__, (_y)); \
} \
_ptr; \
})
#define realloc(_x, _y) mm_realloc(_x, _y)
/**
* @macro mm_calloc
*/
#define mm_calloc(_x, _y) ({ \
void *_ptr = calloc((size_t)(_x), (size_t)(_y)); \
if(_unlikely(_ptr == NULL)) { \
oom_abort(__func__, (_y)); \
} \
_ptr; \
})
#define calloc(_x, _y) mm_calloc(_x, _y)
/* end of mm_malloc.c */
/* miscellaneous macros and types */
#define UNITTEST_UNIQUE_ID 1
#include "unittest.h"
#include "lmm.h"
#define BIT 2 /* 2-bit encoded */
#ifdef GABA_NOWRAP
# include "gaba.h"
#else
# include "gaba_wrap.h"
#endif
#include "gaba_parse.h"
#include "arch/arch.h"
#include "kvec.h"
unittest_config( .name = "minialign" );
unittest( .name = "mm_malloc" ) {
uint64_t const size = 1024 * 1024 * 1024;
uint8_t *p = malloc(size);
assert(p != NULL);
memset(p, 0, size); /* make sure we can touch this area */
p = realloc(p, 2*size);
assert(p != NULL);
p = realloc(p, size/2);
assert(p != NULL);
free(p);
}
/* end of unittest */
typedef union {
uint64_t u64[1];
uint32_t u32[2];
} v2u32_t;
_static_assert(sizeof(v2u32_t) == 8);
typedef union {
uint64_t u64[2];
uint32_t u32[4];
} v4u32_t;
_static_assert(sizeof(v4u32_t) == 16);
typedef struct { size_t n, m; v4u32_t *a; } v4u32_v;
typedef struct { size_t n, m; v2u32_t *a; } v2u32_v;
typedef struct { size_t n, m; uint64_t *a; } uint64_v;
typedef struct { size_t n, m; uint32_t *a; } uint32_v;
typedef struct { size_t n, m; uint16_t *a; } uint16_v;
typedef struct { size_t n, m; uint8_t *a; } uint8_v;
typedef struct { size_t n, m; void **a; } ptr_v;
#include "ksort.h"
#define sort_key_128x(a) ( (a).u64[0] )
KRADIX_SORT_INIT(128x, v4u32_t, sort_key_128x, 8)
#define sort_key_64x(a) ( (a).u32[0] )
KRADIX_SORT_INIT(64x, v2u32_t, sort_key_64x, 4)
KSORT_INIT_GENERIC(uint32_t)
/**
* sequence encoding table
* "NTGKCYSBAWRDMHVN"
* "NACMGRSVTWYHKDBN"
*/
enum alphabet {
A = 0x00,
C = 0x01,
G = 0x02,
T = 0x03,
N = 0x04
};
static uint8_t const enc4f[16] = { [1] = A, [2] = C, [4] = G, [8] = T };
static uint8_t const enc4r[16] = { [1] = T, [2] = G, [4] = C, [8] = A };
static uint8_t const encaf[16] = {
['A' & 0x0f] = A, ['C' & 0x0f] = C,
['G' & 0x0f] = G, ['T' & 0x0f] = T,
['U' & 0x0f] = T, ['N' & 0x0f] = N
};
// #define _encaf(_c) ( 0x03 & (((_c)>>1) - ((_c)>>3)) )
#define _encaf(_c) ( 0x03 & (((_c)>>2) ^ ((_c)>>1)) )
static uint8_t const decaf[16] = { [A] = 'A', [C] = 'C', [G] = 'G', [T] = 'T', [N] = 'N' };
static uint8_t const decar[16] = { [A] = 'T', [C] = 'G', [G] = 'C', [T] = 'A', [N] = 'N' };
static uint8_t const idxaf[256] = { ['A'] = 1, ['C'] = 2, ['G'] = 3, ['T'] = 4, ['U'] = 4, ['N'] = 5 };
/**
* @macro mm_encode_tag
* @brief map SAM tag string to 16-bit int
*/
#define mm_encode_tag(_p) ( (uint16_t)(_p)[0] | ((uint16_t)(_p)[1]<<8) )
/**
* @type read_t, write_t
* @brief abstract I/O function types
*/
typedef uint64_t (*read_t)(void *fp, void *buf, uint64_t size);
typedef uint64_t (*write_t)(void *fp, void const *buf, uint64_t size);
/* time functions */
static _force_inline
double cputime(void)
{
struct rusage r;
getrusage(RUSAGE_SELF, &r);
return(
r.ru_utime.tv_sec
+ r.ru_stime.tv_sec
+ 1e-6 * (r.ru_utime.tv_usec + r.ru_stime.tv_usec)
);
}
static _force_inline
double realtime(void)
{
struct timeval tp;
gettimeofday(&tp, NULL);
return(tp.tv_sec + tp.tv_usec * 1e-6);
}
/* random */
static _force_inline
uint64_t mm_rand64(void)
{
uint64_t bits = 31, n = 0;
for(uint64_t acc = 0; acc < 64; acc += bits) {
n <<= bits; n ^= (uint64_t)rand();
}
return n;
}
/* string handling */
static _force_inline
char *mm_strndup(char const *p, uint64_t l)
{
if(!p) { return(NULL); }
char *q = malloc(sizeof(char) * (l + 1));
memcpy(q, p, l); q[l] = '\0';
return(q);
}
static _force_inline
char *mm_strdup(char const *p)
{
if(!p) { return(NULL); }
kvec_t(char) b = { 0 };
do { kv_push(char, b, *p); } while(*p++);
return(b.a);
}
static _force_inline
char *mm_join(char const *const *p, char c)
{
kvec_t(char) b = { 0 };
do {
char const *q = *p;
do { kv_push(char, b, *q); } while(*q++);
} while(*++p && (b.a[b.n - 1] = c, 1));
return(b.a);
}
static _force_inline
int mm_startswith(char const *p, char const *prf)
{
uint64_t l = strlen(p), r = strlen(prf);
return(l >= r && strncmp(p, prf, r) == 0);
}
static _force_inline
int mm_endswith(char const *p, char const *suf)
{
uint64_t l = strlen(p), r = strlen(suf);
return(l >= r && strncmp(p + l - r, suf, r) == 0);
}
static _force_inline
char *mm_append(char *p, char const *suf)
{
uint64_t l = strlen(p), r = strlen(suf);
p = realloc(p, sizeof(char) * (l + r + 1));
memcpy(p + l, suf, r); p[l + r] = '\0';
return(p);
}
static _force_inline
uint64_t mm_shashn(char const *p, uint64_t l)
{
uint64_t a = 0x12345678;
while(*p && l) { a = (a<<5) ^ (a>>3) ^ *p++; l--; }
return(a);
}
static _force_inline
char const *mm_version(void)
{
char const *prefix = "minialign-";
uint64_t spos = mm_startswith(MM_VERSION, prefix) ? strlen(prefix) : 0; /* match to remove prefix */
return(&MM_VERSION[spos]);
}
/* end of miscellaneous section */
/* hash.c */
/**
* @struct kh_s
* @brief 64-bit key 64-bit value Robinhood hash table
*/
typedef struct kh_s {
uint32_t mask, max, cnt, ub; /* size of the array, element count, upper bound */
v4u32_t *a;
} kh_t;
_static_assert(sizeof(kh_t) == 24);
#define KH_SIZE ( 256 ) /* initial table size */
#define KH_THRESH ( 0.4 ) /* max occupancy */
#define KH_DST_MAX ( 16 ) /* max distance from base pos */
#define KH_INIT_VAL ( UINT64_MAX ) /* initial vals */
#define kh_ptr(h) ( (h)->a )
#define kh_size(h) ( (h)->mask + 1 )
#define kh_cnt(h) ( (h)->cnt )
#define kh_exist(h, i) ( (h)->a[i].u64[0] + 2 >= 2 )
#define kh_key(p) ( (p)->u64[0] )
#define kh_val(p) ( (p)->u64[1] )
/**
* @fn kh_init
* @brief initialize hash with *size* table
*/
static _force_inline
void kh_init_static(kh_t *h, uint64_t size)
{
/* roundup to power of two */
size = 0x8000000000000000>>(lzcnt(size - 1) - 1);
size = MAX2(size, KH_SIZE);
/* initialize kh object */
*h = (kh_t){
.mask = size - 1, /* in-use table size */
.max = size, /* malloc'd table size */
.cnt = 0,
.ub = size * KH_THRESH,
.a = malloc(sizeof(v4u32_t) * size)
};
/* init table with invalid key-val pairs */
for(uint64_t i = 0; i < size; i++) {
h->a[i].u64[0] = UINT64_MAX;
h->a[i].u64[1] = KH_INIT_VAL;
}
return;
}
#define kh_init(_size) ({ kh_t *h = calloc(1, sizeof(kh_t)); kh_init_static(h, _size); h; })
/**
* @fn kh_destroy
*/
static _force_inline
void kh_destroy(kh_t *h)
{
if(h == NULL) { return; }
free(h->a);
free(h);
return;
}
#define kh_destroy_static(_h) { free(((kh_t *)_h)->a); }
/**
* @struct kh_hdr_t
*/
typedef struct kh_hdr_s {
uint32_t size, cnt;
} kh_hdr_t;
_static_assert(sizeof(kh_hdr_t) == 8);
/**
* @fn kh_dump
* @brief binary serializer, fp is an opaque pointer passed to the first argument of wfp
*/
static _force_inline
void kh_dump(kh_t const *h, void *fp, write_t wfp)
{
kh_hdr_t hdr = { 0 };
/* dump a mark of zero-sized table */
if(h == NULL || h->a == NULL) {
wfp(fp, &hdr, sizeof(kh_hdr_t));
return;
}
/* dump size */
hdr = (kh_hdr_t){
.size = h->mask + 1, /* table size */
.cnt = h->cnt /* occupancy */
};
wfp(fp, &hdr, sizeof(kh_hdr_t));
/* dump table */
wfp(fp, h->a, sizeof(v4u32_t) * hdr.size);
return;
}
/**
* @fn kh_load_static
* @brief binary deserializer, fp is an opaque pointer
*/
static _force_inline
void kh_load_static(kh_t *h, void *fp, read_t rfp)
{
kh_hdr_t hdr = { 0 };
/* read sizes, return NULL if table size is zero */
if((rfp(fp, &hdr, sizeof(kh_hdr_t))) != sizeof(kh_hdr_t) || hdr.size == 0) {
*h = (kh_t){ 0 };
return;
}
/* create hash object */
*h = (kh_t){
.mask = hdr.size - 1, /* in-use table size */
.max = hdr.size, /* malloc'd table size */
.cnt = hdr.cnt,
.ub = hdr.size * KH_THRESH,
.a = malloc(sizeof(v4u32_t) * hdr.size)
};
/* read table */
if((rfp(fp, h->a, sizeof(v4u32_t) * hdr.size)) != sizeof(v4u32_t) * hdr.size) {
free(h->a);
free(h);
return;
}
return;
}
#define kh_load(_fp, _rfp) ({ kh_t *h = calloc(1, sizeof(kh_t)); kh_load_static(h, _fp, _rfp); h; })
/**
* @fn kh_clear
* @brief flush the content of the hash table
*/
static _force_inline
void kh_clear(kh_t *h)
{
if(h == 0) { return; }
/* don't clear max since it holds the malloc'd table size */
h->mask = KH_SIZE - 1;
h->cnt = 0;
h->ub = KH_SIZE * KH_THRESH;
for(uint64_t i = 0; i < KH_SIZE; i++) {
h->a[i].u64[0] = UINT64_MAX;
h->a[i].u64[1] = KH_INIT_VAL;
}
return;
}
/**
* @fn kh_allocate
* @brief allocate a bucket for key, returns the index of allocated bucket.
*/
typedef struct { uint64_t idx, n; } kh_bidx_t;
static _force_inline
kh_bidx_t kh_allocate(v4u32_t *a, uint64_t k, uint64_t v, uint64_t mask)
{
#define _poll_bucket(_i, _b0) ({ \
int64_t _b = (_b0); \
uint64_t _k1; \
while(1) { \
/* test: is_empty(kt) || is_moved(kt) */ \
_k1 = a[_i].u64[0]; \
if(_b <= (int64_t)(_k1 & mask) + (_k1 + 2 < 2)) { break; } \
_b -= (_i + 1) & (mask + 1); \
_i = (_i + 1) & mask; \
} \
_k1; /* return key */ \
})
uint64_t i = k & mask, k0 = k, v0 = v;
uint64_t k1 = _poll_bucket(i, i); /* search first bucket */
if(k0 == k1) { return((kh_bidx_t){ i, 0 }); } /* duplicated key */
uint64_t j = i;
a[i].u64[0] = k0; /* update key */
while(k1 + 2 >= 2) {
uint64_t v1 = a[i].u64[1]; /* load for swap */
a[i].u64[1] = v0; /* save previous value */
k0 = k1; v0 = v1; /* robinhood swap */
i = (i + 1) & mask; /* advance index */
k1 = _poll_bucket(i, k0 & mask); /* search next bucket */
a[i].u64[0] = k0; /* update key */
}
a[i].u64[1] = v0; /* save previous value */
return((kh_bidx_t){ j, 1 });
#undef _poll_bucket
}
/**
* @fn kh_extend
* @brief extend hash table
*/
static _force_inline
void kh_extend(kh_t *h)
{
uint64_t prev_size = h->mask + 1, size = 2 * prev_size, mask = size - 1;
debug("kh_extend called, new_size(%lx), cnt(%u), ub(%u)", size, h->cnt, h->ub);
/* update size */
h->mask = mask;
h->ub = size * KH_THRESH;
/* double the table if needed */
if(size > h->max) {
h->a = realloc(h->a, sizeof(v4u32_t) * size);
h->max = size;
}
/* clear the extended area */
for(uint64_t i = 0; i < prev_size; i++) {
h->a[i + prev_size].u64[0] = UINT64_MAX;
h->a[i + prev_size].u64[1] = KH_INIT_VAL;
}
/* reallocate bins */
for(uint64_t i = 0; i < size; i++) {
uint64_t k = h->a[i].u64[0]; /* load key */
/* test if reallocate is required */
if(k + 2 < 2 || (k & mask) == i) { continue; }
uint64_t v = h->a[i].u64[1]; /* load val */
h->a[i] = (v4u32_t){ /* mark the current bin moved */
.u64 = { UINT64_MAX-1, KH_INIT_VAL }
};
kh_allocate(h->a, k, v, mask);
}
return;
}
/**
* @fn kh_put
*/
static _force_inline
void kh_put(kh_t *h, uint64_t key, uint64_t val)
{
if(h->cnt >= h->ub) {
debug("trigger extend, cnt(%u), ub(%u)", h->cnt, h->ub);
kh_extend(h);
}
kh_bidx_t b = kh_allocate(h->a, key, val, h->mask);
h->cnt += b.n;
// h->ub = ((b.idx - key) & h->mask) > KH_DST_MAX ? 0 : h->ub;
h->a[b.idx] = (v4u32_t){
.u64 = { key, val }
};
return;
}
/**
* @fn kh_put_ptr
*/
static _force_inline
uint64_t *kh_put_ptr(kh_t *h, uint64_t key, uint64_t extend)
{
if(extend != 0 && h->cnt >= h->ub) { kh_extend(h); }
kh_bidx_t b = kh_allocate(h->a, key, KH_INIT_VAL, h->mask);
debug("allocated hash bin (%lu, %lu), (%lx, %lx), dst(%ld)", b.idx, b.n, h->a[b.idx].u64[0], h->a[b.idx].u64[1], (b.idx - key) & h->mask);
h->cnt += b.n;
// h->ub = ((b.idx - key) & h->mask) > KH_DST_MAX ? 0 : h->ub;
return(&h->a[b.idx].u64[1]);
}
/**
* @fn kh_get
* @brief returns val or UINT64_MAX if not found
*/
static _force_inline
uint64_t kh_get(kh_t const *h, uint64_t key)
{
uint64_t mask = h->mask, pos = key & mask, k;
do {
if((k = h->a[pos].u64[0]) == key) { return(h->a[pos].u64[1]); }
pos = mask & (pos + 1);
} while(k + 1 != 0); /* !is_empty(k) || is_moved(k) */
return(UINT64_MAX);
}
/**
* @fn kh_get_ptr
* @brief returns pointer to val or NULL if not found
*/
static _force_inline
uint64_t *kh_get_ptr(kh_t const *h, uint64_t key)
{
uint64_t mask = h->mask, pos = key & mask, k;
do {
if((k = h->a[pos].u64[0]) == key) { return(&h->a[pos].u64[1]); }
pos = mask & (pos + 1);
} while(k + 1 != 0); /* !is_empty(k) || is_moved(k) */
return(NULL);
}
/**
* @struct kh_str_t
* @brief string -> string hashmap
*/
typedef struct {
uint8_v s;
kh_t h;
} kh_str_t;
#define kh_str_ptr(_h) ( kh_ptr(&(_h)->h) )
#define kh_str_cnt(_h) ( kh_cnt(&(_h)->h) )
#define kh_str_init_static(_h, _size) { (_h)->s = (uint8_v){ 0 }; kh_init_static(&(_h)->h, _size); }
#define kh_str_init(_size) ({ kh_str_t *h = calloc(1, sizeof(kh_str_t)); kh_init_static(h, _size); h; })
#define kh_str_destroy_static(_h) { kh_destroy_static(&((kh_str_t *)_h)->h); free(((kh_str_t *)_h)->s.a); }
#define kh_str_destroy(_h) { kh_str_destroy_static(_h); free(_h); }
#define kh_str_clear(_h) { kh_clear(&((kh_str_t *)_h)->h); }
/**
* @fn kh_str_put, kh_str_get
*/
static _force_inline
void kh_str_put(kh_str_t *h, char const *k, uint64_t klen, char const *v, uint64_t vlen)
{
if(klen == UINT64_MAX) { klen = strlen(k); }
if(vlen == UINT64_MAX) { vlen = strlen(v); }
kh_put(&h->h, mm_shashn(k, klen), (kv_size(h->s)<<32) | klen);
kv_pushm(uint8_t, h->s, k, klen);
kv_push(uint8_t, h->s, '\0');
kv_pushm(uint8_t, h->s, v, vlen);
kv_push(uint8_t, h->s, '\0');
return;
}
static _force_inline
char const *kh_str_get(kh_str_t const *h, char const *k, uint64_t klen)
{
if(klen == UINT64_MAX) { klen = strlen(k); }
uint64_t const *p = kh_get_ptr(&h->h, mm_shashn(k, klen));
if(p == NULL || (uint32_t)(*p) != klen) { return(0); } /* not found or length differs */
char const *q = (char const *)&h->s.a[*p>>32];
return(strncmp(q, k, klen) == 0 ? q + klen + 1 : NULL);
}
unittest( .name = "kh.base" ) {
kh_t *h = kh_init(0);
assert(h != NULL);
uint64_t const kmask = mm_rand64(), vmask = mm_rand64(), cnt = 1024 * 1024;
uint64_t const *p;
assert(kh_cnt(h) == 0, "cnt(%lu)", kh_cnt(h));
for(uint64_t i = 0; i < 2*cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p == NULL);
assert(kh_get(h, i^kmask) == UINT64_MAX);
}
/* put key-val pairs */
for(uint64_t i = 0; i < cnt; i++) kh_put(h, i^kmask, i^vmask);
assert(kh_cnt(h) == cnt, "cnt(%lu)", kh_cnt(h));
for(uint64_t i = 0; i < cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p != NULL, "i(%lu)", i);
assert(*p == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
assert(kh_get(h, i^kmask) == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
}
for(uint64_t i = cnt; i < 2*cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p == NULL);
assert(kh_get(h, i^kmask) == UINT64_MAX);
}
/* clear */
kh_clear(h);
assert(kh_cnt(h) == 0, "cnt(%lu)", kh_cnt(h));
for(uint64_t i = 0; i < cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p == NULL);
assert(kh_get(h, i^kmask) == UINT64_MAX);
}
/* add another set of key-val pairs */
for(uint64_t i = cnt; i < 2*cnt; i++) kh_put(h, i^kmask, i^vmask);
assert(kh_cnt(h) == cnt, "cnt(%lu)", kh_cnt(h));
for(uint64_t i = 0; i < cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p == NULL);
assert(kh_get(h, i^kmask) == UINT64_MAX);
}
for(uint64_t i = cnt; i < 2*cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p != NULL, "i(%lu)", i);
assert(*p == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
assert(kh_get(h, i^kmask) == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
}
kh_destroy(h);
}
unittest( .name = "kh.io" ) {
kh_t *h = kh_init(0);
uint64_t const kmask = mm_rand64(), vmask = mm_rand64(), cnt = 1024 * 1024;
for(uint64_t i = 0; i < cnt; i++) kh_put(h, i^kmask, i^vmask);
/* dump */
char const *filename = "./minialign.unittest.kh.tmp";
gzFile fp = gzopen(filename, "w");
assert((void *)fp != NULL);
kh_dump(h, (void *)fp, (write_t)gzwrite);
gzclose(fp);
kh_destroy(h);
/* restore */
fp = gzopen(filename, "r");
assert((void *)fp != NULL);
h = kh_load((void *)fp, (read_t)gzread);
assert(h != NULL);
gzclose(fp);
uint64_t const *p;
assert(kh_cnt(h) == cnt, "cnt(%lu)", kh_cnt(h));
for(uint64_t i = 0; i < cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p != NULL, "i(%lu)", i);
assert(*p == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
assert(kh_get(h, i^kmask) == (i^vmask), "i(%lu), val(%lu, %lu)", i, *p, (i^vmask));
}
for(uint64_t i = cnt; i < 2*cnt; i++) {
p = kh_get_ptr(h, i^kmask);
assert(p == NULL);
assert(kh_get(h, i^kmask) == UINT64_MAX);
}
kh_destroy(h);
remove(filename);
}
/* end of hash.c */
/* queue.c */
/**
* @type pt_source_t, pt_worker_t, pt_drain_t
* @brief callback functions types for multithreaded stream
*/
typedef void *(*pt_source_t)(uint32_t tid, void *arg);
typedef void *(*pt_worker_t)(uint32_t tid, void *arg, void *item);
typedef void (*pt_drain_t)(uint32_t tid, void *arg, void *item);
/**
* @struct pt_q_s
* @brief lock-based queue context
*/
typedef struct pt_q_s {
uint64_t lock, head, tail, size;
void **elems;
uint64_t wait_cnt;
uint64_t _pad1[2];
} pt_q_t;
_static_assert(sizeof(pt_q_t) == 64); /* to occupy a single cache line */
/**
* @struct pt_thread_s
* @brief thread-local worker context
*/
typedef struct pt_thread_s {
pthread_t th;
uint64_t tid, wait_cnt;
pt_q_t *in, *out;
volatile pt_worker_t wfp;
volatile void *warg;
} pt_thread_t;
/**
* @struct pt_s
* @brief parallel task processor context
*/
typedef struct pt_s {
pt_q_t in, out;
uint32_t nth;
pt_thread_t c[]; /* [0] is reserved for master */
} pt_t;
#define pt_nth(_pt) ( (_pt)->nth )
#define PT_EMPTY ( (void *)(UINT64_MAX) )
#define PT_EXIT ( (void *)(UINT64_MAX - 1) )
#define PT_DEFAULT_INTERVAL ( 512 * 1024 )
/**
* @fn pt_enq
* @brief enqueue; concurrent queue is better while currently lock-based for simplicity
*/
static _force_inline
uint64_t pt_enq(pt_q_t *q, uint64_t tid, void *elem)
{
uint64_t z, ret = UINT64_MAX;
/* lock by thread id */
do { z = UINT32_MAX; } while(!cas(&q->lock, &z, tid));
/* push element to queue */
uint64_t head = q->head, tail = q->tail, size = q->size;
if(((head + 1) % size) != tail) {
q->elems[head] = elem;
q->head = (head + 1) % size;
ret = 0;
}
/* release */
do { z = tid; } while(!cas(&q->lock, &z, UINT32_MAX));
return(ret);
}
static _force_inline
uint64_t pt_enq_retry(pt_q_t *q, uint64_t tid, void *elem, uint64_t nsec)
{
struct timespec tv = { .tv_nsec = nsec };
while(pt_enq(q, tid, elem) != 0) { q->wait_cnt++; nanosleep(&tv, NULL); }
return(0);
}
/**
* @fn pt_deq
*/
static _force_inline
void *pt_deq(pt_q_t *q, uint64_t tid)
{
void *elem = PT_EMPTY;
uint64_t z;
/* lock by thread id */
do { z = UINT32_MAX; } while(!cas(&q->lock, &z, tid));
/* get element from queue */
uint64_t head = q->head, tail = q->tail, size = q->size;
if(head != tail) {
elem = q->elems[tail]; q->tail = (tail + 1) % size;
}
/* release */
do { z = tid; } while(!cas(&q->lock, &z, UINT32_MAX));
return(elem);
}
/**
* @fn pt_dispatch
* @brief per-thread function dispatcher, with ping-pong prefetching
*/
static _force_inline
void *pt_dispatch(void *s)
{
pt_thread_t *c = (pt_thread_t *)s;
uint64_t const intv = PT_DEFAULT_INTERVAL;
struct timespec tv = { .tv_nsec = intv };
void *ping = PT_EMPTY, *pong = PT_EMPTY;
while(1) {
ping = pt_deq(c->in, c->tid); /* prefetch */
if(ping == PT_EMPTY && pong == PT_EMPTY) {
c->wait_cnt++; nanosleep(&tv, NULL); /* no task is available, sleep for a while */
}
if(pong != PT_EMPTY) {
pt_enq_retry(c->out, c->tid, c->wfp(c->tid, (void *)c->warg, pong), intv);
}
if(ping == PT_EXIT) { break; } /* terminate thread */
pong = pt_deq(c->in, c->tid); /* prefetch */
if(ping == PT_EMPTY && pong == PT_EMPTY) {
c->wait_cnt++; nanosleep(&tv, NULL); /* no task is available, sleep for a while */
}
if(ping != PT_EMPTY) {
pt_enq_retry(c->out, c->tid, c->wfp(c->tid, (void *)c->warg, ping), intv);
}
if(pong == PT_EXIT) { break; } /* terminate thread */
}
return(NULL);
}
/**
* @fn pt_destroy
*/
static _force_inline
void pt_destroy(pt_t *pt)
{
void *status;
if(pt == NULL) { return; }
/* send termination signal */
for(uint64_t i = 1; i < pt->nth; i++) {
pt_enq_retry(pt->c->in, pt->c->tid, PT_EXIT, PT_DEFAULT_INTERVAL);
}
/* wait for the threads terminate */
for(uint64_t i = 1; i < pt->nth; i++) { pthread_join(pt->c[i].th, &status); }
/* clear queues */
while(pt_deq(pt->c->in, pt->c->tid) != PT_EMPTY) {}
while(pt_deq(pt->c->out, pt->c->tid) != PT_EMPTY) {}
/* clear queues and objects */
free(pt->in.elems);
free(pt->out.elems);
free(pt);
return;
}
/**
* @fn pt_init
*/
static _force_inline
pt_t *pt_init(uint32_t nth)
{
/* init object */
nth = (nth == 0)? 1 : nth;
pt_t *pt = calloc(nth, sizeof(pt_t) + sizeof(pt_thread_t));
/* init queues (note: #elems can be larger for better performance?) */
uint64_t const size = 16 * nth;
pt->in = (pt_q_t){
.lock = UINT32_MAX,
.elems = calloc(size, sizeof(void *)),
.size = size
};
pt->out = (pt_q_t){
.lock = UINT32_MAX,
.elems = calloc(size, sizeof(void *)),
.size = size
};
/* init parent thread info */
pt->nth = nth; pt->c[0].tid = 0;
pt->c[0].in = &pt->in;
pt->c[0].out = &pt->out;
/* init children info, create children */
for(uint64_t i = 1; i < nth; i++) {
pt->c[i].tid = i;
pt->c[i].in = &pt->in;
pt->c[i].out = &pt->out;
pthread_create(&pt->c[i].th, NULL, pt_dispatch, (void *)&pt->c[i]);
}
return(pt);
}
/**
* @fn pt_set_worker
* @brief update worker function and argument pointers
*/
static _force_inline
int pt_set_worker(pt_t *pt, void *arg, pt_worker_t wfp)
{
void *item;
/* fails when unprocessed object exists in the queue */
if((item = pt_deq(&pt->in, 0)) != PT_EMPTY) {
pt_enq_retry(&pt->in, 0, item, PT_DEFAULT_INTERVAL);
return(-1);
}
/* update pointers */
for(uint64_t i = 0; i < pt->nth; i++) {
pt->c[i].wfp = wfp; pt->c[i].warg = arg;