summaryrefslogtreecommitdiff
path: root/source/kit/test.h
blob: ca2b7c0de33e29cc119a8524a56201e690489e45 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
//  ================================================================
//
//    test.h
//    https://guattari.tech/git/kit
//
//  Header-only unit-testing and microbenchmarks library for C.
//
//
//    - Define a unique KIT_TEST_FILE for each file to avoid name
//      collisions.
//
//    - Define KIT_TEST_IMPLEMENTATION to include the implementation.
//
//
//  Optional settings
//
//  - KIT_TESTS_SIZE_LIMIT
//  - KIT_TEST_ASSERTIONS_LIMIT
//  - KIT_BENCHS_SIZE_LIMIT
//  - KIT_BENCH_MAX_REPEATS
//  - KIT_BENCH_MAX_CYCLES
//  - KIT_BENCH_REPEATS_DEFAULT_1
//  - KIT_BENCH_REPEATS_DEFAULT_2
//
//
//  Usage example
//
//    //  foo.test.c
//    #define KIT_TEST_FILE foo //  This is required if you want to
//                              //  use multiple test files.
//    #include "test.h"
//    TEST("foo") {
//      REQUIRE(1);
//      REQUIRE_EQ(2 + 2, 4);
//    }
//
//    //  main.c
//    #define KIT_TEST_IMPLEMENTATION
//    #include "test.h"
//    int main(int argc, char **argv) {
//      return run_tests(argc, argv);
//    }
//
//  ================================================================
//
//  The MIT License
//
//  Copyright (c) 2022-2024 Mitya Selivanov
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use, copy,
//  modify, merge, publish, distribute, sublicense, and/or sell copies
//  of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  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 OR COPYRIGHT
//  HOLDERS 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.
//
//  ================================================================

#ifndef KIT_TEST_H
#define KIT_TEST_H

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _GNU_SOURCE
#  define _GNU_SOURCE
#endif

#include <stddef.h>
#include <stdint.h>

#ifndef KIT_TEST_FILE
#  define KIT_TEST_FILE kit_test
#endif

#ifndef KIT_TESTS_SIZE_LIMIT
#  define KIT_TESTS_SIZE_LIMIT 0x1000
#endif

#ifndef KIT_TEST_ASSERTIONS_LIMIT
#  define KIT_TEST_ASSERTIONS_LIMIT 0x50
#endif

#ifndef KIT_BENCHS_SIZE_LIMIT
#  define KIT_BENCHS_SIZE_LIMIT 200
#endif

#ifndef KIT_BENCH_MAX_REPEATS
#  define KIT_BENCH_MAX_REPEATS 4000
#endif

#ifndef KIT_BENCH_MAX_CYCLES
#  define KIT_BENCH_MAX_CYCLES 40
#endif

#ifndef KIT_BENCH_REPEATS_DEFAULT_1
#  define KIT_BENCH_REPEATS_DEFAULT_1 40
#endif

#ifndef KIT_BENCH_REPEATS_DEFAULT_2
#  define KIT_BENCH_REPEATS_DEFAULT_2 400
#endif

typedef void (*kit_test_report_fn)(int test_index, int line,
                                   int64_t value, int64_t expected);
typedef void (*kit_test_run_fn)(
    int kit_test_index_, kit_test_report_fn kit_test_report_fn_);

typedef struct {
  char const     *test_name;
  char const     *test_file;
  kit_test_run_fn test_fn;
  int             assertions;
  int             line[KIT_TEST_ASSERTIONS_LIMIT];
  int             status[KIT_TEST_ASSERTIONS_LIMIT];
  int64_t         value[KIT_TEST_ASSERTIONS_LIMIT];
  int64_t         expected[KIT_TEST_ASSERTIONS_LIMIT];
  int             signal;
} kit_test_case_t;

typedef struct {
  int             size;
  kit_test_case_t v[KIT_TESTS_SIZE_LIMIT];
} kit_tests_list_t;

extern kit_tests_list_t kit_tests_list;

#define KIT_TEST_CONCAT4_(a, b, c, d) a##b##c##d
#define KIT_TEST_CONCAT3_(a, b, c) KIT_TEST_CONCAT4_(a, b, _, c)

#ifdef __cplusplus
#  define KIT_TEST_ON_START_(f)                              \
    static void f(void);                                     \
    static int  KIT_TEST_CONCAT3_(_kit_test_init_, __LINE__, \
                                  f) = (f(), 0);             \
    static void f(void)
#else
#  ifdef _MSC_VER
#    pragma section(".CRT$XCU", read)
#    define KIT_TEST_ON_START_2_(f, p)                               \
      static void f(void);                                           \
      __declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f;       \
      __pragma(comment(linker, "/include:" p #f "_")) static void f( \
          void)
#    ifdef _WIN64
#      define KIT_TEST_ON_START_(f) KIT_TEST_ON_START_2_(f, "")
#    else
#      define KIT_TEST_ON_START_(f) KIT_TEST_ON_START_2_(f, "_")
#    endif
#  else
#    define KIT_TEST_ON_START_(f)                       \
      static void f(void) __attribute__((constructor)); \
      static void f(void)
#  endif
#endif

void kit_test_register(char const *name, char const *file,
                       kit_test_run_fn fn);

#define KIT_TEST(name)                                              \
  static void KIT_TEST_CONCAT3_(kit_test_run_, __LINE__,            \
                                KIT_TEST_FILE)(int,                 \
                                               kit_test_report_fn); \
  KIT_TEST_ON_START_(                                               \
      KIT_TEST_CONCAT3_(kit_test_case_, __LINE__, KIT_TEST_FILE)) { \
    kit_test_register(                                              \
        name, __FILE__,                                             \
        KIT_TEST_CONCAT3_(kit_test_run_, __LINE__, KIT_TEST_FILE)); \
  }                                                                 \
  static void KIT_TEST_CONCAT3_(kit_test_run_, __LINE__,            \
                                KIT_TEST_FILE)(                     \
      int kit_test_index_, kit_test_report_fn kit_test_report_fn_)

#define KIT_REQUIRE(...) \
  kit_test_report_fn_(kit_test_index_, __LINE__, (__VA_ARGS__), 1)

#define KIT_REQUIRE_EQ(...) \
  kit_test_report_fn_(kit_test_index_, __LINE__, __VA_ARGS__)

int kit_run_tests(int argc, char **argv);

typedef void (*kit_bench_set_repeats_limit_fn)(int bench_index,
                                               int repeats_limit);
typedef int (*kit_bench_loop_fn)(int bench_index);
typedef void (*kit_bench_begin_fn)(int bench_index);
typedef void (*kit_bench_end_fn)(int bench_index);

typedef void (*kit_bench_run_fn)(
    int                            kit_bench_index_,
    kit_bench_set_repeats_limit_fn kit_bench_set_repeats_limit_,
    kit_bench_loop_fn              kit_bench_loop_,
    kit_bench_begin_fn             kit_bench_begin_,
    kit_bench_end_fn               kit_bench_end_);

typedef struct {
  char const      *bench_name;
  char const      *bench_file;
  kit_bench_run_fn bench_fn;
  int64_t          sec[KIT_BENCH_MAX_REPEATS];
  int32_t          nsec[KIT_BENCH_MAX_REPEATS];
  int64_t          duration_nsec[KIT_BENCH_MAX_REPEATS];
  int64_t          duration_sorted_nsec[KIT_BENCH_MAX_REPEATS];
  int              repeats;
  int              cycles_size;
  int              cycles[KIT_BENCH_MAX_CYCLES];
  int              cycle;
  int              signal;
  int              ready;
} kit_benchmark_t;

typedef struct {
  int             size;
  kit_benchmark_t v[KIT_BENCHS_SIZE_LIMIT];
} kit_benchs_list_t;

extern kit_benchs_list_t kit_benchs_list;

void kit_bench_register(char const *name, char const *file,
                        kit_bench_run_fn fn);

#define KIT_BENCHMARK(name)                                          \
  static void KIT_TEST_CONCAT3_(kit_bench_run_, __LINE__,            \
                                KIT_TEST_FILE)(                      \
      int, kit_bench_set_repeats_limit_fn, kit_bench_loop_fn,        \
      kit_bench_begin_fn, kit_bench_end_fn);                         \
  KIT_TEST_ON_START_(                                                \
      KIT_TEST_CONCAT3_(kit_benchmark_, __LINE__, KIT_TEST_FILE)) {  \
    kit_bench_register(                                              \
        name, __FILE__,                                              \
        KIT_TEST_CONCAT3_(kit_bench_run_, __LINE__, KIT_TEST_FILE)); \
  }                                                                  \
  static void KIT_TEST_CONCAT3_(kit_bench_run_, __LINE__,            \
                                KIT_TEST_FILE)(                      \
      int                            kit_bench_index_,               \
      kit_bench_set_repeats_limit_fn kit_bench_set_repeats_limit_,   \
      kit_bench_loop_fn              kit_bench_loop_,                \
      kit_bench_begin_fn             kit_bench_begin_,               \
      kit_bench_end_fn               kit_bench_end_)

#define KIT_BENCHMARK_REPEAT(repeats_limit_) \
  kit_bench_set_repeats_limit_(kit_bench_index_, repeats_limit_)

#define KIT_BENCHMARK_BEGIN                   \
  while (kit_bench_loop_(kit_bench_index_)) { \
    kit_bench_begin_(kit_bench_index_);       \
    {

#define KIT_BENCHMARK_END           \
  }                                 \
  kit_bench_end_(kit_bench_index_); \
  }

//  FIXME
//
#define KIT_DO_NOT_OPTIMIZE(x)        \
  do {                                \
    volatile void *bench_ptr_ = &(x); \
    (void) bench_ptr_;                \
  } while (0)

int kit_run_benchmarks(int argc, char **argv);

#define TEST KIT_TEST
#define REQUIRE KIT_REQUIRE
#define REQUIRE_EQ KIT_REQUIRE_EQ
#define BENCHMARK KIT_BENCHMARK
#define BENCHMARK_REPEAT KIT_BENCHMARK_REPEAT
#define BENCHMARK_BEGIN KIT_BENCHMARK_BEGIN
#define BENCHMARK_END KIT_BENCHMARK_END
#define DO_NOT_OPTIMIZE KIT_DO_NOT_OPTIMIZE
#define test_register kit_test_register
#define run_tests kit_run_tests
#define bench_register kit_bench_register
#define run_benchmarks kit_run_benchmarks

#ifdef __cplusplus
}
#endif

#endif

#if defined(KIT_TEST_IMPLEMENTATION) && !defined(KIT_TEST_H_IMPL)
#define KIT_TEST_H_IMPL

#ifdef __cplusplus
extern "C" {
#endif

#ifndef KIT_TIME_H
#  define KIT_TIME_H

#  include <time.h>

#  ifndef TIME_UTC
#    define TIME_UTC 1
#  endif

#  ifdef KIT_REQUIRE_TIMESPEC_GET
#    ifndef WIN32_LEAN_AND_MEAN
#      define WIN32_LEAN_AND_MEAN 1
#    endif
#    include <windows.h>

#    define KIT_TIMESPEC_IMPL_UNIX_EPOCH_IN_TICKS \
      116444736000000000ull
#    define KIT_TIMESPEC_IMPL_TICKS_PER_SECONDS 10000000ull

static int timespec_get(struct timespec *ts, int base) {
  if (ts == NULL || base != TIME_UTC)
    return 0;

  FILETIME       ft;
  ULARGE_INTEGER date;
  LONGLONG       ticks;

  GetSystemTimeAsFileTime(&ft);
  date.HighPart = ft.dwHighDateTime;
  date.LowPart  = ft.dwLowDateTime;
  ticks         = (LONGLONG) (date.QuadPart -
                      KIT_TIMESPEC_IMPL_UNIX_EPOCH_IN_TICKS);
  ts->tv_sec    = ticks / KIT_TIMESPEC_IMPL_TICKS_PER_SECONDS;
  ts->tv_nsec   = (ticks % KIT_TIMESPEC_IMPL_TICKS_PER_SECONDS) * 100;

  return base;
}
#  endif

#endif

#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum {
  kit_white_,
  kit_blue_,
  kit_light_,
  kit_yellow_,
  kit_red_,
  kit_green_
};

static char const *kit_color_codes_[] = { "\x1b[38m", "\x1b[34m",
                                          "\x1b[37m", "\x1b[33m",
                                          "\x1b[31m", "\x1b[32m" };

static int kit_print_color_(int c) {
  return printf("%s", kit_color_codes_[c]);
}

static int kit_signums_[] = { SIGINT, SIGILL,  SIGABRT,
                              SIGFPE, SIGSEGV, SIGTERM };

static char const *kit_signames_[64];

static void kit_signames_init_(void) {
  memset(kit_signames_, 0, sizeof kit_signames_);
  kit_signames_[SIGINT]  = "Interactive attention signal";
  kit_signames_[SIGILL]  = "Illegal instruction";
  kit_signames_[SIGABRT] = "Abnormal termination";
  kit_signames_[SIGFPE]  = "Erroneous arithmetic operation";
  kit_signames_[SIGSEGV] = "Invalid access to storage";
  kit_signames_[SIGTERM] = "Termination request";
}

kit_tests_list_t kit_tests_list = { 0 };

static void kit_report_(int i, int line, int64_t value,
                        int64_t expected) {
  int n = kit_tests_list.v[i].assertions++;

  if (n >= KIT_TEST_ASSERTIONS_LIMIT)
    return;

  kit_tests_list.v[i].line[n]     = line;
  kit_tests_list.v[i].status[n]   = value == expected;
  kit_tests_list.v[i].value[n]    = value;
  kit_tests_list.v[i].expected[n] = expected;
}

static int64_t ns_to_ms(int64_t ns) {
  return (ns + 500000) / 1000000;
}

static int64_t sec_to_ms(int64_t sec) {
  return 1000 * sec;
}

void kit_test_register(char const *name, char const *file,
                       kit_test_run_fn fn) {
  int n = kit_tests_list.size++;
  if (n < KIT_TESTS_SIZE_LIMIT) {
    kit_tests_list.v[n].test_fn    = fn;
    kit_tests_list.v[n].test_name  = name;
    kit_tests_list.v[n].test_file  = file;
    kit_tests_list.v[n].assertions = 0;
  }
}

static jmp_buf kit_test_restore_execution;

static void kit_test_handle_signal(int signum) {
  longjmp(kit_test_restore_execution, signum);
}

static void kit_test_setup_signals() {
  for (int i = 0; i < sizeof kit_signums_ / sizeof *kit_signums_; i++)
    signal(kit_signums_[i], kit_test_handle_signal);
}

static int kit_run_test_(volatile int i) {
  int signum = setjmp(kit_test_restore_execution);

  if (signum != 0) {
    kit_tests_list.v[i].signal = signum;
    return 0;
  }

  kit_tests_list.v[i].test_fn(i, kit_report_);
  return 1;
}

int kit_run_tests(int argc, char **argv) {
  kit_signames_init_();

  int success_count         = 0;
  int fail_assertion_count  = 0;
  int total_assertion_count = 0;
  int status                = 0;
  int quiet                 = 0;
  int no_color              = 0;
  int line_width            = 20;
  int carriage_return       = 1;

  int i, j;

  char const *specific_test = NULL;

  kit_test_setup_signals();

  for (i = 0; i < argc; i++)
    if (strcmp("--no-term-color", argv[i]) == 0)
      no_color = 1;
    else if (strcmp("--no-carriage-return", argv[i]) == 0)
      carriage_return = 0;
    else if (strcmp("--quiet", argv[i]) == 0)
      quiet = 1;
    else if (strcmp("--match", argv[i]) == 0)
      specific_test = argv[++i];

  quiet && (no_color = 1);

  if (specific_test != NULL) {
    no_color || kit_print_color_(kit_light_);
    quiet || printf("Run tests matching ");
    no_color || kit_print_color_(kit_white_);
    quiet || printf("*%s*", specific_test);
    no_color || kit_print_color_(kit_light_);
    quiet || printf("\n\n");
  }

  char const *file        = NULL;
  ptrdiff_t   file_root   = -1;
  int         tests_total = 0;

  for (i = 0; i < kit_tests_list.size && i < KIT_TESTS_SIZE_LIMIT;
       i++) {
    if (specific_test != NULL &&
        strstr(kit_tests_list.v[i].test_name, specific_test) == NULL)
      continue;
    tests_total++;
    int l = 2 + (int) strlen(kit_tests_list.v[i].test_name);
    if (line_width < l)
      line_width = l;
  }

  if (tests_total > 0) {
    char const *s = kit_tests_list.v[0].test_file;

    for (j = 1; j < kit_tests_list.size && j < KIT_TESTS_SIZE_LIMIT;
         j++) {
      if (specific_test != NULL &&
          strstr(kit_tests_list.v[j].test_name, specific_test) ==
              NULL)
        continue;
      if (strcmp(s, kit_tests_list.v[j].test_file) == 0)
        continue;
      int k = 0;
      for (;
           s[k] != '\0' && kit_tests_list.v[j].test_file[k] != '\0' &&
           s[k] == kit_tests_list.v[j].test_file[k];
           k++) { }
      if (file_root == -1 || file_root > k)
        file_root = k;
    }

    if (file_root == -1) {
      for (i = 0; s[i] != '\0'; i++)
        if (s[i] == '/' || s[i] == '\\')
          file_root = i + 1;
    }
  }

  for (i = 0; i < kit_tests_list.size && i < KIT_TESTS_SIZE_LIMIT;
       i++) {
    if (specific_test != NULL &&
        strstr(kit_tests_list.v[i].test_name, specific_test) == NULL)
      continue;
    if (file == NULL ||
        strcmp(file, kit_tests_list.v[i].test_file) != 0) {
      if (file != NULL)
        quiet || printf("\n");
      file = kit_tests_list.v[i].test_file;
      no_color || kit_print_color_(kit_blue_);
      quiet || printf("* ");
      no_color || kit_print_color_(kit_white_);
      quiet || printf("%s\n", file + file_root);
    }

    !carriage_return || no_color || kit_print_color_(kit_yellow_);
    carriage_return || no_color || kit_print_color_(kit_light_);
    quiet || printf("` %s ", kit_tests_list.v[i].test_name);
    !carriage_return || quiet || printf("\r");
    quiet || fflush(stdout);

    struct timespec begin, end;
    timespec_get(&begin, TIME_UTC);

    int test_status = kit_run_test_(i);

    timespec_get(&end, TIME_UTC);
    int duration = (int) (ns_to_ms(end.tv_nsec - begin.tv_nsec) +
                          sec_to_ms(end.tv_sec - begin.tv_sec));

    for (j = 0; j < kit_tests_list.v[i].assertions &&
                j < KIT_TEST_ASSERTIONS_LIMIT;
         j++)
      if (kit_tests_list.v[i].status[j] == 0) {
        fail_assertion_count++;
        test_status = 0;
      }

    if (kit_tests_list.v[i].assertions > KIT_TEST_ASSERTIONS_LIMIT)
      test_status = 0;

    total_assertion_count += kit_tests_list.v[i].assertions;

    !carriage_return || no_color || kit_print_color_(kit_light_);
    !carriage_return || quiet ||
        printf("` %s ", kit_tests_list.v[i].test_name);

    int l = (int) strlen(kit_tests_list.v[i].test_name);
    quiet || printf("%*c", line_width - l, ' ');

    if (test_status == 0) {
      no_color || kit_print_color_(kit_red_);
      quiet || printf("FAIL");
      no_color || kit_print_color_(kit_light_);
      duration == 0 || quiet || printf(" %d ms", duration);
      quiet || printf("\n");
      status = 1;
    } else {
      no_color || kit_print_color_(kit_green_);
      quiet || printf("OK");
      no_color || kit_print_color_(kit_light_);
      duration == 0 || quiet || printf("   %d ms", duration);
      quiet || printf("\n");
      success_count++;
    }

    quiet || fflush(stdout);
  }

  no_color || kit_print_color_(kit_white_);
  quiet || printf("\n%d of %d tests passed.\n", success_count,
                  tests_total);
  quiet || printf("%d of %d assertions passed.\n\n",
                  total_assertion_count - fail_assertion_count,
                  total_assertion_count);

  no_color || kit_print_color_(kit_light_);

  if (!quiet && status != 0) {
    int have_kit_report_s = 0;

    for (i = 0; i < kit_tests_list.size && i < KIT_TESTS_SIZE_LIMIT;
         i++) {
      if (specific_test != NULL &&
          strstr(kit_tests_list.v[i].test_name, specific_test) ==
              NULL)
        continue;
      if (kit_tests_list.v[i].signal != 0) {
        int signum = kit_tests_list.v[i].signal;
        if (signum >= 0 &&
            signum < sizeof kit_signames_ / sizeof *kit_signames_ &&
            kit_signames_[signum] != NULL) {
          no_color || kit_print_color_(kit_light_);
          printf("Signal \"%s\" (%d) for \"", kit_signames_[signum],
                 signum);
          no_color || kit_print_color_(kit_white_);
          printf("%s", kit_tests_list.v[i].test_name);
          no_color || kit_print_color_(kit_light_);
          printf("\" in \"");
          no_color || kit_print_color_(kit_white_);

          printf("%s", kit_tests_list.v[i].test_file + file_root);
          no_color || kit_print_color_(kit_light_);
          printf("\"!\n");
        } else {
          no_color || kit_print_color_(kit_light_);
          printf("Unknown signal (%d) for \"", signum);
          no_color || kit_print_color_(kit_white_);
          printf("%s", kit_tests_list.v[i].test_name);
          no_color || kit_print_color_(kit_light_);
          printf("\" in \"");
          no_color || kit_print_color_(kit_white_);

          printf("%s", kit_tests_list.v[i].test_file + file_root);
          no_color || kit_print_color_(kit_light_);
          printf("\"!\n");
        }
        have_kit_report_s = 1;
      }
      if (kit_tests_list.v[i].assertions >
          KIT_TEST_ASSERTIONS_LIMIT) {
        no_color || kit_print_color_(kit_light_);
        printf("Too many assertions for \"");
        no_color || kit_print_color_(kit_white_);
        printf("%s", kit_tests_list.v[i].test_name);
        no_color || kit_print_color_(kit_light_);
        printf("\" in \"");
        no_color || kit_print_color_(kit_white_);

        printf("%s", kit_tests_list.v[i].test_file + file_root);
        no_color || kit_print_color_(kit_light_);
        printf("\"!\n");
        have_kit_report_s = 1;
      }
    }

    have_kit_report_s &&printf("\n");
  }

  if (!quiet && status != 0) {
    for (i = 0; i < kit_tests_list.size && i < KIT_TESTS_SIZE_LIMIT;
         i++) {
      if (specific_test != NULL &&
          strstr(kit_tests_list.v[i].test_name, specific_test) ==
              NULL)
        continue;

      if (kit_tests_list.v[i].assertions <= KIT_TEST_ASSERTIONS_LIMIT)
        for (j = 0; j < kit_tests_list.v[i].assertions; j++)
          if (!kit_tests_list.v[i].status[j]) {
            no_color || kit_print_color_(kit_light_);
            printf("Assertion on line ");
            no_color || kit_print_color_(kit_white_);
            printf("%d", kit_tests_list.v[i].line[j]);
            no_color || kit_print_color_(kit_light_);
            printf(" in \"");
            no_color || kit_print_color_(kit_white_);
            printf("%s", kit_tests_list.v[i].test_file + file_root);
            no_color || kit_print_color_(kit_light_);
            printf("\" failed.\n");
            no_color || kit_print_color_(kit_red_);
            printf(" -> ");
            no_color || kit_print_color_(kit_light_);
            printf("Got wrong value ");
            no_color || kit_print_color_(kit_white_);
            printf("%10lld",
                   (long long) kit_tests_list.v[i].value[j]);
            no_color || kit_print_color_(kit_light_);
            printf("  (");
            no_color || kit_print_color_(kit_white_);
            printf("0x%08llx",
                   (unsigned long long) kit_tests_list.v[i].value[j]);
            no_color || kit_print_color_(kit_light_);
            printf(")\n");
            no_color || kit_print_color_(kit_green_);
            printf(" -> ");
            no_color || kit_print_color_(kit_light_);
            printf("Expected value  ");
            no_color || kit_print_color_(kit_white_);
            printf("%10lld",
                   (long long) kit_tests_list.v[i].expected[j]);
            no_color || kit_print_color_(kit_light_);
            printf("  (");
            no_color || kit_print_color_(kit_white_);
            printf(
                "0x%08llx",
                (unsigned long long) kit_tests_list.v[i].expected[j]);
            no_color || kit_print_color_(kit_light_);
            printf(")\n\n");
          }
    }
  }

  if (kit_tests_list.size > KIT_TESTS_SIZE_LIMIT) {
    no_color || kit_print_color_(kit_light_);
    quiet || printf("Too many tests!\n\n");
    status = 1;
  }

  if (status == 0) {
    no_color || kit_print_color_(kit_green_);
    quiet || printf("OK\n");
  } else {
    no_color || kit_print_color_(kit_red_);
    quiet || printf("FAILED\n");
  }

  no_color || kit_print_color_(kit_light_);
  quiet || printf("\n");
  return status;
}

kit_benchs_list_t kit_benchs_list = { 0 };

static void bench_set_repeats_limit(int i, int repeats_limit) {
  if (kit_benchs_list.v[i].ready)
    return;
  if (kit_benchs_list.v[i].cycles_size >= KIT_BENCH_MAX_CYCLES)
    return;
  kit_benchs_list.v[i].cycles[kit_benchs_list.v[i].cycles_size] =
      repeats_limit;
  kit_benchs_list.v[i].cycles_size++;
}

static int bench_loop(int i) {
  if (!kit_benchs_list.v[i].ready)
    return 0;
  return kit_benchs_list.v[i].repeats <
         kit_benchs_list.v[i].cycles[kit_benchs_list.v[i].cycle];
}

static void bench_begin(int i) {
  int n = kit_benchs_list.v[i].repeats++;

  if (n >= KIT_BENCH_MAX_REPEATS)
    return;

  struct timespec tv;
  timespec_get(&tv, TIME_UTC);

  kit_benchs_list.v[i].sec[n]  = (int64_t) tv.tv_sec;
  kit_benchs_list.v[i].nsec[n] = (int64_t) tv.tv_nsec;
}

static void bench_end(int i) {
  int n = kit_benchs_list.v[i].repeats - 1;

  if (n < 0 || n >= KIT_BENCH_MAX_REPEATS)
    return;

  struct timespec tv;
  timespec_get(&tv, TIME_UTC);

  int64_t sec  = ((int64_t) tv.tv_sec) - kit_benchs_list.v[i].sec[n];
  int64_t nsec = ((int64_t) tv.tv_nsec) -
                 kit_benchs_list.v[i].nsec[n];

  kit_benchs_list.v[i].duration_nsec[n] = sec * 1000000000 + nsec;
}

void kit_bench_register(char const *name, char const *file,
                        kit_bench_run_fn fn) {
  int n = kit_benchs_list.size++;
  if (n < KIT_BENCHS_SIZE_LIMIT) {
    kit_benchmark_t *bench = kit_benchs_list.v + n;

    bench->bench_fn    = fn;
    bench->bench_name  = name;
    bench->bench_file  = file;
    bench->cycles_size = 0;
    bench->ready       = 0;
  }
}

static void kit_bench_setup_signals() {
  for (int i = 0; i < sizeof kit_signums_ / sizeof *kit_signums_; i++)
    signal(kit_signums_[i], kit_test_handle_signal);
}

static int kit_run_bench_(volatile int i) {
  int signum = setjmp(kit_test_restore_execution);

  if (signum != 0) {
    kit_benchs_list.v[i].signal = signum;
    return 0;
  }

  kit_benchs_list.v[i].bench_fn(i, bench_set_repeats_limit,
                                bench_loop, bench_begin, bench_end);
  return 1;
}

static int kit_compare_64_(void const *x_, void const *y_) {
  int64_t const *x = (int64_t const *) x_;
  int64_t const *y = (int64_t const *) y_;
  return *x - *y;
}

static int kit_compare_32_(void const *x_, void const *y_) {
  int const *x = (int const *) x_;
  int const *y = (int const *) y_;
  return *x - *y;
}

int kit_run_benchmarks(int argc, char **argv) {
  int success_count   = 0;
  int status          = 0;
  int no_color        = 0;
  int line_width      = 20;
  int carriage_return = 1;

  char const *specific_bench = NULL;

  kit_bench_setup_signals();

  for (int i = 0; i < argc; i++)
    if (strcmp("--no-term-color", argv[i]) == 0)
      no_color = 1;
    else if (strcmp("--no-carriage-return", argv[i]) == 0)
      carriage_return = 0;
    else if (strcmp("--match", argv[i]) == 0)
      specific_bench = argv[++i];

  if (specific_bench != NULL) {
    no_color || kit_print_color_(kit_light_);
    printf("Run benchmarks matching ");
    no_color || kit_print_color_(kit_white_);
    printf("*%s*", specific_bench);
    no_color || kit_print_color_(kit_light_);
    printf("\n\n");
  }

  char const *file         = NULL;
  ptrdiff_t   file_root    = -1;
  int         benchs_total = 0;

  for (int i = 0;
       i < kit_benchs_list.size && i < KIT_BENCHS_SIZE_LIMIT; i++) {
    if (specific_bench != NULL &&
        strstr(kit_benchs_list.v[i].bench_name, specific_bench) ==
            NULL)
      continue;
    benchs_total++;
    int l = 2 + (int) strlen(kit_benchs_list.v[i].bench_name);
    if (line_width < l)
      line_width = l;
  }

  if (benchs_total > 0) {
    char const *s = kit_benchs_list.v[0].bench_file;

    for (int j = 1;
         j < kit_benchs_list.size && j < KIT_BENCHS_SIZE_LIMIT; j++) {
      kit_benchmark_t *bench = kit_benchs_list.v + j;

      if (specific_bench != NULL &&
          strstr(bench->bench_name, specific_bench) == NULL)
        continue;
      if (strcmp(s, bench->bench_file) == 0)
        continue;
      int k = 0;
      for (; s[k] != '\0' && bench->bench_file[k] != '\0' &&
             s[k] == bench->bench_file[k];
           k++) { }
      if (file_root == -1 || file_root > k)
        file_root = k;
    }

    if (file_root == -1) {
      for (int i = 0; s[i] != '\0'; i++)
        if (s[i] == '/' || s[i] == '\\')
          file_root = i + 1;
    }
  }

  no_color || kit_print_color_(kit_blue_);
  printf("# ");
  no_color || kit_print_color_(kit_light_);
  printf("BENCHMARK");
  printf("%*c", line_width - 9, ' ');
  no_color || kit_print_color_(kit_green_);
  printf(" LOW      ");
  no_color || kit_print_color_(kit_light_);
  printf("|");
  no_color || kit_print_color_(kit_blue_);
  printf(" MEDIAN   ");
  no_color || kit_print_color_(kit_light_);
  printf("|");
  no_color || kit_print_color_(kit_yellow_);
  printf(" HIGH\n");
  no_color || kit_print_color_(kit_light_);
  printf("                       (in microseconds)\n\n");

  /*  Prepare cycles.
   */

  for (int i = 0;
       i < kit_benchs_list.size && i < KIT_BENCHS_SIZE_LIMIT; i++) {
    kit_benchmark_t *bench = kit_benchs_list.v + i;

    if (specific_bench != NULL &&
        strstr(bench->bench_name, specific_bench) == NULL)
      continue;

    kit_run_bench_(i);

    if (bench->cycles_size == 0) {
      bench->cycles_size = 2;
      bench->cycles[0]   = KIT_BENCH_REPEATS_DEFAULT_1;
      bench->cycles[1]   = KIT_BENCH_REPEATS_DEFAULT_2;
    }

    qsort(bench->cycles, bench->cycles_size, sizeof *bench->cycles,
          kit_compare_32_);

    kit_benchs_list.v[i].ready = 1;
  }

  /*  Run cycles.
   */

  for (int cycle = 0; cycle < KIT_BENCH_MAX_CYCLES; cycle++) {
    /*  Prepare cycle.
     */

    int cycles_done = 1;

    for (int i = 0;
         i < kit_benchs_list.size && i < KIT_BENCHS_SIZE_LIMIT; i++) {
      kit_benchmark_t *bench = kit_benchs_list.v + i;

      if (specific_bench != NULL &&
          strstr(bench->bench_name, specific_bench) == NULL)
        continue;
      if (cycle >= bench->cycles_size)
        continue;

      bench->repeats = 0;
      bench->cycle   = cycle;
      cycles_done    = 0;
    }

    if (cycles_done)
      break;

    /*  Run benchmarks.
     */

    for (int i = 0;
         i < kit_benchs_list.size && i < KIT_BENCHS_SIZE_LIMIT; i++) {
      kit_benchmark_t *bench = kit_benchs_list.v + i;

      if (specific_bench != NULL &&
          strstr(bench->bench_name, specific_bench) == NULL)
        continue;
      if (cycle >= bench->cycles_size)
        continue;

      if (file == NULL || strcmp(file, bench->bench_file) != 0) {
        if (file != NULL)
          printf("\n");
        file = bench->bench_file;
        no_color || kit_print_color_(kit_blue_);
        printf("* ");
        no_color || kit_print_color_(kit_white_);
        printf("%s\n", file + file_root);
      }

      !carriage_return || no_color || kit_print_color_(kit_yellow_);
      carriage_return || no_color || kit_print_color_(kit_light_);
      printf("` %s ", bench->bench_name);
      !carriage_return || printf("\r");
      fflush(stdout);

      int bench_status = kit_run_bench_(i);

      if (bench->repeats > KIT_BENCH_MAX_REPEATS)
        bench_status = 0;

      !carriage_return || no_color || kit_print_color_(kit_light_);
      !carriage_return || printf("` %s ", bench->bench_name);

      int l = (int) strlen(bench->bench_name);
      printf("%*c", line_width - l, ' ');

      if (bench->repeats <= 0) {
        no_color || kit_print_color_(kit_yellow_);
        printf("                                0 runs\n");
        success_count++;
      } else if (bench_status == 0) {
        no_color || kit_print_color_(kit_red_);
        printf("                                FAIL\n");
        status = 1;
      } else {
        int repeats = bench->repeats;

        memcpy(bench->duration_sorted_nsec, bench->duration_nsec,
               repeats * sizeof *bench->duration_sorted_nsec);
        qsort(bench->duration_sorted_nsec, repeats,
              sizeof *bench->duration_sorted_nsec, kit_compare_64_);

        int64_t average = bench->duration_sorted_nsec[repeats / 2];
        int64_t floor   = bench->duration_sorted_nsec[repeats / 20];
        int64_t roof =
            bench->duration_sorted_nsec[repeats - repeats / 20 - 1];

        no_color || kit_print_color_(kit_white_);
        printf("%-9g", (double) floor * 0.001);
        no_color || kit_print_color_(kit_light_);
        printf("| ");
        no_color || kit_print_color_(kit_white_);
        printf("%-9g", (double) average * 0.001);
        no_color || kit_print_color_(kit_light_);
        printf("| ");
        no_color || kit_print_color_(kit_white_);
        printf("%-9g", (double) roof * 0.001);
        no_color || kit_print_color_(kit_light_);
        printf(" %d runs\n", repeats);
        success_count++;
      }
    }
  }

  printf("\n");

  if (status != 0) {
    for (int i = 0;
         i < kit_benchs_list.size && i < KIT_BENCHS_SIZE_LIMIT; i++) {
      kit_benchmark_t *bench = kit_benchs_list.v + i;

      if (specific_bench != NULL &&
          strstr(bench->bench_name, specific_bench) == NULL)
        continue;
      if (bench->signal != 0) {
        int signum = bench->signal;
        if (signum >= 0 &&
            signum < sizeof kit_signames_ / sizeof *kit_signames_ &&
            kit_signames_[signum] != NULL) {
          no_color || kit_print_color_(kit_light_);
          printf("Signal \"%s\" (%d) for \"", kit_signames_[signum],
                 signum);
          no_color || kit_print_color_(kit_white_);
          printf("%s", bench->bench_name);
          no_color || kit_print_color_(kit_light_);
          printf("\" in \"");
          no_color || kit_print_color_(kit_white_);
          printf("%s", bench->bench_file + file_root);
          no_color || kit_print_color_(kit_light_);
          printf("\"!.\n");
        } else {
          no_color || kit_print_color_(kit_light_);
          printf("Unknown signal (%d) for \"", signum);
          no_color || kit_print_color_(kit_white_);
          printf("%s", bench->bench_name);
          no_color || kit_print_color_(kit_light_);
          printf("\" in \"");
          no_color || kit_print_color_(kit_white_);
          printf("%s", bench->bench_file + file_root);
          no_color || kit_print_color_(kit_light_);
          printf("\"!.\n");
        }
      }
    }

    printf("\n");
  }

  if (kit_benchs_list.size > KIT_BENCHS_SIZE_LIMIT) {
    no_color || kit_print_color_(kit_light_);
    printf("Too many benchmarks!\n\n");
    status = 1;
  }

  if (status == 0) {
    no_color || kit_print_color_(kit_green_);
    printf("DONE\n");
  } else {
    no_color || kit_print_color_(kit_red_);
    printf("DONE WITH ERRORS\n");
  }

  no_color || kit_print_color_(kit_light_);
  printf("\n");
  return status;
}

#ifdef __cplusplus
}
#endif

#endif