/
fio-stl.h
11706 lines (10172 loc) · 395 KB
/
fio-stl.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
/* *****************************************************************************
Copyright: Boaz Segev, 2019
License: ISC / MIT (choose your license)
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
/* *****************************************************************************
# facil.io's C STL - Basic Dynamic Types Using Macros for Templates
This file contains macros that create generic / common core types, such as:
* Linked Lists - defined by `FIO_LIST_NAME`
* Dynamic Arrays - defined by `FIO_ARY_NAME`
* Hash Maps / Sets - defined by `FIO_MAP_NAME`
* Binary Safe Dynamic Strings - defined by `FIO_STR_NAME`
* Reference counting / Type wrapper - defined by `FIO_REF_NAME` (adds atomic)
* Soft / Dynamic Types (FIOBJ) - defined by `FIO_FIOBJ`
This file also contains common helper macros / primitives, such as:
* Pointer Tagging - defined by `FIO_PTR_TAG(p)`/`FIO_PTR_UNTAG(p)`
* Logging and Assertion (no heap allocation) - defined by `FIO_LOG`
* Atomic add/subtract/replace - defined by `FIO_ATOMIC`
* Bit-Byte Operations - defined by `FIO_BITWISE` and `FIO_BITMAP` (adds atomic)
* Network byte ordering macros - defined by `FIO_NTOL` (adds `FIO_BITWISE`)
* Data Hashing (using Risky Hash) - defined by `FIO_RISKY_HASH`
* Psedo Random Generation - defined by `FIO_RAND`
* String / Number conversion - defined by `FIO_ATOL`
* Command Line Interface helpers - defined by `FIO_CLI`
* Custom Memory Allocation - defined by `FIO_MALLOC`
* Custom JSON Parser - defined by `FIO_JSON`
However, this file does very little (if anything) unless specifically requested.
To make sure this file defines a specific macro or type, it's macro should be
set.
In addition, if the `FIO_TEST_CSTL` macro is defined, the self-testing function
`fio_test_dynamic_types()` will be defined. the `fio_test_dynamic_types`
function will test the functionality of this file and, as consequence, will
define all available macros.
**Notes**:
- To make these functions safe for kernel authoring, the `FIO_MEM_CALLOC` /
`FIO_MEM_FREE` / `FIO_MEM_REALLOC` macros should be (re)-defined.
These macros default to using the `malloc` and `free` functions calls. If
`FIO_MALLOC` was defined, these macros will default to the custom memory
allocator.
- To make the custom memory allocator safe for kernel authoring, the
`FIO_MEM_PAGE_ALLOC`, `FIO_MEM_PAGE_REALLOC` and `FIO_MEM_PAGE_FREE` macros
should be defined. These macros default to using `mmap` and `munmap` (on
linux, also `mremap`).
- The functions defined using this file default to `static` or `static
inline`.
To create an externally visible API, define the `FIO_EXTERN`. Define the
`FIO_EXTERN_COMPLETE` macro to include the API's implementation as well.
***************************************************************************** */
/* *****************************************************************************
Constants (included once)
***************************************************************************** */
#ifndef H___FIO_CSTL_INCLUDE_ONCE_H
#define H___FIO_CSTL_INCLUDE_ONCE_H
/* *****************************************************************************
Basic macros and included files
***************************************************************************** */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#if !defined(__GNUC__) && !defined(__clang__) && !defined(GNUC_BYPASS)
#define __attribute__(...)
#define __has_include(...) 0
#define __has_builtin(...) 0
#define GNUC_BYPASS 1
#elif !defined(__clang__) && !defined(__has_builtin)
/* E.g: GCC < 6.0 doesn't support __has_builtin */
#define __has_builtin(...) 0
#define GNUC_BYPASS 1
#endif
#ifndef __has_include
#define __has_include(...) 0
#define GNUC_BYPASS 1
#endif
#if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5))
/* GCC < 4.5 doesn't support deprecation reason string */
#define deprecated(reason) deprecated
#endif
#if !defined(__clang__) && !defined(__GNUC__)
#define __thread _Thread_value
#endif
#include <ctype.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__) || \
defined(__CYGWIN__)
#define H___FIO_UNIX_TOOLS_H 1
#endif
/* *****************************************************************************
Version macros and Macro Stringifier
***************************************************************************** */
/* Automatically convert version data to a string constant - ignore these two */
#ifndef FIO_MACRO2STR
#define FIO_MACRO2STR_STEP2(macro) #macro
#define FIO_MACRO2STR(macro) FIO_MACRO2STR_STEP2(macro)
#endif
#define FIO_VERSION_MAJOR 0
#define FIO_VERSION_MINOR 8
#define FIO_VERSION_PATCH 0
#define FIO_VERSION_BETA 1
/** set FIO_VERSION_STRING - version as a String literal */
#if FIO_VERSION_BETA
#define FIO_VERSION_STRING \
FIO_MACRO2STR(FIO_VERSION_MAJOR) \
"." FIO_MACRO2STR(FIO_VERSION_MINOR) "." FIO_MACRO2STR( \
FIO_VERSION_PATCH) ".beta" FIO_MACRO2STR(FIO_VERSION_BETA)
#else
#define FIO_VERSION_STRING \
FIO_MACRO2STR(FIO_VERSION_MAJOR) \
"." FIO_MACRO2STR(FIO_VERSION_MINOR) "." FIO_MACRO2STR(FIO_VERSION_PATCH)
#endif
/* *****************************************************************************
Pointer Arithmatics
***************************************************************************** */
/** Masks a pointer's left-most bits, returning the right bits. */
#define FIO_PTR_MATH_LMASK(T_type, ptr, bits) \
((T_type *)((uintptr_t)(ptr) & (((uintptr_t)1 << (bits)) - 1)))
/** Masks a pointer's right-most bits, returning the left bits. */
#define FIO_PTR_MATH_RMASK(T_type, ptr, bits) \
((T_type *)((uintptr_t)(ptr) & (~(((uintptr_t)1 << (bits)) - 1))))
/** Add offset bytes to pointer, updating the pointer's type. */
#define FIO_PTR_MATH_ADD(T_type, ptr, offset) \
((T_type *)((uintptr_t)(ptr) + (uintptr_t)(offset)))
/** Subtract X bytes from pointer, updating the pointer's type. */
#define FIO_PTR_MATH_SUB(T_type, ptr, offset) \
((T_type *)((uintptr_t)(ptr) - (uintptr_t)(offset)))
/** Find the root object (of a struct) from it's field. */
#define FIO_PTR_FROM_FIELD(T_type, field, ptr) \
FIO_PTR_MATH_SUB(T_type, ptr, (&((T_type *)0)->field))
/* *****************************************************************************
Memory allocation macros
***************************************************************************** */
#ifndef FIO_MEM_CALLOC
/** Allocates size X units of bytes, where all bytes equal zero. */
#define FIO_MEM_CALLOC(size, units) calloc((size), (units))
#undef FIO_MEM_REALLOC
/** Reallocates memory, copying (at least) `copy_len` if neccessary. */
#define FIO_MEM_REALLOC(ptr, old_size, new_size, copy_len) \
realloc((ptr), (new_size))
#undef FIO_MEM_FREE
/** Frees allocated memory. */
#define FIO_MEM_FREE(ptr, size) free((ptr))
#endif /* FIO_MEM_CALLOC */
/* *****************************************************************************
Linked Lists Persistent Macros and Types
***************************************************************************** */
/** A common linked list node type. */
typedef struct fio___list_node_s {
struct fio___list_node_s *next;
struct fio___list_node_s *prev;
} fio___list_node_s;
/** A linked list node type */
#define FIO_LIST_NODE fio___list_node_s
/** A linked list head type */
#define FIO_LIST_HEAD fio___list_node_s
/** Allows initialization of FIO_LIST_HEAD objects. */
#define FIO_LIST_INIT(obj) \
{ .next = &(obj), .prev = &(obj) }
/* *****************************************************************************
Miscellaneous helper macros
***************************************************************************** */
/** An empty macro, adding white space. Used to avoid function like macros. */
#define FIO_NOOP
/* allow logging to quitely fail unless enabled */
#define FIO_LOG_DEBUG(...)
#define FIO_LOG_INFO(...)
#define FIO_LOG_WARNING(...)
#define FIO_LOG_ERROR(...)
#define FIO_LOG_FATAL(...)
#define FIO_LOG2STDERR(...)
#define FIO_LOG2STDERR2(...)
/* Asserts a condition is true, or kills the application using SIGINT. */
#define FIO_ASSERT(cond, ...) \
if (!(cond)) { \
FIO_LOG_FATAL("(" __FILE__ ":" FIO_MACRO2STR(__LINE__) ") "__VA_ARGS__); \
perror(" errno"); \
kill(0, SIGINT); \
exit(-1); \
}
#ifndef FIO_ASSERT_ALLOC
/** Tests for an allocation failure. The behavior can be overridden. */
#define FIO_ASSERT_ALLOC(ptr) \
if (!(ptr)) { \
FIO_LOG_FATAL("memory allocation error "__FILE__ \
":" FIO_MACRO2STR(__LINE__)); \
kill(0, SIGINT); \
exit(-1); \
}
#endif
#ifdef DEBUG
/** If `DEBUG` is defined, acts as `FIO_ASSERT`, otherwaise a NOOP. */
#define FIO_ASSERT_DEBUG(cond, ...) FIO_ASSERT(cond, __VA_ARGS__)
#else
#define FIO_ASSERT_DEBUG(...)
#endif
/* *****************************************************************************
End persistent segment (end include-once guard)
***************************************************************************** */
#endif /* H___FIO_CSTL_INCLUDE_ONCE_H */
/* *****************************************************************************
Common internal Macros
***************************************************************************** */
/* *****************************************************************************
Common macros
***************************************************************************** */
#ifndef FIO_NAME_FROM_MACRO_STEP2 /* don't redefine in recursive include */
/* Used for naming functions and types, prefixing FIO_NAME to the name */
#define FIO_NAME_FROM_MACRO_STEP2(prefix, postfix) prefix##_##postfix
#define FIO_NAME_FROM_MACRO_STEP1(prefix, postfix) \
FIO_NAME_FROM_MACRO_STEP2(prefix, postfix)
#define FIO_NAME(prefix, postfix) FIO_NAME_FROM_MACRO_STEP1(prefix, postfix)
#if !FIO_EXTERN
#define SFUNC_ static __attribute__((unused))
#define IFUNC_ static inline __attribute__((unused))
#ifndef FIO_EXTERN_COMPLETE /* force implementation, emitting static data */
#define FIO_EXTERN_COMPLETE 2
#endif
#else /* FIO_EXTERN */
#define SFUNC_
#define IFUNC_
#endif /* FIO_EXTERN */
#define HFUNC static inline __attribute__((unused)) /* internal helper */
#define HSFUNC static __attribute__((unused)) /* internal helper */
#define SFUNC SFUNC_
#define IFUNC IFUNC_
#ifndef FIO_PTR_TAG
/**
* Supports embedded pointer tagging / untagging for the included types.
*
* Should resolve to a tagged pointer value. i.e.: ((uintptr_t)(p) | 1)
*/
#define FIO_PTR_TAG(p) (p)
#endif
#ifndef FIO_PTR_UNTAG
/**
* Supports embedded pointer tagging / untagging for the included types.
*
* Should resolve to an untagged pointer value. i.e.: ((uintptr_t)(p) | ~1UL)
*/
#define FIO_PTR_UNTAG(p) (p)
#endif
/**
* If the FIO_PTR_TAG_TYPE is defined, then functions returning a type's pointer
* will return a pointer of the specified type instead.
*/
#ifndef FIO_PTR_TAG_TYPE
#endif
#else /* FIO_NAME_FROM_MACRO_STEP2 - internal helper types are `static` */
#undef SFUNC
#undef IFUNC
#define SFUNC HSFUNC
#define IFUNC HFUNC
#endif /* FIO_NAME_FROM_MACRO_STEP2 vs FIO_STL_KEEP__*/
/* *****************************************************************************
C++ extern start
***************************************************************************** */
/* support C++ */
#ifdef __cplusplus
extern "C" {
/* C++ keyword was deprecated */
#define register
#endif
/* *****************************************************************************
Logging
Use:
```c
FIO_LOG2STDERR("message.") // => message.
FIO_LOG_LEVEL = FIO_LOG_LEVEL_WARNING; // set dynamic logging level
FIO_LOG_INFO("message"); // => [no output]
int i = 3;
FIO_LOG_WARNING("number invalid: %d", i); // => WARNING: number invalid: 3
```
***************************************************************************** */
/**
* Enables logging macros that avoid heap memory allocations
*/
#if !defined(FIO_LOG_PRINT__) && (defined(FIO_LOG) || defined(FIO_MALLOC))
#ifndef FIO_LOG_LENGTH_LIMIT
#define FIO_LOG_LENGTH_LIMIT 1024
#endif
#if FIO_LOG_LENGTH_LIMIT > 128
#define FIO_LOG____LENGTH_ON_STACK FIO_LOG_LENGTH_LIMIT
#define FIO_LOG____LENGTH_BORDER (FIO_LOG_LENGTH_LIMIT - 32)
#else
#define FIO_LOG____LENGTH_ON_STACK (FIO_LOG_LENGTH_LIMIT + 32)
#define FIO_LOG____LENGTH_BORDER FIO_LOG_LENGTH_LIMIT
#endif
#undef FIO_LOG2STDERR
#pragma weak FIO_LOG2STDERR
void __attribute__((format(printf, 1, 0), weak))
FIO_LOG2STDERR(const char *format, ...) {
char tmp___log[FIO_LOG____LENGTH_ON_STACK];
va_list argv;
va_start(argv, format);
int len___log = vsnprintf(tmp___log, FIO_LOG_LENGTH_LIMIT - 2, format, argv);
va_end(argv);
if (len___log <= 0 || len___log >= FIO_LOG_LENGTH_LIMIT - 2) {
if (len___log >= FIO_LOG_LENGTH_LIMIT - 2) {
memcpy(tmp___log + FIO_LOG____LENGTH_BORDER, "... (warning: truncated).",
25);
len___log = FIO_LOG____LENGTH_BORDER + 25;
} else {
fwrite("ERROR: log output error (can't write).\n", 39, 1, stderr);
return;
}
}
tmp___log[len___log++] = '\n';
tmp___log[len___log] = '0';
fwrite(tmp___log, len___log, 1, stderr);
}
#undef FIO_LOG____LENGTH_ON_STACK
#undef FIO_LOG____LENGTH_BORDER
#undef FIO_LOG2STDERR2
#define FIO_LOG2STDERR2(...) \
FIO_LOG2STDERR("("__FILE__ \
":" FIO_MACRO2STR(__LINE__) "): " __VA_ARGS__)
/** Logging level of zero (no logging). */
#define FIO_LOG_LEVEL_NONE 0
/** Log fatal errors. */
#define FIO_LOG_LEVEL_FATAL 1
/** Log errors and fatal errors. */
#define FIO_LOG_LEVEL_ERROR 2
/** Log warnings, errors and fatal errors. */
#define FIO_LOG_LEVEL_WARNING 3
/** Log every message (info, warnings, errors and fatal errors). */
#define FIO_LOG_LEVEL_INFO 4
/** Log everything, including debug messages. */
#define FIO_LOG_LEVEL_DEBUG 5
/** The logging level */
#ifndef FIO_LOG_LEVEL_DEFAULT
#if DEBUG
#define FIO_LOG_LEVEL_DEFAULT FIO_LOG_LEVEL_DEBUG
#else
#define FIO_LOG_LEVEL_DEFAULT FIO_LOG_LEVEL_INFO
#endif
#endif
int __attribute__((weak)) FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEFAULT;
#define FIO_LOG_PRINT__(level, ...) \
do { \
if (level <= FIO_LOG_LEVEL) \
FIO_LOG2STDERR(__VA_ARGS__); \
} while (0)
#undef FIO_LOG_DEBUG
#define FIO_LOG_DEBUG(...) \
FIO_LOG_PRINT__(FIO_LOG_LEVEL_DEBUG, \
"DEBUG ("__FILE__ \
":" FIO_MACRO2STR(__LINE__) "): " __VA_ARGS__)
#undef FIO_LOG_INFO
#define FIO_LOG_INFO(...) \
FIO_LOG_PRINT__(FIO_LOG_LEVEL_INFO, "INFO: " __VA_ARGS__)
#undef FIO_LOG_WARNING
#define FIO_LOG_WARNING(...) \
FIO_LOG_PRINT__(FIO_LOG_LEVEL_WARNING, "WARNING: " __VA_ARGS__)
#undef FIO_LOG_ERROR
#define FIO_LOG_ERROR(...) \
FIO_LOG_PRINT__(FIO_LOG_LEVEL_ERROR, "ERROR: " __VA_ARGS__)
#undef FIO_LOG_FATAL
#define FIO_LOG_FATAL(...) \
FIO_LOG_PRINT__(FIO_LOG_LEVEL_FATAL, "FATAL: " __VA_ARGS__)
#undef FIO_LOG
#endif /* FIO_LOG */
/* *****************************************************************************
Atomic Operations
***************************************************************************** */
#if (defined(FIO_ATOMIC) || defined(FIO_BITMAP) || defined(FIO_REF_NAME) || \
defined(FIO_MALLOC)) && \
!defined(fio_atomic_xchange)
/* C11 Atomics are defined? */
#if defined(__ATOMIC_RELAXED)
/** An atomic exchange operation, returns previous value */
#define fio_atomic_xchange(p_obj, value) \
__atomic_exchange_n((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic addition operation, returns new value */
#define fio_atomic_add(p_obj, value) \
__atomic_add_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic subtraction operation, returns new value */
#define fio_atomic_sub(p_obj, value) \
__atomic_sub_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic AND (&) operation, returns new value */
#define fio_atomic_and(p_obj, value) \
__atomic_and_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic XOR (^) operation, returns new value */
#define fio_atomic_xor(p_obj, value) \
__atomic_xor_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic OR (|) operation, returns new value */
#define fio_atomic_or(p_obj, value) \
__atomic_or_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/** An atomic NOT AND ((~)&) operation, returns new value */
#define fio_atomic_nand(p_obj, value) \
__atomic_nand_fetch((p_obj), (value), __ATOMIC_SEQ_CST)
/* note: __ATOMIC_SEQ_CST may be safer and __ATOMIC_ACQ_REL may be faster */
/* Select the correct compiler builtin method. */
#elif __has_builtin(__sync_add_and_fetch) || (__GNUC__ > 3)
/** An atomic exchange operation, ruturns previous value */
#define fio_atomic_xchange(p_obj, value) \
__sync_val_compare_and_swap((p_obj), *(p_obj), (value))
/** An atomic addition operation, returns new value */
#define fio_atomic_add(p_obj, value) __sync_add_and_fetch((p_obj), (value))
/** An atomic subtraction operation, returns new value */
#define fio_atomic_sub(p_obj, value) __sync_sub_and_fetch((p_obj), (value))
/** An atomic AND (&) operation, returns new value */
#define fio_atomic_and(p_obj, value) __sync_and_and_fetch((p_obj), (value))
/** An atomic XOR (^) operation, returns new value */
#define fio_atomic_xor(p_obj, value) __sync_xor_and_fetch((p_obj), (value))
/** An atomic OR (|) operation, returns new value */
#define fio_atomic_or(p_obj, value) __sync_or_and_fetch((p_obj), (value))
/** An atomic NOT AND ((~)&) operation, returns new value */
#define fio_atomic_nand(p_obj, value) __sync_nand_and_fetch((p_obj), (value))
#else
#error Required builtin "__sync_add_and_fetch" not found.
#endif
#ifndef FIO_THREAD_RESCHEDULE
/**
* Reschedules the thread by calling nanosleeps for a sinlge nano-second.
*
* In practice, the thread will probably sleep for 60ns or more.
*/
#define FIO_THREAD_RESCHEDULE() \
do { \
const struct timespec tm = {.tv_nsec = 1}; \
nanosleep(&tm, NULL); \
} while (0)
#endif
#ifndef FIO_THREAD_WAIT
/**
* Calls nonsleep with the requested nano-second count.
*/
#define FIO_THREAD_WAIT(nano_sec) \
do { \
const struct timespec tm = {.tv_nsec = ((nano_sec) % 1000000000), \
.tv_sec = ((nano_sec) / 1000000000)}; \
nanosleep(&tm, NULL); \
} while (0)
#endif
#define FIO_LOCK_INIT 0
typedef volatile unsigned char fio_lock_i;
/** Returns 0 on success and 1 on failure. */
HFUNC uint8_t fio_trylock(fio_lock_i *lock) {
__asm__ volatile("" ::: "memory"); /* clobber CPU registers */
return fio_atomic_xchange(lock, 1);
}
/** Busy waits for a lock to become available - not recommended. */
HFUNC void fio_lock(fio_lock_i *lock) {
while (fio_trylock(lock)) {
struct timespec tm = {.tv_nsec = 1};
nanosleep(&tm, NULL);
}
}
/** Returns 1 if the lock is locked, 0 otherwise. */
HFUNC uint8_t fio_is_locked(fio_lock_i *lock) { return *lock; }
/** Unlocks the lock, no matter which thread owns the lock. */
HFUNC void fio_unlock(fio_lock_i *lock) { fio_atomic_xchange(lock, 0); }
#endif /* FIO_ATOMIC */
#undef FIO_ATOMIC
/* *****************************************************************************
Bit-Byte Operations
***************************************************************************** */
#if (defined(FIO_BITWISE) || defined(FIO_RAND) || defined(FIO_NTOL)) && \
!defined(fio_lrot)
/* *****************************************************************************
Swapping byte's order (`bswap` variations)
***************************************************************************** */
/** Byte swap a 16 bit integer, inlined. */
#if __has_builtin(__builtin_bswap16)
#define fio_bswap16(i) __builtin_bswap16((uint16_t)(i))
#else
#define fio_bswap16(i) ((((i)&0xFFU) << 8) | (((i)&0xFF00U) >> 8))
#endif
/** Byte swap a 32 bit integer, inlined. */
#if __has_builtin(__builtin_bswap32)
#define fio_bswap32(i) __builtin_bswap32((uint32_t)(i))
#else
#define fio_bswap32(i) \
((((i)&0xFFUL) << 24) | (((i)&0xFF00UL) << 8) | (((i)&0xFF0000UL) >> 8) | \
(((i)&0xFF000000UL) >> 24))
#endif
/** Byte swap a 64 bit integer, inlined. */
#if __has_builtin(__builtin_bswap64)
#define fio_bswap64(i) __builtin_bswap64((uint64_t)(i))
#else
#define fio_bswap64(i) \
((((i)&0xFFULL) << 56) | (((i)&0xFF00ULL) << 40) | \
(((i)&0xFF0000ULL) << 24) | (((i)&0xFF000000ULL) << 8) | \
(((i)&0xFF00000000ULL) >> 8) | (((i)&0xFF0000000000ULL) >> 24) | \
(((i)&0xFF000000000000ULL) >> 40) | (((i)&0xFF00000000000000ULL) >> 56))
#endif
/* *****************************************************************************
Bit rotation
***************************************************************************** */
/** 32Bit left rotation, inlined. */
#define fio_lrot32(i, bits) \
(((uint32_t)(i) << ((bits)&31UL)) | ((uint32_t)(i) >> ((-(bits)) & 31UL)))
/** 32Bit right rotation, inlined. */
#define fio_rrot32(i, bits) \
(((uint32_t)(i) >> ((bits)&31UL)) | ((uint32_t)(i) << ((-(bits)) & 31UL)))
/** 64Bit left rotation, inlined. */
#define fio_lrot64(i, bits) \
(((uint64_t)(i) << ((bits)&63UL)) | ((uint64_t)(i) >> ((-(bits)) & 63UL)))
/** 64Bit right rotation, inlined. */
#define fio_rrot64(i, bits) \
(((uint64_t)(i) >> ((bits)&63UL)) | ((uint64_t)(i) << ((-(bits)) & 63UL)))
/** Left rotation for an unknown size element, inlined. */
#define fio_lrot(i, bits) \
(((i) << ((bits) & ((sizeof((i)) << 3) - 1))) | \
((i) >> ((-(bits)) & ((sizeof((i)) << 3) - 1))))
/** Right rotation for an unknown size element, inlined. */
#define fio_rrot(i, bits) \
(((i) >> ((bits) & ((sizeof((i)) << 3) - 1))) | \
((i) << ((-(bits)) & ((sizeof((i)) << 3) - 1))))
/* *****************************************************************************
Unaligned memory read / write operations
***************************************************************************** */
/** Converts an unaligned network ordered byte stream to a 16 bit number. */
#define fio_str2u16(c) \
((uint16_t)(((uint16_t)(((uint8_t *)(c))[0]) << 8) | \
(uint16_t)(((uint8_t *)(c))[1])))
/** Converts an unaligned network ordered byte stream to a 32 bit number. */
#define fio_str2u32(c) \
((uint32_t)(((uint32_t)(((uint8_t *)(c))[0]) << 24) | \
((uint32_t)(((uint8_t *)(c))[1]) << 16) | \
((uint32_t)(((uint8_t *)(c))[2]) << 8) | \
(uint32_t)(((uint8_t *)(c))[3])))
/** Converts an unaligned network ordered byte stream to a 64 bit number. */
#define fio_str2u64(c) \
((uint64_t)((((uint64_t)((uint8_t *)(c))[0]) << 56) | \
(((uint64_t)((uint8_t *)(c))[1]) << 48) | \
(((uint64_t)((uint8_t *)(c))[2]) << 40) | \
(((uint64_t)((uint8_t *)(c))[3]) << 32) | \
(((uint64_t)((uint8_t *)(c))[4]) << 24) | \
(((uint64_t)((uint8_t *)(c))[5]) << 16) | \
(((uint64_t)((uint8_t *)(c))[6]) << 8) | (((uint8_t *)(c))[7])))
/** Writes a local 16 bit number to an unaligned buffer in network order. */
#define fio_u2str16(buffer, i) \
do { \
((uint8_t *)(buffer))[0] = ((uint16_t)(i) >> 8) & 0xFF; \
((uint8_t *)(buffer))[1] = ((uint16_t)(i)) & 0xFF; \
} while (0);
/** Writes a local 32 bit number to an unaligned buffer in network order. */
#define fio_u2str32(buffer, i) \
do { \
((uint8_t *)(buffer))[0] = ((uint32_t)(i) >> 24) & 0xFF; \
((uint8_t *)(buffer))[1] = ((uint32_t)(i) >> 16) & 0xFF; \
((uint8_t *)(buffer))[2] = ((uint32_t)(i) >> 8) & 0xFF; \
((uint8_t *)(buffer))[3] = ((uint32_t)(i)) & 0xFF; \
} while (0);
/** Writes a local 64 bit number to an unaligned buffer in network order. */
#define fio_u2str64(buffer, i) \
do { \
((uint8_t *)(buffer))[0] = (((uint64_t)(i) >> 56) & 0xFF); \
((uint8_t *)(buffer))[1] = (((uint64_t)(i) >> 48) & 0xFF); \
((uint8_t *)(buffer))[2] = (((uint64_t)(i) >> 40) & 0xFF); \
((uint8_t *)(buffer))[3] = (((uint64_t)(i) >> 32) & 0xFF); \
((uint8_t *)(buffer))[4] = (((uint64_t)(i) >> 24) & 0xFF); \
((uint8_t *)(buffer))[5] = (((uint64_t)(i) >> 16) & 0xFF); \
((uint8_t *)(buffer))[6] = (((uint64_t)(i) >> 8) & 0xFF); \
((uint8_t *)(buffer))[7] = (((uint64_t)(i)) & 0xFF); \
} while (0);
/* *****************************************************************************
Constant-time selectors
***************************************************************************** */
/** Returns 1 if the expression is true (input isn't zero). */
HFUNC uintptr_t fio_ct_true(uintptr_t cond) {
// promise that the highest bit is set if any bits are set, than shift.
return ((cond | (0 - cond)) >> ((sizeof(cond) << 3) - 1));
}
/** Returns 1 if the expression is false (input is zero). */
HFUNC uintptr_t fio_ct_false(uintptr_t cond) {
// fio_ct_true returns only one bit, XOR will inverse that bit.
return fio_ct_true(cond) ^ 1;
}
/** Returns `a` if `cond` is boolean and true, returns b otherwise. */
HFUNC uintptr_t fio_ct_if(uint8_t cond, uintptr_t a, uintptr_t b) {
// b^(a^b) cancels b out. 0-1 => sets all bits.
return (b ^ ((0 - (cond & 1)) & (a ^ b)));
}
/** Returns `a` if `cond` isn't zero (uses fio_ct_true), returns b otherwise. */
HFUNC uintptr_t fio_ct_if2(uintptr_t cond, uintptr_t a, uintptr_t b) {
// b^(a^b) cancels b out. 0-1 => sets all bits.
return fio_ct_if(fio_ct_true(cond), a, b);
}
/* *****************************************************************************
Hemming Distance and bit counting
***************************************************************************** */
#if __has_builtin(__builtin_popcountll)
#define fio_popcount(n) __builtin_popcountll(n)
#else
HFUNC int fio_popcount(uint64_t n) {
int c = 0;
while (n) {
++c;
n &= n - 1;
}
return c;
}
#endif
#define fio_hemming_dist(n1, n2) fio_popcount(((uint64_t)(n1) ^ (uint64_t)(n2)))
/* *****************************************************************************
Bitewise helpers cleanup
***************************************************************************** */
#endif /* FIO_BITWISE */
#undef FIO_BITWISE
/* *****************************************************************************
Bitmap Helpers
***************************************************************************** */
#if defined(FIO_BITMAP) && !defined(H___FIO_BITMAP_H)
#define H___FIO_BITMAP_H
/* *****************************************************************************
Bitmap access / manipulation
***************************************************************************** */
HFUNC uint8_t fio_bitmap_get(void *map, size_t bit) {
return ((((uint8_t *)(map))[(bit) >> 3] >> ((bit)&7)) & 1);
}
HFUNC void fio_bitmap_set(void *map, size_t bit) {
fio_atomic_or((uint8_t *)(map) + ((bit) >> 3), (1UL << ((bit)&7)));
}
HFUNC void fio_bitmap_unset(void *map, size_t bit) {
fio_atomic_and((uint8_t *)(map) + ((bit) >> 3),
(uint8_t)(~(1UL << ((bit)&7))));
}
#endif
#undef FIO_BITMAP
/* *****************************************************************************
Network Byte Ordering
***************************************************************************** */
#if defined(FIO_NTOL) && !defined(fio_lton16)
#if !defined(__BIG_ENDIAN__)
/* nothing to do */
#elif (defined(__LITTLE_ENDIAN__) && !__LITTLE_ENDIAN__) || \
(defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
#define __BIG_ENDIAN__ 1
#elif !defined(__BIG_ENDIAN__) && !defined(__BYTE_ORDER__) && \
!defined(__LITTLE_ENDIAN__)
#error Could not detect byte order on this system.
#endif
#if __BIG_ENDIAN__
/** Local byte order to Network byte order, 16 bit integer */
#define fio_lton16(i) (i)
/** Local byte order to Network byte order, 32 bit integer */
#define fio_lton32(i) (i)
/** Local byte order to Network byte order, 62 bit integer */
#define fio_lton64(i) (i)
/** Network byte order to Local byte order, 16 bit integer */
#define fio_ntol16(i) (i)
/** Network byte order to Local byte order, 32 bit integer */
#define fio_ntol32(i) (i)
/** Network byte order to Local byte order, 62 bit integer */
#define fio_ntol64(i) (i)
#else /* Little Endian */
/** Local byte order to Network byte order, 16 bit integer */
#define fio_lton16(i) fio_bswap16((i))
/** Local byte order to Network byte order, 32 bit integer */
#define fio_lton32(i) fio_bswap32((i))
/** Local byte order to Network byte order, 62 bit integer */
#define fio_lton64(i) fio_bswap64((i))
/** Network byte order to Local byte order, 16 bit integer */
#define fio_ntol16(i) fio_bswap16((i))
/** Network byte order to Local byte order, 32 bit integer */
#define fio_ntol32(i) fio_bswap32((i))
/** Network byte order to Local byte order, 62 bit integer */
#define fio_ntol64(i) fio_bswap64((i))
#endif /* __BIG_ENDIAN__ */
#endif /* H___FIO_NTOL_H */
/* *****************************************************************************
Custom Memory Allocation
***************************************************************************** */
#if defined(FIO_MALLOC) && !defined(H___FIO_MALLOC_H)
#define H___FIO_MALLOC_H
/* *****************************************************************************
Memory Allocation - API
***************************************************************************** */
/* *****************************************************************************
Memory allocator for short lived objects
***************************************************************************** */
/* inform the compiler that the returned value is aligned on 16 byte marker */
#if __clang__ || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)
#define FIO_ALIGN __attribute__((assume_aligned(16)))
#define FIO_ALIGN_NEW __attribute__((malloc, assume_aligned(16)))
#else
#define FIO_ALIGN
#define FIO_ALIGN_NEW
#endif
/**
* Allocates memory using a per-CPU core block memory pool.
* Memory is zeroed out.
*