-
Notifications
You must be signed in to change notification settings - Fork 0
/
CLM_LIBS.h
3938 lines (3921 loc) · 313 KB
/
CLM_LIBS.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
/** *********************************************************************** **/
/** **/
/** # CLM_LIBS **/
/** **/
/** **CONTENT:** The CLM_LIBS code-generating macros **/
/** **/
/** **AUTHOR:** Carlos Luna-Mota **/
/** **/
/** **SOURCE:** <https://github.com/CarlosLunaMota/CLM_LIBS> **/
/** **/
/** *********************************************************************** **/
/** **/
/** ## INTRODUCTION **/
/** **/
/** This is a collection of code-generating macros for the C preprocessor. **/
/** **/
/** The main motivation to write these macros is to put together all the **/
/** functions that I frequently use in my C projects so I can test them **/
/** properly, document them properly and trust them hereafter. **/
/** **/
/** I am using the code-generating macro approach for writting these **/
/** libraries because I wanted to provide generic data structures without **/
/** using `void` pointers. **/
/** **/
/** Although this is a personal project, I am trying to document everything **/
/** so others can use this code too. For the same reason, I release the **/
/** code into the Public Domain using the Unlicense (see LICENSE below). **/
/** **/
/** *********************************************************************** **/
/** **/
/** ## CODE CONVENTIONS **/
/** **/
/** Each library is just a code generating macro whose name starts with **/
/** `IMPORT_CLM_`. The C preprocessor will substitute each macro call with **/
/** a set of functions and type definitions before compiling the code, so **/
/** you just get the same behavior that you would get if you coded these **/
/** auxilary functions and data types by hand (including type-safety). **/
/** **/
/** The name of all types and functions starts with the name of the library **/
/** (macro) they belong to. The user can add an optional prefix to all the **/
/** functions and data types when calling a macro to avoid conflicts with **/
/** existing code or different calls to the same macro. **/
/** **/
/** All `CLM_LIBS` functions are declared as `static inline` and are **/
/** mutually independent (no `CLM_LIBS` function calls any other `CLM_LIBS` **/
/** function) although a few of them are recursive (they call themselves). **/
/** This self-imposed constraint hurts modularity and readability but **/
/** simplifies the task of versioning and reusing the code: You could erase **/
/** or substitute any function without worrying about dependencies. **/
/** **/
/** I am willing to sacrfice efficiency for practical reasons like safety, **/
/** versatility or interface coherence. I will probably be the main user of **/
/** these libraries so I want them to be easy to use rather than fast or **/
/** easy to code. If performance is your main concern, there might be **/
/** better libraries out there (that will probably be WAY more difficult to **/
/** use). This being said, I will try to provide code that is efficient in **/
/** terms of time and space. I just will not agonize about it. **/
/** **/
/** I am also not targeting outdated C compilers or embeded systems. I make **/
/** use of C99 features and manage the memory allocations with the standard **/
/** `malloc` and `free` functions. I am writing these libraries to be easy **/
/** to read and modify so anyone can adapt them to their needs, though. **/
/** **/
/** Finally, regarding data types: **/
/** **/
/** * `double` is the default floating point type **/
/** * `size_t` is the default index and size type (transdichotomous model) **/
/** * `char *` is the default `\0`-ended string type **/
/** * `bool` is the default boolean type (rather than `int`) **/
/** * All container types are named as the macro they belong to and are **/
/** pointers to the corresponding structs (same name with `_s` suffix). **/
/** **/
/** *********************************************************************** **/
/** **/
/** ## CODE DEPENDENCIES **/
/** **/
/** The file `CLM_LIBS.h` contains the code, the documentation and the **/
/** license. The other files that you may find in the repository are used **/
/** for the developement of `CLM_LIBS.h` and are not needed in practice: **/
/** **/
/** * `README.md` - Contains the documentation in GitHub's MarkDown format **/
/** * `CHEATSHEET.md` - Contains a quick-reference cheatsheet **/
/** * `UpdateDocs.py` - Contains a script for generating the documentation **/
/** * `LICENSE` - Contains another copy of the same license (see below) **/
/** * `makefile` - Contains a script for automating the test process **/
/** * `test.c` - Contains a unit-test suite for each library **/
/** **/
/** `CLM_LIBS.h` relies only on the C standard library and compiles without **/
/** warnings using the GCC parameters `-std=c99 -Wall -Wextra -pedantic **/
/** -Wformat-overflow=0`. More over, the code has been tested using **/
/** `valgrind --leak-check=full` reporting no memory leaks. **/
/** **/
/** The standard libraries used are (in alphabetical order): **/
/** **/
#include <assert.h> /* Include assertions unless NDEBUG is defined. */
#include <float.h> /* Floating point limits. */
#include <limits.h> /* Integer limits. */
#include <stdbool.h> /* Bool type and {true, false} values. */
#include <stdint.h> /* Fixed width integer types. */
#include <stdio.h> /* Input and output functions. */
#include <stdlib.h> /* Memory allocation and random functions. */
#include <string.h> /* The size_t type and string functions. */
#include <time.h> /* Time and calendar functions. */
/** **/
/** *********************************************************************** **/
/** **/
/** ## CODE LICENSE **/
/** **/
/** This is free and unencumbered software released into the public domain. **/
/** **/
/** Anyone is free to copy, modify, publish, use, compile, sell, or **/
/** distribute this software, either in source code form or as a compiled **/
/** binary, for any purpose, commercial or non-commercial, and by any **/
/** means. **/
/** **/
/** In jurisdictions that recognize copyright laws, the author or authors **/
/** of this software dedicate any and all copyright interest in the **/
/** software to the public domain. We make this dedication for the benefit **/
/** of the public at large and to the detriment of our heirs and **/
/** successors. We intend this dedication to be an overt act of **/
/** relinquishment in perpetuity of all present and future rights to this **/
/** software under copyright law. **/
/** **/
/** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, **/
/** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF **/
/** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. **/
/** IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR **/
/** OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, **/
/** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR **/
/** OTHER DEALINGS IN THE SOFTWARE. **/
/** **/
/** For more information, please refer to <http://unlicense.org/> **/
/** **/
/** *********************************************************************** **/
/** **/
/** ## THE MACROS **/
/** **/
/** Each macro generates a collection of related functions and typedefs. **/
/** **/
/** All the macros have an optional parameter `prefix` that allows the **/
/** user to change the name of the functions and data types so they don't **/
/** crash with other user-defined functions/types or with different calls **/
/** to the same macro. **/
/** **/
/** Some of the macros require two mandatory parameters (`type` & `less`) **/
/** that are used to build generic functions tailored to that data type. **/
/** **/
/** The `type` parameter could be any standard or user-defined data type. **/
/** **/
/** The `less` parameter should be the name (NOT A POINTER, JUST THE NAME) **/
/** of a comparing function/macro for the corresponding data type. **/
/** **/
/** The `bool less(const type x, const type y)` function must accept two **/
/** `const type` values and return: **/
/** **/
/** * `less(x, y) == true` if `x < y` **/
/** * `less(x, y) == false` if `x >= y` **/
/** **/
/** **Example:** **/
/** **/
/** #include "CLM_LIBS.h" **/
/** **/
/** #define LESS_NUM(i, j) ((i) < (j)) **/
/** **/
/** typedef struct pair { int i; double d; } pair_t; **/
/** **/
/** bool less_pair(const pair_t p1, pair_t p2) { **/
/** return (p1.i < p2.i || (p1.i == p2.i && p1.d < p2.d)); **/
/** } **/
/** **/
/** IMPORT_CLM_RAND() **/
/** IMPORT_CLM_ARRAY(int, LESS_NUM, int_) **/
/** IMPORT_CLM_ARRAY(double, LESS_NUM, dbl_) **/
/** IMPORT_CLM_STREE(pair_t, less_pair, ) **/
/** **/
/** int main(void) { **/
/** **/
/** pair_t pair; **/
/** size_t i, N = 10; **/
/** stree tree = NULL; **/
/** int_array A = int_array_new(N); **/
/** dbl_array B = dbl_array_new(N); **/
/** **/
/** printf("\nRANDOM:\n"); **/
/** for (i = 0; i < N; i++) { **/
/** A[i] = rand_int(100); **/
/** B[i] = rand_double(100); **/
/** printf("\t(%d, %f)\n", A[i], B[i]); **/
/** } **/
/** **/
/** printf("\nLEXICOGRAPHICALLY SORTED:\n"); **/
/** for (i = 0; i < N; i++) { **/
/** pair.i = A[i]; **/
/** pair.d = B[i]; **/
/** stree_insert(&tree, pair); **/
/** } **/
/** stree_min(&tree); **/
/** while (tree) { **/
/** pair = stree_pop(&tree); **/
/** printf("\t(%d, %f)\n", pair.i, pair.d); **/
/** } **/
/** **/
/** printf("\nINDEPENDENTLY SORTED:\n"); **/
/** int_array_sort(A, N); **/
/** dbl_array_sort(B, N); **/
/** for (i = 0; i < N; i++) { printf("\t(%d, %f)\n", A[i], B[i]); } **/
/** **/
/** free(A); **/
/** free(B); **/
/** } **/
/** **/
#ifndef CLM_LIBS
/** ********************************************************************* **/
/** **/
/** ### CLM_LIBS **/
/** **/
/** Contains the version number (= date) of this release of CLM_LIBS. **/
/** **/
#define CLM_LIBS 20240815
/** ********************************************************************* **/
/** **/
/** ### CLM_TIME **/
/** **/
/** A set of time-related and date-related functions. **/
/** **/
#define IMPORT_CLM_TIME(prefix) \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### time_elapsed **/ \
/** **/ \
/** Returns a `double` with the number of seconds elapsed since the **/ \
/** last time you executed: `crono = clock();` **/ \
/** **/ \
/** **Example:** Compare the performance of two functions with: **/ \
/** **/ \
/** clock_t crono = clock(); **/ \
/** Function_1(); **/ \
/** printf("Function 1 = %.3f sec.\n", time_elapsed(crono)); **/ \
/** **/ \
/** crono = clock(); **/ \
/** Function_2(); **/ \
/** printf("Function 2 = %.3f sec.\n", time_elapsed(crono)); **/ \
/** **/ \
static inline double prefix##time_elapsed(const clock_t crono) { \
\
return ((double) (clock() - crono)) / CLOCKS_PER_SEC; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### time_pause **/ \
/** **/ \
/** Flushes the `stdin`, prints `message` in the `stdout` and then **/ \
/** reads the `stdin` until a `\n` or a `EOF` appears. **/ \
/** **/ \
/** **Warning:** If `message == NULL` prints the default message: **/ \
/** **/ \
/** ">> Press return to resume <<\n" **/ \
/** **/ \
/** **Example:** Pause the program until the user hits return with: **/ \
/** **/ \
/** show_results(); **/ \
/** time_pause("\t\tPAUSE: Press return to resume.\n"); **/ \
/** show_more_results(); **/ \
/** **/ \
static inline void prefix##time_pause(const char* message) { \
\
int c; \
\
fflush(stdin); \
\
if (message) { fprintf(stdout, "%s", message); } \
else { fprintf(stdout, ">> Press return to resume <<\n"); } \
fflush(stdout); \
\
do { c = getc(stdin); } while (c != '\n' && c != EOF); \
clearerr(stdin); \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### time_stamp **/ \
/** **/ \
/** Returns a `\0` ended string with a timestamp formated as follows: **/ \
/** **/ \
/** * The `Year ` will be included if the 6th bit of `format` is 1. **/ \
/** * The `Month ` will be included if the 5th bit of `format` is 1. **/ \
/** * The `Day ` will be included if the 4th bit of `format` is 1. **/ \
/** * The `hour ` will be included if the 3rd bit of `format` is 1. **/ \
/** * The `minute` will be included if the 2nd bit of `format` is 1. **/ \
/** * The `second` will be included if the 1st bit of `format` is 1. **/ \
/** * The output will be "machine friendly" if `format >= 0`. **/ \
/** * The output will be "human friendly" if `format < 0`. **/ \
/** **/ \
/** Some useful examples: **/ \
/** **/ \
/** * `get_timestamp( 32+16+8+4+2+1);` returns `"YYYYMMDDhhmmss"` **/ \
/** * `get_timestamp( 32+16+8+4+2); ` returns `"YYYYMMDDhhmm"` **/ \
/** * `get_timestamp( 32+16+8); ` returns `"YYYYMMDD"` **/ \
/** * `get_timestamp( 4+2+1);` returns `"hhmmss"` **/ \
/** * `get_timestamp(-32-16-8-4-2-1);` returns `"YYYY/MM/DD hh:mm:ss"` **/ \
/** * `get_timestamp(-32-16-8-4-2); ` returns `"YYYY/MM/DD hh:mm"` **/ \
/** * `get_timestamp(-32-16-8); ` returns `"YYYY/MM/DD"` **/ \
/** * `get_timestamp(-32-16); ` returns `"YYYY/MM"` **/ \
/** * `get_timestamp( -16-8-4-2-1);` returns `"MM/DD hh:mm:ss"` **/ \
/** * `get_timestamp( -16-8-4-2); ` returns `"MM/DD hh:mm"` **/ \
/** * `get_timestamp( -16-8); ` returns `"MM/DD"` **/ \
/** * `get_timestamp( -4-2-1);` returns `"hh:mm:ss"` **/ \
/** * `get_timestamp( -4-2); ` returns `"hh:mm"` **/ \
/** **/ \
/** **Warning:** The user should free the string after using it. **/ \
/** **/ \
/** **Warning:** The case `format == 0` defaults to `format == 63`. **/ \
/** **/ \
/** **Example:** Output `MyString` in a timestamped file with: **/ \
/** **/ \
/** char filename[36]; **/ \
/** char *timestamp = time_stamp(0); **/ \
/** **/ \
/** sprintf(filename, "output_%s.txt", timestamp); **/ \
/** FILE *MyOutput = fopen(filename, "a"); **/ \
/** fprintf(MyOutput, MyString); **/ \
/** **/ \
/** fclose(MyOutput); **/ \
/** free(timestamp); **/ \
/** **/ \
static inline char *prefix##time_stamp(const int format) { \
\
time_t now = time(NULL); \
struct tm tm = *localtime(&now); \
char *timestamp = (char *) malloc(20 * sizeof(char)); \
\
int f = (!format) ? (1<<6)-1 : (format > 0) ? (format) : -(format); \
\
char Y[5] = "", M[3] = "", D[3] = "", h[3] = "", m[3] = "", s[3] = ""; \
char YM[2] = "", MD[2] = "", Dh[2] = "", hm[2] = "", ms[2] = ""; \
\
if (timestamp) { \
if (f & 32) { sprintf(Y, "%04d",tm.tm_year+1900); } \
if (f & 16) { sprintf(M, "%02d",tm.tm_mon+1); } \
if (f & 8) { sprintf(D, "%02d",tm.tm_mday); } \
if (f & 4) { sprintf(h, "%02d",tm.tm_hour); } \
if (f & 2) { sprintf(m, "%02d",tm.tm_min); } \
if (f & 1) { sprintf(s, "%02d",tm.tm_sec); } \
\
if (format < 0) { \
if ((f & 16) && (f & 32)) { sprintf(YM, "/"); } \
if ((f & 8) && (f & 48)) { sprintf(MD, "/"); } \
if ((f & 7) && (f > 7)) { sprintf(Dh, " "); } \
if ((f & 2) && (f & 4)) { sprintf(hm, ":"); } \
if ((f & 1) && (f & 6)) { sprintf(ms, ":"); } \
} \
\
sprintf(timestamp, "%s%s%s%s%s%s%s%s%s%s%s", \
Y, YM, M, MD, D, Dh, h, hm, m, ms, s); \
} \
\
return timestamp; \
} \
\
/** ********************************************************************* **/
/** **/
/** ### CLM_RAND **/
/** **/
/** A set of random and quasi-random number generators. **/
/** **/
#define IMPORT_CLM_RAND(prefix) \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### rand_int **/ \
/** **/ \
/** Returns an uniformly random `int` in the range `[0, n)`. **/ \
/** **/ \
/** **Warning:** Parameter `n` must satisfy `RAND_MAX >= n > 0`. **/ \
/** **/ \
/** **Example:** Print 10 random `int` in the range `[A, B]` with: **/ \
/** **/ \
/** size_t i; **/ \
/** for (i = 0; i < 10; i++) { printf("%d ", A+rand_int(B-A+1)); } **/ \
/** **/ \
static inline int prefix##rand_int(const int n) { \
\
/* Preconditions */ \
assert(n > 0); \
assert(RAND_MAX >= n); \
\
/* Monte-Carlo uniformly random generator */ \
int r, range = RAND_MAX - (RAND_MAX % n); \
do { r = rand(); } while (r >= range); \
return r % n; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### rand_size_t **/ \
/** **/ \
/** Returns an uniformly random `size_t` in the range `[0, n)`. **/ \
/** **/ \
/** **Warning:** Parameter `n` must satisfy `RAND_MAX >= n > 0`. **/ \
/** **/ \
/** **Example:** Select a random element from an array of size N with: **/ \
/** **/ \
/** type elem = MyArray[rand_size_t(N)]; **/ \
/** **/ \
static inline size_t prefix##rand_size_t(const size_t n) { \
\
/* Preconditions */ \
assert(n > 0); \
assert(RAND_MAX >= n); \
\
/* Monte-Carlo uniformly random generator */ \
size_t r, range = RAND_MAX - (RAND_MAX % n); \
do { r = rand(); } while (r >= range); \
return r % n; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### rand_double **/ \
/** **/ \
/** Returns an uniformly random `int` in the range `[0.0, n)`. **/ \
/** **/ \
/** **Warning:** Parameter `n` must satisfy `n > DLB_EPSILON`. **/ \
/** **/ \
/** **Example:** Print 10 random `double` in the range `[A, B)` with: **/ \
/** **/ \
/** size_t i; **/ \
/** for (i = 0; i < 10; i++) { printf("%f ", A+rand_double(B-A)); } **/ \
/** **/ \
static inline double prefix##rand_double(const double n) { \
\
/* Preconditions */ \
assert(n > DBL_EPSILON); \
\
/* Uniformly random generator */ \
return n * ((double) rand() / (double) RAND_MAX); \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### rand_halton **/ \
/** **/ \
/** Returns a quasi-random number in the range `[0.0, 1.0)`. **/ \
/** **/ \
/** More specifically, returns the `n`-th element of the Halton **/ \
/** low-discrepancy sequence that has the `base` as a base. **/ \
/** **/ \
/** In general it is advisable to use small prime numbers as `base`. **/ \
/** In particular, if you need to produce quasi-random D-dimensional **/ \
/** points, you should use `D` coprime numbers as 'base', one for each **/ \
/** dimension (see example below). **/ \
/** **/ \
/** **Warning:** Parameter `base` must satisfy `base > 1`. **/ \
/** **/ \
/** **Warning:** The algorithm is deterministic, which means that for **/ \
/** a fixed `(base, n)` input, it will always provide the same output. **/ \
/** **/ \
/** **Example:** Get 100 quasi-random 3D points with: **/ \
/** **/ \
/** double *X = (double *) malloc(100 * sizeof(double)); **/ \
/** double *Y = (double *) malloc(100 * sizeof(double)); **/ \
/** double *Z = (double *) malloc(100 * sizeof(double)); **/ \
/** if (X && Y && Z) { **/ \
/** for (size_t i = 0; i < 100; i++) { **/ \
/** X[i] = x_min + (x_max-x_min)*rand_halton(2, i); **/ \
/** Y[i] = y_min + (y_max-y_min)*rand_halton(3, i); **/ \
/** Z[i] = z_min + (z_max-z_min)*rand_halton(5, i); **/ \
/** } **/ \
/** } **/ \
/** **/ \
static inline double prefix##rand_halton(const size_t base, size_t n) { \
\
/* Precondition */ \
assert(base > 1); \
\
/* Get the `n`-th element of the Halton Sequence of base `base` */ \
double den = 1.0; \
double num = 0.0; \
while (n) { \
den = den * base; \
num = num * base + (n % base); \
n /= base; \
} \
return num / den; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### rand_color **/ \
/** **/ \
/** Returns a random RGB color with the same Saturation and Brightness **/ \
/** (but different Hue) than the RGB color provided. **/ \
/** **/ \
/** More specifically, generates a low discrepancy sequence of colors **/ \
/** based on the additive recurrence: **/ \
/** **/ \
/** Hue[n] = (Hue[n-1] + (phi-1)) % 1.0 **/ \
/** **/ \
/** where Hue is taken in the [0.0, 1.0) range and: **/ \
/** **/ \
/** phi = (1.0 + sqrt(5.0)) / 2.0 = 1.61803398874989484820458683436 **/ \
/** **/ \
/** **Warning:** `r`, `g` and `b` must be integers in [0, 255]. **/ \
/** **/ \
/** **Warning:** The algorithm is deterministic, which means that for **/ \
/** a fixed input color, it will always provide the same output color. **/ \
/** **/ \
/** **Example:** Generate 5 random colors with: **/ \
/** **/ \
/** int r = 255; **/ \
/** int g = 135; **/ \
/** int b = 0; **/ \
/** int R[5]; G[5]; B[5]; **/ \
/** for (size_t i = 0; i < 5; i++) { **/ \
/** rand_color(&r, &g, &b); **/ \
/** R[i] = r; G[i] = g; B[i] = b; **/ \
/** } **/ \
/** **/ \
static inline void prefix##rand_color(int *r, int *g, int *b) { \
\
/* Preconditions */ \
assert(0 <= *r && *r < 256); \
assert(0 <= *g && *g < 256); \
assert(0 <= *b && *b < 256); \
\
double rr = ((double) *r) / 256.0; \
double gg = ((double) *g) / 256.0; \
double bb = ((double) *b) / 256.0; \
double h,s,v, f, phi = 0.61803398874989484820458683436; \
double max, min, dif; \
int i; \
\
/*** RGB to HSV conversion *******************************************/ \
/* */ \
/* from (r,g,b) in [0,1)x[0,1)x[0,1) to (h,s,v) in [0,1)x[0,1)x[0,1) */ \
/* */ \
max = (gg > bb) ? ((rr > gg) ? rr : gg) : ((rr > bb) ? rr : bb); \
min = (gg < bb) ? ((rr < gg) ? rr : gg) : ((rr < bb) ? rr : bb); \
dif = max-min; \
if (max > 0.0 && dif > 0.0) { \
v = max; \
s = dif / max; \
if (rr == max) { h = ( (gg-bb)/(2.0*dif)) / 3.0; } \
else if (gg == max) { h = (1.0 + (bb-rr)/(2.0*dif)) / 3.0; } \
else { h = (2.0 + (rr-gg)/(2.0*dif)) / 3.0; } \
if (h < 0.0) { h += 1.0; } \
} else { v = max; h = s = 0.0; } \
\
\
/* Get next quasi-random Hue value */ \
h = (h + phi); \
if (h >= 1.0) { h -= 1.0; } \
\
\
/*** HSV to RGB conversion *******************************************/ \
/* */ \
/* from (h,s,v) in [0,1)x[0,1)x[0,1) to (r,g,b) in [0,1)x[0,1)x[0,1) */ \
/* */ \
i = (int) (6.0*h); \
f = 6.0*h - ((double) i); \
if (i == 0) { rr = v; gg = v*(1-s*(1-f)); bb = v*(1-s); } \
else if (i == 2) { gg = v; bb = v*(1-s*(1-f)); rr = v*(1-s); } \
else if (i == 4) { bb = v; rr = v*(1-s*(1-f)); gg = v*(1-s); } \
else if (i == 1) { rr = v*(1-s*f); gg = v; bb = v*(1-s); } \
else if (i == 3) { gg = v*(1-s*f); bb = v; rr = v*(1-s); } \
else if (i == 5) { bb = v*(1-s*f); rr = v; gg = v*(1-s); } \
\
\
/* Store the new RGB values */ \
*r = (int) (rr * 256); \
*g = (int) (gg * 256); \
*b = (int) (bb * 256); \
} \
\
/** ********************************************************************* **/
/** **/
/** ### CLM_PRINTF **/
/** **/
/** A set of formatting functions for the standard terminal output. **/
/** **/
#define IMPORT_CLM_PRINTF(prefix) \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_reset **/ \
/** **/ \
/** Resets all formating parameters of printf to their default values. **/ \
/** **/ \
/** **Example:** Give your command line a "retro look" with: **/ \
/** **/ \
/** printf_reset(); **/ \
/** printf_set_back_color(0x00, 0x00, 0x00); **/ \
/** printf_set_text_color(0x33, 0xFF, 0x00); **/ \
/** **/ \
static inline void prefix##printf_reset() { printf("\033[0m"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_delete **/ \
/** **/ \
/** Deletes everything from the cursor position to the end of the line. **/ \
/** **/ \
/** **Example:** Remove the last 2 lines with: **/ \
/** **/ \
/** printf_move(0,-1); **/ \
/** printf_delete(); **/ \
/** printf_move(0,-1); **/ \
/** printf_delete(); **/ \
/** **/ \
/** **Example:** Erase the last 5 characters with: **/ \
/** **/ \
/** printf_move(-5,0); **/ \
/** printf_delete(); **/ \
/** **/ \
static inline void prefix##printf_delete() { printf("\033[K"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_bold **/ \
/** **/ \
/** Sets the printf function in boldface mode. **/ \
/** **/ \
/** **Example:** Print the string `txt` in boldface with: **/ \
/** **/ \
/** printf_set_bold(); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_bold() { printf("\033[1m"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_light **/ \
/** **/ \
/** Sets the printf function in lightface mode. **/ \
/** **/ \
/** **Example:** Print the string `txt` in lightface with: **/ \
/** **/ \
/** printf_set_light(); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_light() { printf("\033[2m"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_strike **/ \
/** **/ \
/** Sets the printf function in strikethrough mode. **/ \
/** **/ \
/** **Example:** Print the string `txt` striked with: **/ \
/** **/ \
/** printf_set_strike(); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_strike() { printf("\033[9m"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_underline **/ \
/** **/ \
/** Sets the printf function in underline mode. **/ \
/** **/ \
/** **Example:** Print the string `txt` underlined with: **/ \
/** **/ \
/** printf_set_underline(); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_underline() { printf("\033[4m"); } \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_move **/ \
/** **/ \
/** Moves the cursor to the relative position defined by `(dx,dy)`. **/ \
/** **/ \
/** **Warning:** Text will be overwritten from that position. **/ \
/** **/ \
/** **Warning:** Negative movement goes towards the upper-left corner. **/ \
/** **/ \
/** **Example:** Remove the last 2 lines with: **/ \
/** **/ \
/** printf_move(0,-1); **/ \
/** printf_delete(); **/ \
/** printf_move(0,-1); **/ \
/** printf_delete(); **/ \
/** **/ \
/** **Example:** Erase the last 5 characters with: **/ \
/** **/ \
/** printf_move(-5,0); **/ \
/** printf_delete(); **/ \
/** **/ \
static inline void prefix##printf_move(const int dx, const int dy) { \
if (dy < 0) { printf("\033[%dA", -dy); } \
if (dy > 0) { printf("\033[%dB", dy); } \
if (dx > 0) { printf("\033[%dC", dx); } \
if (dx < 0) { printf("\033[%dD", -dx); } \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_text_grey **/ \
/** **/ \
/** Sets a greyscale text color for the printf function. **/ \
/** **/ \
/** The greyscale palette goes from black (`0`) to white (`23`). **/ \
/** **/ \
/** **Warning:** `grey` must be a integer in the range [0, 23]. **/ \
/** **/ \
/** **Example:** Print the string `txt` in white with: **/ \
/** **/ \
/** printf_set_text_grey(23); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_text_grey(const int grey) { \
\
/* Preconditions: */ \
assert(0 <= grey && grey < 24); \
\
printf("\033[38;5;%dm", 232 + grey); \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_back_grey **/ \
/** **/ \
/** Sets a greyscale background color for the printf function. **/ \
/** **/ \
/** The greyscale palette goes from black (`0`) to white (`23`). **/ \
/** **/ \
/** **Warning:** `grey` must be a integer in the range [0, 23]. **/ \
/** **/ \
/** **Example:** Print the string `txt` on a white background with: **/ \
/** **/ \
/** printf_set_back_grey(23); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_back_grey(const int grey) { \
\
/* Preconditions: */ \
assert(0 <= grey && grey < 24); \
\
printf("\033[48;5;%dm", 232 + grey); \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_text_color **/ \
/** **/ \
/** Sets the color of the text for the printf function. **/ \
/** **/ \
/** The actual color of the text will be the closest color to `(r,g,b)` **/ \
/** in the web-safe palette: `[0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF]^3` **/ \
/** **/ \
/** **Warning:** `r`, `g` and `b` must be integers in `[0, 255]`. **/ \
/** **/ \
/** **Example:** Print the string `txt` in red with: **/ \
/** **/ \
/** printf_set_text_color(0xFF, 0x00, 0x00); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_text_color(const int r, const int g, \
const int b) { \
/* Preconditions: */ \
assert(0 <= r && r < 256); \
assert(0 <= g && g < 256); \
assert(0 <= b && b < 256); \
\
int rr = (r+25) / 51; \
int gg = (g+25) / 51; \
int bb = (b+25) / 51; \
printf("\033[38;5;%dm", (rr*36) + (gg*6) + bb + 16); \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### printf_set_back_color **/ \
/** **/ \
/** Sets the color of the background for the printf function. **/ \
/** **/ \
/** The actual background color will be the closest color to `(r,g,b)` **/ \
/** in the web-safe palette: `[0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF]^3` **/ \
/** **/ \
/** **Warning:** `r`, `g` and `b` must be integers in `[0, 255]`. **/ \
/** **/ \
/** **Example:** Print the string `txt` on a blue background with: **/ \
/** **/ \
/** printf_set_back_color(0, 0, 255); **/ \
/** printf("%s", txt); **/ \
/** printf_reset(); **/ \
/** **/ \
static inline void prefix##printf_set_back_color(const int r, const int g, \
const int b) { \
/* Preconditions: */ \
assert(0 <= r && r < 256); \
assert(0 <= g && g < 256); \
assert(0 <= b && b < 256); \
\
int rr = (r+25) / 51; \
int gg = (g+25) / 51; \
int bb = (b+25) / 51; \
printf("\033[48;5;%dm", (rr*36) + (gg*6) + bb + 16); \
} \
\
/** ********************************************************************* **/
/** **/
/** ### CLM_HASH **/
/** **/
/** A set of reversible bit-mixer functions for unsigned integers. **/
/** **/
#define IMPORT_CLM_HASH(prefix) \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### hash_mix32 **/ \
/** **/ \
/** Given a `uint32_t` value returns another `uint32_t` value that can **/ \
/** be used as a (non-cryptographic) hash of the first value. **/ \
/** **/ \
/** On average, changing a single bit in the input changes each bit of **/ \
/** the output with probability 1/2, so, this deterministic function **/ \
/** could be used as a non-cryptographic pseudorandom number generator. **/ \
/** **/ \
/** This function is based on `triple32` by Chris Wellons, see: **/ \
/** https://nullprogram.com/blog/2018/07/31/ **/ \
/** **/ \
/** **Warning:** Zero is a fixed point by design. **/ \
/** **/ \
/** **Warning:** This function is reversible by design. **/ \
/** **/ \
/** **Example:** Find the index of `elem` in a `2^K` hash table with: **/ \
/** **/ \
/** int index = hash_mix32(elem) & ((1 << K)-1); **/ \
/** **/ \
/** **Example:** Generate 5 pseudorandom `uint32_t` numbers with: **/ \
/** **/ \
/** uint32_t N[5]; **/ \
/** uint32_t SEED = (uint32_t) 314159285; // change it! **/ \
/** uint32_t PHI_32 = (uint32_t) 0x9e3779b9; // 2^32 * Phi **/ \
/** for (int i = 0; i < 5; i++) { **/ \
/** N[i] = hash_mix32(SEED + (i+1) * PHI_32); **/ \
/** } **/ \
/** **/ \
static inline uint32_t prefix##hash_mix32(uint32_t h) { \
\
h ^= (h >> 17); \
h *= (uint32_t) 0xed5ad4bb; \
h ^= (h >> 11); \
h *= (uint32_t) 0xac4c1b51; \
h ^= (h >> 15); \
h *= (uint32_t) 0x31848bab; \
h ^= (h >> 14); \
\
return h; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### hash_unmix32 **/ \
/** **/ \
/** Given a `uint32_t` value returns another `uint32_t` value that can **/ \
/** be used as a (non-cryptographic) hash of the first value. **/ \
/** **/ \
/** This function is the inverse of `hash_mix32` and has the very same **/ \
/** properties. See `hash_mix32` documentation for the details. **/ \
/** **/ \
/** **Warning:** Zero is a fixed point by design. **/ \
/** **/ \
/** **Warning:** This function is reversible by design. **/ \
/** **/ \
/** **Example:** Reverse a hash operation with: **/ \
/** **/ \
/** assert(hash_unmix32(hash_mix32(i)) == i); **/ \
/** assert(hash_mix32(hash_unmix32(i)) == i); **/ \
/** **/ \
static inline uint32_t prefix##hash_unmix32(uint32_t h) { \
\
h ^= (h >> 14) ^ (h >> 28); \
h *= (uint32_t) 0x32b21703; \
h ^= (h >> 15) ^ (h >> 30); \
h *= (uint32_t) 0x469e0db1; \
h ^= (h >> 11) ^ (h >> 22); \
h *= (uint32_t) 0x79a85073; \
h ^= (h >> 17); \
\
return h; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### hash_mix64 **/ \
/** **/ \
/** Given a `uint64_t` value returns another `uint64_t` value that can **/ \
/** be used as a (non-cryptographic) hash of the first value. **/ \
/** **/ \
/** On average, changing a single bit in the input changes each bit of **/ \
/** the output with probability 1/2, so, this deterministic function **/ \
/** could be used as a non-cryptographic pseudorandom number generator. **/ \
/** **/ \
/** This function is based on `splitmix64` by Sebastiano Vigna, see: **/ \
/** http://xoshiro.di.unimi.it/splitmix64.c **/ \
/** **/ \
/** **Warning:** Zero is a fixed point by design. **/ \
/** **/ \
/** **Warning:** This function is reversible by design. **/ \
/** **/ \
/** **Example:** Find the index of `elem` in a `2^K` hash table with: **/ \
/** **/ \
/** size_t index = hash_mix64(elem) & ((1 << K)-1); **/ \
/** **/ \
/** **Example:** Generate 5 pseudorandom `uint64_t` numbers with: **/ \
/** **/ \
/** uint64_t N[5]; **/ \
/** uint64_t SEED = (uint64_t) 314159285; // change it! **/ \
/** uint64_t PHI_64 = (uint64_t) 0x9e3779b97f4a7c15; // 2^64 * Phi **/ \
/** for (int i = 0; i < 5; i++) { **/ \
/** N[i] = hash_mix64(SEED + (i+1) * PHI_64); **/ \
/** } **/ \
/** **/ \
static inline uint64_t prefix##hash_mix64(uint64_t h) { \
\
h ^= (h >> 30); \
h *= (uint64_t) 0xbf58476d1ce4e5b9; \
h ^= (h >> 27); \
h *= (uint64_t) 0x94d049bb133111eb; \
h ^= (h >> 31); \
\
return h; \
} \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### hash_unmix64 **/ \
/** **/ \
/** Given a `uint64_t` value returns another `uint64_t` value that can **/ \
/** be used as a (non-cryptographic) hash of the first value. **/ \
/** **/ \
/** This function is the inverse of `hash_mix64` and has the very same **/ \
/** properties. See `hash_mix64` documentation for the details. **/ \
/** **/ \
/** **Warning:** Zero is a fixed point by design. **/ \
/** **/ \
/** **Warning:** This function is reversible by design. **/ \
/** **/ \
/** **Example:** Reverse a hash operation with: **/ \
/** **/ \
/** assert(hash_unmix64(hash_mix64(i)) == i); **/ \
/** assert(hash_mix64(hash_unmix64(i)) == i); **/ \
/** **/ \
static inline uint64_t prefix##hash_unmix64(uint64_t h) { \
\
h ^= (h >> 31) ^ (h >> 62); \
h *= (uint64_t) 0x319642b2d24d8ec3; \
h ^= (h >> 27) ^ (h >> 54); \
h *= (uint64_t) 0x96de1b173f119089; \
h ^= (h >> 30) ^ (h >> 60); \
\
return h; \
} \
\
/** ********************************************************************* **/
/** **/
/** ### CLM_DAMM **/
/** **/
/** A set of check digit functions using the Damm algorithm. **/
/** **/
#define IMPORT_CLM_DAMM(prefix) \
\
/** ******************************************************************* **/ \
/** **/ \
/** #### damm_dec **/ \
/** **/ \
/** Returns a the checksum character of the `\0`-terminated numeric **/ \
/** string `txt`. **/ \
/** **/ \
/** The algorithm guarantees that: **/ \
/** **/ \
/** damm_dec(txt ++ damm_dec(txt)) == '0' **/ \
/** **/ \
/** where `txt ++ c` is the concatenation of `txt` and `c`. **/ \
/** **/ \
/** **Warning:** All non-numeric characters will be ignored. **/ \
/** **/ \
/** **Example:** Add a checksum character to the string `s` with: **/ \
/** **/ \
/** size_t length = strlen(s); **/ \