-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.h
1117 lines (1012 loc) · 39.5 KB
/
utils.h
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
#ifndef UTIL_H
#define UTIL_H 1
/**
* Author: Melkor-1
* Date: Friday, June 7, 2024
*
* Declares utility constants, macros, and functions. */
#include <complex.h>
#include <inttypes.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#define CHARIFY_0 '0'
#define CHARIFY_1 '1'
#define CHARIFY_2 '2'
#define CHARIFY_3 '3'
#define CHARIFY_4 '4'
#define CHARIFY_5 '5'
#define CHARIFY_6 '6'
#define CHARIFY_7 '7'
#define CHARIFY_8 '8'
#define CHARIFY_9 '9'
#define CHARIFY_A 'A'
#define CHARIFY_B 'B'
#define CHARIFY_C 'C'
#define CHARIFY_D 'D'
#define CHARIFY_E 'E'
#define CHARIFY_F 'F'
#define CHARIFY_G 'G'
#define CHARIFY_H 'H'
#define CHARIFY_I 'I'
#define CHARIFY_J 'J'
#define CHARIFY_K 'K'
#define CHARIFY_L 'L'
#define CHARIFY_M 'M'
#define CHARIFY_N 'N'
#define CHARIFY_O 'O'
#define CHARIFY_P 'P'
#define CHARIFY_Q 'Q'
#define CHARIFY_R 'R'
#define CHARIFY_S 'S'
#define CHARIFY_T 'T'
#define CHARIFY_U 'U'
#define CHARIFY_V 'V'
#define CHARIFY_W 'W'
#define CHARIFY_X 'X'
#define CHARIFY_Y 'Y'
#define CHARIFY_Z 'Z'
#define CHARIFY__ '_'
#define CHARIFY_a 'a'
#define CHARIFY_b 'b'
#define CHARIFY_c 'c'
#define CHARIFY_d 'd'
#define CHARIFY_e 'e'
#define CHARIFY_f 'f'
#define CHARIFY_g 'g'
#define CHARIFY_h 'h'
#define CHARIFY_i 'i'
#define CHARIFY_j 'j'
#define CHARIFY_k 'k'
#define CHARIFY_l 'l'
#define CHARIFY_m 'm'
#define CHARIFY_n 'n'
#define CHARIFY_o 'o'
#define CHARIFY_p 'p'
#define CHARIFY_q 'q'
#define CHARIFY_r 'r'
#define CHARIFY_s 's'
#define CHARIFY_t 't'
#define CHARIFY_u 'u'
#define CHARIFY_v 'v'
#define CHARIFY_w 'w'
#define CHARIFY_x 'x'
#define CHARIFY_y 'y'
#define CHARIFY_z 'z'
#define CONCAT2_INDIRECT(A, B) A ## B
#define STRINGIFY_INDIRECT(A) #A
/**
* Concatenate A to B together to form a single token. */
#define CONCAT2(A, B) CONCAT2_INDIRECT(A, B)
/**
* Macro that "char-ifies" its argument, e.g., CHARIFY(x) becomes 'x'.
*
* X can only be in the set [0-9_A-Za-z]. */
#define CHARIFY(X) CONCAT2(CHARIFY_, X)
/**
* Macro that "string-ifies" its argument, e.g., STRINGIFY(x) becomes "x".
*
* X - The unquoted string to stringify. */
#define STRINGIFY(X) STRINGIFY_INDIRECT(X)
/**
* Synthesises a name prefixed by PREFIX unique to the line on which it is used.
*
* Notes:
* 1) All uses for a given PREFIX that refer to the same name must be on the same
* line. This is not a problem within macro definitions, but would not work
* outside of them since there is no way to refer to a previously used unique
* name. But if the intent is to have multiple "unique" names on a single line,
* the value of PREFIX must be different.
*
* 2) If UNIQUE_NAME is used within a macro and that macro does not expose
* PREFIX (but picks one), then using the macro twice on the same line
* (possibly nested, as in MAX(a, MAX(b, c)) ) will cause different
* variables to end up with the same unique names.
*
* This is generally useful in macros to avoid any conflict with existing
* identifiers, and also because having a unique name allows you to use the
* same macro multiple times in the same scope or nested scopes and avoid
* "shadows" warnings. */
#define UNIQUE_NAME(PREFIX) CONCAT2(CONCAT2(PREFIX, _), __LINE__)
/**
* C version of C++'s const_char.
*
* T - The type to cast to.
* EXPR - The expression to cast.
*
* Note: This macro can not actually implement C++'s const char because there
* is no way to do it in C. It merely serves as a visual cue for the type of
* cast meant. */
#define CONST_CAST(T, EXPR) ((T)(EXPR))
/**
* C version of C++'s static_cast.
*
* T - The type to cast to.
* EXPR - The expression to cast.
*
* Note: This macro can not actually implement C++'s static_cast because there
* is no way to do it in C. It serves merely as a visual cue for the type of
* cast meant. */
#define STATIC_CAST(T, EXPR) ((T)(EXPR))
/**
* Cast either from or to an integral type --- similar to C++'s
* reinterpret_cast, but for integers only.
*
* T - The type to cast to.
* EXPR - The expression to cast.
*
* Note: In C++, this would be done via reinterpret_cast, but it is not
* posible to implement that in C that works for both pointers and integers. */
#define INTEGER_CAST(T, EXPR) ((T)(uintmax_t)(EXPR))
/**
* Cast either from or to a pointer type --- similar to C++'s
* reinterpret_cast, but for pointers only.
*
* T - The type to cast to.
* EXPR - The expression to cast.
*
* Note: This macro silences a "cast to pointer from integer of different size"
* warning. In C++, this would be done via reinterpret_cast, but it is not
* possible to implement that in C that works for both pointers and integers. */
#define POINTER_CAST(T, EXPR) ((T)(uintptr_t)(EXPR))
/**
* Expands to 1 (true) if VAL is within the range of LO to HI (inclusive),
* else 0 (false).
*
* Note: RANGE() evaluates VAL_ more than once. */
#define RANGE(VAL, LO, HI) \
(((VAL) >= (LO)) && ((VAL) <= (HI)))
/**
* Expands to 1 (true) if VAL is within the range of LO to HI (exclusive),
* else 0 (false).
*
* Note: RANGE() evaluates VAL more than once. */
#define RANGEM1(VAL, LO, HI) \
(((VAL) >= (LO)) && ((VAL) < (HI)))
/**
* Embeds the given statements into a compound statement block. */
#define BLOCK(...) do { __VA_ARGS__ } while (false)
/**
* To enable debugging trace, define DEBUG. */
#ifdef DEBUG
#define TRACE_ON 1
#else
#define TRACE_ON 0
#endif
/**
* When debugging trace is enabled, TRACE() prints to stderr with the formatted
* message, source file name, line number, and function name.
*
* FMT - The printf() format string literal to use.
* ... - The printf() arguments. */
#define TRACE(FMT, ...) \
BLOCK( \
if (TRACE_ON) { \
/* "" provides rudimentary type-checking. */ \
fprintf(stderr, "%s::%d::%s():: " FMT "", __FILE__, \
__LINE__, __func__, __VA_OPT__(,) __VA_ARGS__); \
} \
)
/**
* Asserts that this line of code is run at most once --- useful in
* initialization functions that must be called at most once. For example:
*
* void initialize(void) {
* ASSERT_RUN_ONCE();
* // ...
* }
*
* Note: This implementation is not thread-safe. */
#ifndef NDEBUG
#define ASSERT_RUN_ONCE() \
BLOCK( \
static bool UNIQUE_NAME(called); \
assert(!UNIQUE_NAME(called)); \
UNIQUE_NAME(called) = true; \
)
#else
#define ASSERT_RUN_ONCE() (void)0
#endif /* NDEBUG */
/**
* Convenience macro for iterating N times. */
#define FOR_N_TIMES(N) \
for (size_t UNIQUE_NAME(i) = 0; \
UNIQUE_NAME(i) < STATIC_CAST(size_t, (N)); \
STATIC_ASSERT_EXPR(IS_INTEGRAL(N), #N " must be an integral type."), \
++UNIQUE_NAME(i))
/**
* Compile-time check of whether an expression is compatible with a type.
*
* EXPR - An expression. It is not evaluted.
* T - The type to check against.
*
* Note: Only an expression can be compared with a type. Two expressions or
* two type names can not be directly compared.
*
* To compare two types, a compound literal can be used to create a literal of
* a given type like so:
*
* IS_COMPATIBLE((size_t){0}, unsigned long);
*
* To test two variables for type compatibility, typeof can be used like so:
*
* IS_COMPATIBLE(x, typeof(y));
*
* Also note that this would not work for arrays, nor when one argument is a
* pointer and another an array.
*
* Returns to 1 (true) if EXPR is compatible with T, 0 (false) elsewise. */
#define IS_COMPATIBLE(EXPR, T) \
_Generic((EXPR), \
T : 1, \
default: 0 \
)
/**
* Compile-time check of whether T has type nullptr_t.
*
* T - An expression. It is not evaluted.
*
* Returns 1 (true) if T is the type nullptr_t, 0 (false) elsewise. */
#define IS_NULLPTR(T) \
_Generic((T), \
nullptr_t: 1, \
default : 0 \
)
/**
* Compile-time check of whether T has type FILE *.
*
* T - An expression. It is not evaluted.
*
* Returns 1 (true) if T is the type FILE *, 0 (false) elsewise. */
#define IS_FILE_PTR(T) \
_Generic((T), \
FILE * : 1, \
default: 0 \
)
/**
* Compile-time check of whether T is an array.
*
* T - An expression. It is not evaluted.
*
* Note: IS_ARRAY() distinguishes between arrays and pointers, not between
* arrays and arbitrary other types.
*
* Returns 1 (true) only if T is an array; 0 (false) elsewise.
*
* See also: https://stackoverflow.com/a/77881417/99089 */
#define IS_ARRAY(T) \
_Generic( &(T), \
typeof(*T) (*)[] : 1, \
default : 0 \
)
/**
* Compile-time check of whether A is a pointer.
*
* T - An expression. It is not evaluted.
*
* Note: IS_POINTER() distinguishes between arrays and pointers, not between
* pointers and arbitrary other types.
*
* Returns 1 (true) only if T is a pointer; 0 (false) elsewise.
*
* See also: https://stackoverflow.com/a/77881417/99089 */
#define IS_POINTER(T) !IS_ARRAY(T)
/**
* Implements a "static if" similar to "if constexpr" in C++.
*
* EXPR - An expression (evaluated at compile-time).
* THEN - An expression returned only if EXPR is non-zero (true).
* ELSE - An expression returned only if EXPR is zero (false).
*
* Returns:
* THEN only if EXPR is non-zero (true); or:
* ELSE only if EXPR is zero (false). */
#define STATIC_IF(EXPR, THEN, ELSE) \
_Generic( &(char[1 + !!(EXPR)]){0}, \
char (*)[2]: (THEN), \
char (*)[1]: (ELSE) \
)
/**
* Compile-time check of whether char is signed or unsigned.
*
* Returns 1 (true) if char is signed, else 0 (false). */
#define IS_CHAR_SIGNED STATIC_IF((char)-1 < 0, 1, 0)
/**
* Compile-time check of whether sig_atomic_t is signed or unsigned.
*
* Returns 1 (true) if sig_atomic_t is signed, else 0 (false). */
#define IS_SIG_ATOMIC_T_SIGNED STATIC_IF((sig_atomic_t)-1 < 0, 1, 0)
/**
* Compile-time check of whether wint_t is signed or unsigned.
*
* Returns 1 (true) if wint_t is signed, else 0 (false). */
#define IS_WINT_T_SIGNED STATIC_IF((wint_t)-1 < 0, 1, 0)
/**
* Compile-time check of whether wchar_t is signed or unsigned.
*
* Returns 1 (true) if wchar_t is signed, else 0 (false). */
#define IS_WCHAR_T_SIGNED STATIC_IF((wchar_t)-1 < 0, 1, 0)
#define IS_SIGNED15(T) \
_Generic((T), \
wchar_t : IS_WCHAR_T_SIGNED, \
default : 0 \
)
#define IS_SIGNED14(T) \
_Generic((T), \
wint_t : IS_WINT_T_SIGNED, \
default : IS_SIGNED15(T) \
)
#define IS_SIGNED13(T) \
_Generic((T), \
sig_atomic_t : IS_SIG_ATOMIC_T_SIGNED, \
default : IS_SIGNED14(T) \
)
#define IS_SIGNED12(T) \
_Generic((T), \
int_fast64_t : 1, \
default : IS_SIGNED13(T) \
)
#define IS_SIGNED11(T) \
_Generic((T), \
int_fast32_t : 1, \
default : IS_SIGNED12(T) \
)
#define IS_SIGNED10(T) \
_Generic((T), \
int_fast16_t : 1, \
default : IS_SIGNED11(T) \
)
#define IS_SIGNED9(T) \
_Generic((T), \
int_fast8_t : 1, \
default : IS_SIGNED10(T) \
)
#define IS_SIGNED8(T) \
_Generic((T), \
int_least64_t : 1, \
default : IS_SIGNED9(T) \
)
#define IS_SIGNED7(T) \
_Generic((T), \
int_least32_t : 1, \
default : IS_SIGNED8(T) \
)
#define IS_SIGNED6(T) \
_Generic((T), \
int_least16_t : 1, \
default : IS_SIGNED7(T) \
)
#define IS_SIGNED5(T) \
_Generic((T), \
int_least8_t : 1, \
default : IS_SIGNED6(T) \
)
#define IS_SIGNED4(T) \
_Generic((T), \
int8_t : 1, \
int16_t : 1, \
int32_t : 1, \
int64_t : 1, \
default : IS_SIGNED5(T) \
)
#define IS_SIGNED3(T) \
_Generic((T), \
intptr_t : 1, \
default : IS_SIGNED4(T) \
)
#define IS_SIGNED2(T) \
_Generic((T), \
intmax_t : 1, \
default : IS_SIGNED3(T) \
)
#define IS_SIGNED1(T) \
_Generic((T), \
ptrdiff_t : 1, \
default : IS_SIGNED2(T) \
)
/**
* Compile-time check whether the type of T is a signed type.
*
* T - An expression. It is not evaluated.
*
* Note: This would not detect _BitInt.
*
* Returns 1 (true) only if T is a signed type; 0 (false) elsewise. */
#define IS_SIGNED(T) \
_Generic((T), \
char : IS_CHAR_SIGNED, \
short int : 1, \
int : 1, \
long int : 1, \
long long int : 1, \
default : IS_SIGNED1(T) \
)
#define IS_UNSIGNED15(T) \
_Generic((T), \
wchar_t : !IS_WCHAR_T_SIGNED, \
default : 0 \
)
#define IS_UNSIGNED14(T) \
_Generic((T), \
wint_t : !IS_WINT_T_SIGNED, \
default : IS_UNSIGNED15(T) \
)
#define IS_UNSIGNED13(T) \
_Generic((T), \
sig_atomic_t : !IS_SIG_ATOMIC_T_SIGNED,\
default : IS_UNSIGNED14(T) \
)
#define IS_UNSIGNED12(T) \
_Generic((T), \
uint_fast64_t : 1, \
default : IS_UNSIGNED13(T) \
)
#define IS_UNSIGNED11(T) \
_Generic((T), \
uint_fast32_t : 1, \
default : IS_UNSIGNED12(T) \
)
#define IS_UNSIGNED10(T) \
_Generic((T), \
uint_fast16_t : 1, \
default : IS_UNSIGNED11(T) \
)
#define IS_UNSIGNED9(T) \
_Generic((T), \
uint_fast8_t : 1, \
default : IS_UNSIGNED10(T) \
)
#define IS_UNSIGNED8(T) \
_Generic((T), \
uint_least64_t : 1, \
default : IS_UNSIGNED9(T) \
)
#define IS_UNSIGNED7(T) \
_Generic((T), \
uint_least32_t : 1, \
default : IS_UNSIGNED8(T) \
)
#define IS_UNSIGNED6(T) \
_Generic((T), \
uint_least16_t : 1, \
default : IS_UNSIGNED7(T) \
)
#define IS_UNSIGNED5(T) \
_Generic((T), \
uint_least8_t : 1, \
default : IS_UNSIGNED6(T) \
)
#define IS_UNSIGNED4(T) \
_Generic((T), \
uint8_t : 1, \
uint16_t : 1, \
uint32_t : 1, \
uint64_t : 1, \
default : IS_UNSIGNED5(T) \
)
#define IS_UNSIGNED3(T) \
_Generic((T), \
uintptr_t : 1, \
default : IS_UNSIGNED4(T) \
)
#define IS_UNSIGNED2(T) \
_Generic((T), \
uintmax_t : 1, \
default : IS_UNSIGNED3(T) \
)
#define IS_UNSIGNED1(T) \
_Generic((T), \
size_t : 1, \
default : IS_UNSIGNED2(T) \
)
/**
* Compile-time check of whether the type of T is a unsigned type.
*
* T - An expression. It is not evaluated.
*
* Note: This would not detect _BitInt.
*
* Returns 1 (true) only if T is a unsigned type; 0 (false) elsewise. */
#define IS_UNSIGNED(T) \
_Generic((T), \
_Bool : 1, \
char : !IS_CHAR_SIGNED, \
unsigned char : 1, \
unsigned short int : 1, \
unsigned int : 1, \
unsigned long int : 1, \
unsigned long long int : 1, \
default : IS_UNSIGNED1(T) \
)
/**
* Compile-time check of whether the type of T is any integral type.
*
* T - An expression. It is not evaluated.
*
* Note: This would not detect _BitInt.
*
* Returns 1 (true) if T is any integral type, 0 (false) elsewise. */
#define IS_INTEGRAL(T) (IS_SIGNED(T) || IS_UNSIGNED(T))
/**
* Compile-time check of whether the type of T is a floating-point type.
*
* T - An expression. It is not evaluated.
*
* Returns 1 (true) if T is a floating-point type, 0 (false) elsewise. */
#if defined(__STDC_IEC_60559_DFP__) \
&& defined(__STDC_IEC_60559_COMPLEX__) \
&& defined(_Imaginary_I)
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double : 1, \
float _Complex : 1, \
double _Complex : 1, \
long double _Complex : 1, \
float _Imaginary : 1, \
double _Imaginary : 1, \
long double _Imaginary: 1, \
_Decimal32 : 1, \
_Decimal64 : 1, \
_Decimal128 : 1, \
default : 0 \
)
#elif defined(__STDC_IEC_60559_COMPLEX__) \
&& defined(_Imaginary_I) \
&& !defined(__STDC_IEC_60559_DFP__)
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double : 1, \
float _Complex : 1, \
double _Complex : 1, \
long double _Complex : 1, \
float _Imaginary : 1, \
double _Imaginary : 1, \
long double _Imaginary: 1, \
default : 1 \
)
#elif defined(__STDC_IEC_60559_COMPLEX__) \
&& defined(__STDC_IEC_60559_DFP__) \
&& !defined(_Imaginary_I)
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double : 1, \
float _Complex : 1, \
double _Complex : 1, \
long double _Complex : 1, \
_Decimal32 : 1, \
_Decimal64 : 1, \
_Decimal128 : 1, \
default : 0 \
)
#elif defined(__STDC_IEC_60559_DFP__) && !defined(__STDC_IEC_60559_COMPLEX__)
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double : 1, \
_Decimal32 : 1, \
_Decimal64 : 1, \
_Decimal128 : 1, \
default : 0 \
)
#elif defined(__STDC_IEC_60559_COMPLEX__) && !defined(__STDC_IEC_60559_DFP__)
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double : 1, \
float _Complex : 1, \
double _Complex : 1, \
long double _Complex : 1, \
default : 0 \
)
#else
#define IS_FLOATING_POINT(T) \
_Generic((T), \
float : 1, \
double : 1, \
long double: 1, \
default : 0 \
)
#endif
/**
* Compile-time check of whether the type of T is any arithmetic type.
*
* T - An expression. It is not evaluated.
*
* Note: This would not detect _BitInt.
*
* Returns 1 (true) only if T is a C is any arithmetic type, 0 (false) elsewise. */
#define IS_ARITHMETIC(T) (IS_INTEGRAL(T) || IS_FLOATING_POINT(T))
/**
* Compile-time check of whether the type of T is a C string type, i.e. char *,
* or char const *.
*
* T - An expression. It is not evaluated.
*
* Returns 1 (true) only if T is a C string type, 0 (false) elsewise. */
#define IS_C_STR(T) \
_Generic((T), \
char * : 1, \
char const *: 1, \
default : 0 \
)
/**
* Compile-time of whether the type of T is compatible with the type of an
* array of length N.
*
* T - An expression. It is not evaluated.
* N - Length of array.
*
* Returns 1 (true) only if T is compatible with array of length N, 0 (false)
* elsewise. */
#define IS_COMPATIBLE_WITH_ARRAY_OF_LENGTH_N(T, N) \
_Generic(&(T), \
typeof(*T) (*)[N]: 1, \
default : 0 \
)
/**
* Compile-time of whether the type of T is variable-length array or an
* unspecified-length array.
*
* T - An expression. It is not evaluated.
*
* Returns 1 (true) only if T is a VLA or a ULA, 0 (false) elsewise.
*
* See also: https://stackoverflow.com/a/78597305/20017547 */
#define IS_VLA_OR_ULA(T) \
(IS_COMPATIBLE_WITH_ARRAY_OF_LENGTH_N(T, 1) \
&& IS_COMPATIBLE_WITH_ARRAY_OF_LENGTH_N(T, 2))
/**
* Compile-time check of whether the type of T is a function type.
*
* T - An expression. It is not evaluated.
*
* Returns 1 (true) only if T is a function type, 0 (false) elsewise.
*
* See also: https://stackoverflow.com/a/78601265/20017547 */
#define IS_FUNCTION(T) \
_Generic((T), \
typeof(T)*: true, \
default: false \
)
/**
* Like C11's _Static_assert() except that it can be used in an expression.
*
* EXPR - The expression to check.
* MSG - The string literal of the error message to print only if EXPR evalutes
* to false.
*
* Always returns true. */
#define STATIC_ASSERT_EXPR(EXPR, MSG) \
(!!sizeof( struct { static_assert ( (EXPR), MSG ); char c; } ))
/**
* Gets the number of elements of the given array. */
#define ARRAY_CARDINALITY(ARRAY) ( \
sizeof(ARRAY) / sizeof(0[ARRAY]) \
* STATIC_ASSERT_EXPR( IS_ARRAY(ARRAY), #ARRAY " must be an array" ))
/**
* Strips trailing linefeed from S.
*
* S - The C string to strip the linefeed from.
*
* Note: STRIP_LF() evalutes S more than once. */
#define STRIP_LF(S) \
(((S) + (STATIC_ASSERT_EXPR(IS_C_STR(S), \
#S " must be a C string") - 1))[strcspn((S), "\r\n")] = '\0')
/**
* Gets the length of S.
*
* S - The C string literal to get the length of.
*
* Note: STRLITLEN() evalutes S more than once. */
#define STRLITLEN(S) \
(ARRAY_CARDINALITY(S) - STATIC_ASSERT_EXPR(IS_C_STR(S), \
#S " must be a C string literal"))
/**
* Advances S over all CHARS.
*
* S - The C string pointer to advance.
* CHARS - A C string containing the characters to skip over.
*
* Returns the updated S.
*
* Note: SKIP_CHARS() evalutes S more than once. */
#define SKIP_CHARS(S, CHARS) \
((S) += strspn((S), (CHARS)))
/**
* Advances S over all whitespace.
*
* S - The string pointer to advance.
*
* Returns the updated S.
*
* Note: SKIP_WS() evalutes S more than once. */
#define SKIP_WS(S) \
SKIP_CHARS((S), " \n\t\r\f\v")
/**
* Convenience macro for iterating over the elements of a fixed-length array.
*
* Note: Compound literal array is not a valid value for ARRAY.
*
* VAR - The element loop variable.
* ARRAY - The array to iterate over. */
#define FOREACH_ARRAY_ELEMENT(VAR, ARRAY) \
for (typeof(*ARRAY) const *VAR = (ARRAY); VAR < (ARRAY) + ARRAY_CARDINALITY(ARRAY); ++VAR)
/**
* The machinery to vectorize any function that takes any type of pointer.
*
* TYPE - The type of pointer the function takes. For a function that takes in
* a void *, this shall be void.
* FN - The function to vectorize.
* ... - The arguments. */
#define FN_APPLY(TYPE, FN, ...) \
BLOCK( \
void *stopper = (int[]){0}; \
TYPE **list = (TYPE*[]){ __VA_ARGS__, stopper}; \
for (size_t i = 0; list[i]; i++) { \
STATIC_ASSERT_EXPR(IS_FUNCTION(FN), \
#FN " should be a function."); \
FN(list[i]); \
} \
)
/**
* Calls the free() function individually on all arguments --- useful for
* replacing multiple individual calls to free() like these:
*
* free(a);
* free(b);
* free(c);
* free(d);
*/
#define FREE_ALL(...) FN_APPLY(void, free, __VA_ARGS__)
/**
* Initializes memory pointed to by a pointer with values of a specified type
* and number of elements.
*
* PTR - The pointer to memory to be initialized.
* TYPE - The type of the elements.
* NELEMS - The number of elements.
* ... - The elements. */
#define INIT(PTR, TYPE, NELEMS, ...) \
memcpy(PTR, (TYPE []) {__VA_ARGS__}, NELEMS * sizeof(TYPE))
/**
* Takes two type names (or expressions representing types) and evalutes to the
* size (in bytes) of the larget type.
*
* MAXSIZE() never evalutes either X or Y. */
#define MAXSIZE(X, Y) (sizeof(X) > sizeof(Y) ? sizeof(X) : sizeof(Y))
/**
* Takes two type names (or expressions representing types) and evalutes to the
* size (in bytes) of the smaller type.
*
* MINSIZE() never evalutes either X or Y. */
#define MINSIZE(X, Y) (sizeof(X) < sizeof(Y) ? sizeof(X) : sizeof(Y))
/**
* Copies the minimum of the sizes of T and S from S to T. */
#define BYTECOPY(T, S) memcpy(&(T), &(S), MINSIZE(T, S))
/**
* A special-case of INTERNAL_ERROR() that prints an unexpected integer value.
*
* EXPR - The expression having the unexpected value. */
#define UNEXPECTED_INT_VALUE(EXPR) \
INTERNAL_ERROR("%lld (0x%llX): unexpected value for " #EXPR "\n", \
(long long)(EXPR), (unsigned long long)(EXPR))
/**
* A special-case of fatal_error() that additionally prints the file, line,
* and function name where an internal error occured.
*
* FMT - The printf() format string literal to use.
* ... - The printf() arguments. */
#define INTERNAL_ERROR(FMT, ...) \
fatal_error("%s::%d::%s(): internal error: " FMT "", __FILE__, __LINE__, \
__VA_OPT__(,) __VA_ARGS__)
/**
* The macro to which FPRINTF dispatches in the absence of arguments. */
#define FPRINTF_II(STREAM, FMT) \
fputs(FMT, STREAM)
/**
* The macro to which FPRINTF dispatches in the presence of arguments. */
#define FPRINTF_III(STREAM, FMT, ...) \
fprintf(STREAM, FMT "", __VA_ARGS__)
/**
* Augments calls to fprintf() such that two types of problem are detected:
* - If there is only a format argument and no others, we want to use fputs()
* to avoid scanning the format at execution time.
* - If there are more than one arguments, it should be assured that the format
* is a string literal, such that the contents can be parsed at compiel time.
*
* STREAM - The stream to print to.
* FMT - The printf() format string to use.
*
* If there were no arguments present beside FMT, then the return value is the
* same as what fputs() would return, else if is what fprintf() would return. */
#define FPRINTF(STREAM, FMT, ...) \
FPRINTF_II ## __VA_OPT__(I) \
(STREAM + (STATIC_ASSERT_EXPR(IS_FILE_PTR(STREAM), \
#STREAM " must be a FILE *") - 1), \
FMT __VA_OPT__(,) __VA_ARGS__)
/**
* Increases cap by 2x and returns it.
*
* If cap is less than 8, bumps it up to 8.
*
* double_capacity() does not check for overflow. */
[[reproducible, gnu::always_inline, gnu::const]] static inline size_t
double_capacity(size_t cap);
/**
* Increases cap by 1.5x and returns it.
*
* If cap is less than, bumps it up to 8.
*
* grow_capacity() does not check for overflow. */
[[reproducible, gnu::always_inline, gnu::const]] static inline size_t
grow_capacity(size_t cap);
/* The semantics of reproducible and gnu::const are a little different, but
* that difference is not relevant here.
*
* Fall back to gnu::const if reproducible is not available, or vice versa. If
* neither are recognized, they shall be ignored. */
[[reproducible, gnu::always_inline, gnu::const]] static inline size_t
double_capacity(size_t cap)
{
return cap < 8 ? 8 : cap * 2;
}
[[reproducible, gnu::always_inline, gnu::const]] static inline size_t
grow_capacity(size_t cap)
{
return cap < 8 ? 8 : cap * 3 / 2;
}
/**
* Trims the memory region pointed by p to n bytes with realloc().
*
* Returns the trimmed memory region on success, or p on failure. */
[[gnu::always_inline]] static inline void *safe_trim(void *p, size_t n)
{
void *const p2 = realloc(p, n);
return p2 ? p2 : p;
}
/* -------------------------------------------------------------------------- */
/**
* The functions util_asprintf() and util_vasprintf() are analogs of sprintf()
* and vsprintf(), except that they allocate a string large enough to hold the
* output including the terminating null byte ('\0'), and return a pointer to
* it via the first argument. This pointer should be passed to free() to release
* the allocated storage when it is no longer needed.
*
* strp - a pointer to the pointer that will hold the string.
* fmt - format string.
* ... - any arguments to fmt.
*
* When successful, these functions return the number of bytes printed, just
* like sprintf(). If memory allocation was not possible, or some other error
* occurs, these functions will return -1, and the contents of strp are unde‐
* -fined. */
[[gnu::format(printf, 2, 3)]] int util_asprintf(char **restrict strp,
const char fmt[restrict static 1],
...);
/**
* See util_asprintf(). */
int util_vasprintf(char **restrict strp,
const char fmt[restrict static 1],
va_list ap);
/**
* The util_strnlen() function returns the number of bytes in the string
* pointed to by s, excluding the terminating null byte ('\0'), but at most
* n. In doing this, strnlen() looks only at the first n characters in the
* string pointed to by s and never beyond s[n - 1].
*