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
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
|
#ifndef KIT_INL_H
#define KIT_INL_H
/*********************************************************************
* *
* File: source/kit/types.h *
* *
*********************************************************************/
#ifndef KIT_TYPES_H
#define KIT_TYPES_H
typedef signed char i8;
typedef signed short i16;
typedef signed int i32;
typedef signed long long i64;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef float f32;
typedef double f64;
#endif
/*********************************************************************
* *
* File: source/kit/status.h *
* *
*********************************************************************/
#ifndef KIT_STATUS_H
#define KIT_STATUS_H
#ifdef __cplusplus
extern "C" {
#endif
enum {
KIT_OK,
KIT_ERROR_BAD_ALLOC,
KIT_ERROR_MKDIR_FAILED,
KIT_ERROR_RMDIR_FAILED,
KIT_ERROR_UNLINK_FAILED,
KIT_ERROR_FILE_ALREADY_EXISTS,
KIT_ERROR_FILE_DO_NOT_EXIST,
KIT_ERROR_PATH_TOO_LONG,
KIT_ERROR_SOCKETS_STARTUP_FAILED,
KIT_ERROR_SOCKET_CONTROL_FAILED
};
typedef signed int kit_status_t;
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/allocator.h *
* *
*********************************************************************/
#ifndef KIT_ALLOCATOR_H
#define KIT_ALLOCATOR_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { KIT_ALLOCATE, KIT_DEALLOCATE, KIT_REALLOCATE };
typedef void *(*kit_allocate_fn)(int request, void *state,
ptrdiff_t size,
ptrdiff_t previous_size,
void *pointer);
typedef struct {
void *state;
kit_allocate_fn allocate;
} kit_allocator_t;
/* Application should implement this function if custom allocator
* dispatch is enabled.
*
* See KIT_ENABLE_CUSTOM_ALLOC_DISPATCH macro.
*/
void *kit_alloc_dispatch(kit_allocator_t alloc, int request,
ptrdiff_t size, ptrdiff_t previous_size,
void *pointer);
kit_allocator_t kit_alloc_default(void);
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/time.h *
* *
*********************************************************************/
#ifndef KIT_TIME_H
#define KIT_TIME_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <time.h>
#ifndef TIME_UTC
# define TIME_UTC 1
#endif
#ifdef __MINGW32__
# 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
/*********************************************************************
* *
* File: source/kit/thread_defs.h *
* *
*********************************************************************/
#ifndef KIT_THREAD_DEFS_H
#define KIT_THREAD_DEFS_H
#ifdef __cplusplus
extern "C" {
#endif
enum {
thrd_success = 0,
thrd_timedout,
thrd_error,
thrd_busy,
thrd_nomem,
thrd_wrong_stack_size
};
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/thread.h *
* *
*********************************************************************/
#ifndef KIT_THREAD_H
#define KIT_THREAD_H
#ifndef KIT_DISABLE_SYSTEM_THREADS
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
# include <stddef.h>
# include <time.h>
# if defined(__cplusplus)
# define _Noreturn [[noreturn]]
# elif defined(_MSC_VER)
# define _Noreturn __declspec(noreturn)
# endif
# if !defined(_WIN32) || defined(__CYGWIN__)
# include <pthread.h>
# endif
# ifndef _Thread_local
# if defined(__cplusplus)
/* C++11 doesn't need `_Thread_local` keyword or macro */
# elif !defined(__STDC_NO_THREADS__)
/* threads are optional in C11, _Thread_local present in this
* condition */
# elif defined(_MSC_VER)
# define _Thread_local __declspec(thread)
# elif defined(__GNUC__)
# define _Thread_local __thread
# else
/* Leave _Thread_local undefined so that use of _Thread_local would
* not promote to a non-thread-local global variable
*/
# endif
# endif
# if !defined(__cplusplus)
/*
* C11 thread_local() macro
* C++11 and above already have thread_local keyword
*/
# ifndef thread_local
# if _MSC_VER
# define thread_local __declspec(thread)
# else
# define thread_local _Thread_local
# endif
# endif
# endif
# ifdef __cplusplus
extern "C" {
# endif
typedef void (*tss_dtor_t)(void *);
typedef int (*thrd_start_t)(void *);
# if defined(_WIN32) && !defined(__CYGWIN__)
typedef struct {
void *handle;
} thrd_t;
typedef unsigned long tss_t;
# else
typedef pthread_t thrd_t;
typedef pthread_key_t tss_t;
# endif
int thrd_create(thrd_t *, thrd_start_t, void *);
int thrd_create_with_stack(thrd_t *, thrd_start_t, void *,
ptrdiff_t stack_size);
thrd_t thrd_current(void);
int thrd_detach(thrd_t);
int thrd_equal(thrd_t, thrd_t);
_Noreturn void thrd_exit(int);
int thrd_join(thrd_t, int *);
int thrd_sleep(const struct timespec *, struct timespec *);
void thrd_yield(void);
# ifdef __cplusplus
}
# endif
#endif
#endif
/*********************************************************************
* *
* File: source/kit/atomic.h *
* *
*********************************************************************/
#ifndef KIT_ATOMIC_H
#define KIT_ATOMIC_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdint.h>
#ifndef _MSC_VER
# include <stdatomic.h>
# define KIT_ATOMIC(type_) type_ _Atomic
#else
# include <assert.h>
# define KIT_ATOMIC(type_) type_ volatile
# ifdef __cplusplus
extern "C" {
# endif
enum {
memory_order_relaxed,
memory_order_consume,
memory_order_acquire,
memory_order_release,
memory_order_acq_rel,
memory_order_seq_cst
};
void kit_atomic_store_explicit_8(uint8_t volatile *var, uint8_t value,
int memory_order);
void kit_atomic_store_explicit_16(uint16_t volatile *var,
uint16_t value, int memory_order);
void kit_atomic_store_explicit_32(uint32_t volatile *var,
uint32_t value, int memory_order);
void kit_atomic_store_explicit_64(uint64_t volatile *var,
uint64_t value, int memory_order);
uint8_t kit_atomic_load_explicit_8(uint8_t volatile *var,
int memory_order);
uint16_t kit_atomic_load_explicit_16(uint16_t volatile *var,
int memory_order);
uint32_t kit_atomic_load_explicit_32(uint32_t volatile *var,
int memory_order);
uint64_t kit_atomic_load_explicit_64(uint64_t volatile *var,
int memory_order);
uint8_t kit_atomic_exchange_explicit_8(uint8_t volatile *var,
uint8_t value,
int memory_order);
uint16_t kit_atomic_exchange_explicit_16(uint16_t volatile *var,
uint16_t value,
int memory_order);
uint32_t kit_atomic_exchange_explicit_32(uint32_t volatile *var,
uint32_t value,
int memory_order);
uint64_t kit_atomic_exchange_explicit_64(uint64_t volatile *var,
uint64_t value,
int memory_order);
uint8_t kit_atomic_fetch_add_explicit_8(uint8_t volatile *var,
uint8_t value,
int memory_order);
uint16_t kit_atomic_fetch_add_explicit_16(uint16_t volatile *var,
uint16_t value,
int memory_order);
uint32_t kit_atomic_fetch_add_explicit_32(uint32_t volatile *var,
uint32_t value,
int memory_order);
uint64_t kit_atomic_fetch_add_explicit_64(uint64_t volatile *var,
uint64_t value,
int memory_order);
# define atomic_store_explicit(var_, value_, memory_order_) \
do { \
assert(sizeof *(var_) == 1 || sizeof *(var_) == 2 || \
sizeof *(var_) == 4 || sizeof *(var_) == 8); \
if (sizeof *(var_) == 1) \
kit_atomic_store_explicit_8((uint8_t volatile *) (var_), \
(uint8_t) (value_), \
(memory_order_)); \
if (sizeof *(var_) == 2) \
kit_atomic_store_explicit_16((uint16_t volatile *) (var_), \
(uint16_t) (value_), \
(memory_order_)); \
if (sizeof *(var_) == 4) \
kit_atomic_store_explicit_32((uint32_t volatile *) (var_), \
(uint32_t) (value_), \
(memory_order_)); \
if (sizeof *(var_) == 8) \
kit_atomic_store_explicit_64((uint64_t volatile *) (var_), \
(uint64_t) (value_), \
(memory_order_)); \
} while (0)
# define atomic_load_explicit(var_, memory_order_) \
(assert(sizeof *(var_) == 1 || sizeof *(var_) == 2 || \
sizeof *(var_) == 4 || sizeof *(var_) == 8), \
(sizeof *(var_) == 1 \
? kit_atomic_load_explicit_8((uint8_t volatile *) (var_), \
(memory_order_)) \
: sizeof *(var_) == 2 \
? kit_atomic_load_explicit_16( \
(uint16_t volatile *) (var_), (memory_order_)) \
: sizeof *(var_) == 4 \
? kit_atomic_load_explicit_32( \
(uint32_t volatile *) (var_), (memory_order_)) \
: kit_atomic_load_explicit_64( \
(uint64_t volatile *) (var_), (memory_order_))))
# define atomic_exchange_explicit(var_, value_, memory_order_) \
(assert(sizeof *(var_) == 1 || sizeof *(var_) == 2 || \
sizeof *(var_) == 4 || sizeof *(var_) == 8), \
(sizeof *(var_) == 1 ? kit_atomic_exchange_explicit_8( \
(uint8_t volatile *) (var_), \
(uint8_t) (value_), (memory_order_)) \
: sizeof *(var_) == 2 \
? kit_atomic_exchange_explicit_16( \
(uint16_t volatile *) (var_), (uint16_t) (value_), \
(memory_order_)) \
: sizeof *(var_) == 4 \
? kit_atomic_exchange_explicit_32( \
(uint32_t volatile *) (var_), (uint32_t) (value_), \
(memory_order_)) \
: kit_atomic_exchange_explicit_64( \
(uint64_t volatile *) (var_), (uint64_t) (value_), \
(memory_order_))))
# define atomic_fetch_add_explicit(var_, value_, memory_order_) \
(assert(sizeof *(var_) == 1 || sizeof *(var_) == 2 || \
sizeof *(var_) == 4 || sizeof *(var_) == 8), \
(sizeof *(var_) == 1 ? kit_atomic_fetch_add_explicit_8( \
(uint8_t volatile *) (var_), \
(uint8_t) (value_), (memory_order_)) \
: sizeof *(var_) == 2 \
? kit_atomic_fetch_add_explicit_16( \
(uint16_t volatile *) (var_), (uint16_t) (value_), \
(memory_order_)) \
: sizeof *(var_) == 4 \
? kit_atomic_fetch_add_explicit_32( \
(uint32_t volatile *) (var_), (uint32_t) (value_), \
(memory_order_)) \
: kit_atomic_fetch_add_explicit_64( \
(uint64_t volatile *) (var_), (uint64_t) (value_), \
(memory_order_))))
#endif
#ifndef KIT_DISABLE_SHORT_NAMES
# define ATOMIC KIT_ATOMIC
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/mutex.h *
* *
*********************************************************************/
#ifndef KIT_MUTEX_H
#define KIT_MUTEX_H
#ifndef KIT_DISABLE_SYSTEM_THREADS
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
# if !defined(_WIN32) || defined(__CYGWIN__)
# include <pthread.h>
# endif
# ifdef __cplusplus
extern "C" {
# endif
# if defined(_WIN32) && !defined(__CYGWIN__)
typedef struct {
void *DebugInfo;
long LockCount;
long RecursionCount;
void *OwningThread;
void *LockSemaphore;
uintptr_t SpinCount;
} mtx_t;
# else
typedef pthread_mutex_t mtx_t;
# endif
enum {
mtx_plain = 0,
mtx_recursive = 1,
mtx_timed = 2,
};
void mtx_destroy(mtx_t *mtx_);
int mtx_init(mtx_t *mtx_, int);
int mtx_lock(mtx_t *mtx_);
int mtx_timedlock(mtx_t *__restrict mtx_,
struct timespec const *__restrict);
int mtx_trylock(mtx_t *mtx_);
int mtx_unlock(mtx_t *mtx_);
# ifdef __cplusplus
}
# endif
#endif
#endif
/*********************************************************************
* *
* File: source/kit/condition_variable.h *
* *
*********************************************************************/
#ifndef KIT_CONDITION_VARIABLE_H
#define KIT_CONDITION_VARIABLE_H
#ifndef KIT_DISABLE_SYSTEM_THREADS
# ifdef __cplusplus
extern "C" {
# endif
# if defined(_WIN32) && !defined(__CYGWIN__)
typedef struct {
void *Ptr;
} cnd_t;
typedef struct {
volatile uintptr_t status;
} once_flag;
# else
typedef pthread_cond_t cnd_t;
typedef pthread_once_t once_flag;
# endif
void call_once(once_flag *, void (*)(void));
int cnd_broadcast(cnd_t *);
void cnd_destroy(cnd_t *);
int cnd_init(cnd_t *);
int cnd_signal(cnd_t *);
int cnd_timedwait(cnd_t *__restrict, mtx_t *__restrict mtx_,
struct timespec const *__restrict);
int cnd_wait(cnd_t *, mtx_t *mtx_);
# ifdef __cplusplus
}
# endif
#endif
#endif
/*********************************************************************
* *
* File: source/kit/array_ref.h *
* *
*********************************************************************/
#ifndef KIT_ARRAY_REF_H
#define KIT_ARRAY_REF_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*kit_ar_compare_fn)(void *left, void *right);
int kit_ar_equal_bytes(ptrdiff_t left_element_size,
ptrdiff_t left_size, void *left_data,
ptrdiff_t right_element_size,
ptrdiff_t right_size, void *right_data);
int kit_ar_compare(ptrdiff_t left_element_size, ptrdiff_t left_size,
void *left_data, ptrdiff_t right_element_size,
ptrdiff_t right_size, void *right_data,
kit_ar_compare_fn compare);
#define KIT_AR(type_) \
struct { \
ptrdiff_t size; \
type_ *values; \
}
#define KIT_AR_WRAP(name_, element_type_, array_) \
struct { \
ptrdiff_t size; \
element_type_ *values; \
} name_ = { .size = (sizeof(array_) / sizeof((array_)[0])), \
.values = (array_) }
#define KIT_AR_EQUAL(left_, right_) \
kit_ar_equal_bytes(sizeof((left_).values[0]), (left_).size, \
(left_).values, sizeof((right_).values[0]), \
(right_).size, (right_).values)
#define KIT_AR_COMPARE(left_, right_, compare_) \
kit_ar_compare(sizeof((left_).values[0]), (left_).size, \
(left_).values, sizeof((right_).values[0]), \
(right_).size, (right_).values, \
(kit_ar_compare_fn) (compare_))
#ifndef KIT_DISABLE_SHORT_NAMES
# define ar_compare_fn kit_ar_compare_fn
# define ar_equal_bytes kit_ar_equal_bytes
# define ar_compare kit_ar_compare
# define AR KIT_AR
# define AR_WRAP KIT_AR_WRAP
# define AR_EQUAL KIT_AR_EQUAL
# define AR_COMPARE KIT_AR_COMPARE
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/string_ref.h *
* *
*********************************************************************/
#ifndef KIT_STRING_REF_H
#define KIT_STRING_REF_H
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef KIT_AR(char) kit_string_ref_t;
typedef kit_string_ref_t kit_str_t;
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC push_options
# pragma GCC optimize("O3")
#endif
static kit_str_t kit_str(ptrdiff_t size, char *static_string) {
kit_str_t s = { .size = size, .values = static_string };
return s;
}
/* Make a barbarian string for C standard library functions.
* Not thread safe.
* Use with caution.
*/
static char *kit_make_bs(kit_str_t s) {
static char buf[8][4096];
static int index = 0;
ptrdiff_t n = s.size;
if (n > 4095)
n = 4095;
memcpy(buf[index], s.values, n);
buf[index][n] = '\0';
char *result = buf[index];
index = (index + 1) % 8;
return result;
}
#ifdef __GNUC__
# pragma GCC pop_options
# pragma GCC diagnostic pop
#endif
#define KIT_SZ(static_str_) \
kit_str(sizeof(static_str_) - 1, (static_str_))
#define KIT_WRAP_BS(string_) kit_str(strlen(string_), (string_))
#define KIT_WRAP_STR(string_) \
kit_str((string_).size, (string_).values)
#ifndef KIT_DISABLE_SHORT_NAMES
# define BS(string_) kit_make_bs(KIT_WRAP_STR(string_))
# define string_ref_t kit_string_ref_t
# define str_t kit_str_t
# define SZ KIT_SZ
# define WRAP_BS KIT_WRAP_BS
# define WRAP_STR KIT_WRAP_STR
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/dynamic_array.h *
* *
*********************************************************************/
#ifndef KIT_DYNAMIC_ARRAY_H
#define KIT_DYNAMIC_ARRAY_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
ptrdiff_t capacity;
ptrdiff_t size;
void *values;
kit_allocator_t alloc;
} kit_da_void_t;
void kit_da_init(kit_da_void_t *array, ptrdiff_t element_size,
ptrdiff_t size, kit_allocator_t alloc);
void kit_da_resize(kit_da_void_t *array, ptrdiff_t element_size,
ptrdiff_t size);
/* Dynamic array type definition.
*/
#define KIT_DA(element_type_) \
struct { \
ptrdiff_t capacity; \
ptrdiff_t size; \
element_type_ *values; \
kit_allocator_t alloc; \
}
/* Initialize dynamic array.
*/
#define KIT_DA_INIT(array_, size_, alloc_) \
kit_da_init((kit_da_void_t *) &(array_), \
sizeof((array_).values[0]), (size_), (alloc_))
/* Declare and initialize dynamic array.
*/
#define KIT_DA_CREATE(name_, element_type_, size_) \
KIT_DA(element_type_) name_; \
KIT_DA_INIT(name_, (size_), kit_alloc_default())
/* Destroy dynamic array.
*/
#define KIT_DA_DESTROY(array_) \
do { \
if ((array_).values != NULL) \
kit_alloc_dispatch((array_).alloc, KIT_DEALLOCATE, 0, 0, \
(array_).values); \
} while (0)
/* Resize dynamic array.
*/
#define KIT_DA_RESIZE(array_, size_) \
kit_da_resize((kit_da_void_t *) &(array_), \
sizeof((array_).values[0]), size_)
/* Append a value to dynamic array.
*/
#define KIT_DA_APPEND(array_, value_) \
do { \
ptrdiff_t kit_index_back_ = (array_).size; \
KIT_DA_RESIZE((array_), kit_index_back_ + 1); \
if (kit_index_back_ < (array_).size) \
(array_).values[kit_index_back_] = (value_); \
} while (0)
/* Insert a value into dynamic array.
*/
#define KIT_DA_INSERT(array_, index_, value_) \
do { \
ptrdiff_t kit_i_; \
ptrdiff_t kit_index_back_ = (array_).size; \
ptrdiff_t kit_indert_n_ = (index_); \
KIT_DA_RESIZE((array_), kit_index_back_ + 1); \
if (kit_index_back_ + 1 == (array_).size) { \
for (kit_i_ = kit_index_back_; kit_i_ > kit_indert_n_; \
kit_i_--) \
(array_).values[kit_i_] = (array_).values[kit_i_ - 1]; \
(array_).values[kit_indert_n_] = (value_); \
} \
} while (0)
/* Erase a value from dynamic array.
*/
#define KIT_DA_ERASE(array_, index_) \
do { \
ptrdiff_t i_; \
for (i_ = (index_) + 1; i_ < (array_).size; i_++) \
(array_).values[i_ - 1] = (array_).values[i_]; \
KIT_DA_RESIZE((array_), (array_).size - 1); \
} while (0)
typedef KIT_DA(char) kit_string_t;
#ifndef KIT_DISABLE_SHORT_NAMES
# define da_void_t kit_da_void_t
# define da_init kit_da_init
# define da_resize kit_da_resize
# define string_t kit_string_t
# define DA KIT_DA
# define DA_INIT KIT_DA_INIT
# define DA_CREATE KIT_DA_CREATE
# define DA_DESTROY KIT_DA_DESTROY
# define DA_RESIZE KIT_DA_RESIZE
# define DA_APPEND KIT_DA_APPEND
# define DA_INSERT KIT_DA_INSERT
# define DA_ERASE KIT_DA_ERASE
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/lower_bound.h *
* *
*********************************************************************/
#ifndef KIT_LOWER_BOUND_H
#define KIT_LOWER_BOUND_H
#ifdef __cplusplus
extern "C" {
#endif
#define KIT_LOWER_BOUND_INL(return_val, size, ...) \
do { \
ptrdiff_t position_ = 0; \
ptrdiff_t count_ = (size); \
while (count_ > 0) { \
ptrdiff_t const delta_ = count_ / 2; \
ptrdiff_t const index_ = position_ + delta_; \
if (__VA_ARGS__) { \
position_ += delta_ + 1; \
count_ -= delta_ + 1; \
} else \
count_ = delta_; \
} \
(return_val) = position_; \
} while (0)
#define KIT_LOWER_BOUND(return_val, array, value, op) \
KIT_LOWER_BOUND_INL(return_val, (array).size, \
(op) ((array).values[index_], (value)))
#define KIT_LOWER_BOUND_REF(return_val, array, value, op) \
KIT_LOWER_BOUND_INL(return_val, (array).size, \
(op) ((array).values + index_, (value)))
#ifndef KIT_DISABLE_SHORT_NAMES
# define LOWER_BOUND_INL KIT_LOWER_BOUND_INL
# define LOWER_BOUND KIT_LOWER_BOUND
# define LOWER_BOUND_REF KIT_LOWER_BOUND_REF
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/move_back.h *
* *
*********************************************************************/
#ifndef KIT_MOVE_BACK_H
#define KIT_MOVE_BACK_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#define KIT_MOVE_BACK_INL(new_size, array, ...) \
do { \
ptrdiff_t index_; \
ptrdiff_t end_ = (array).size; \
unsigned char temp_[sizeof *(array).values]; \
for (index_ = 0; index_ < end_;) { \
if (__VA_ARGS__) { \
end_--; \
if (index_ != end_) { \
memcpy(temp_, (array).values + end_, \
sizeof *(array).values); \
(array).values[end_] = (array).values[index_]; \
memcpy((array).values + index_, temp_, \
sizeof *(array).values); \
} \
} else \
index_++; \
} \
(new_size) = end_; \
} while (0)
#define KIT_MOVE_BACK(new_size, array, value, cond) \
KIT_MOVE_BACK_INL(new_size, array, \
(cond) ((array).values[index_], (value)))
#define KIT_MOVE_BACK_REF(new_size, array, value, cond) \
KIT_MOVE_BACK_INL(new_size, array, \
(cond) ((array).values + index_, (value)))
#ifndef KIT_DISABLE_SHORT_NAMES
# define MOVE_BACK_INL KIT_MOVE_BACK_INL
# define MOVE_BACK KIT_MOVE_BACK
# define MOVE_BACK_REF KIT_MOVE_BACK_REF
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/bigint.h *
* *
*********************************************************************/
#ifndef KIT_BIGINT_H
#define KIT_BIGINT_H
#include <assert.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef KIT_BIGINT_SIZE
# define KIT_BIGINT_SIZE 64
#endif
#if __STDC_VERSION__ >= 199901L
static_assert(sizeof(uint8_t) == 1, "uint8_t size should be 1 byte");
static_assert(sizeof(uint32_t) == 4,
"uint32_t size should be 4 bytes");
static_assert(sizeof(uint64_t) == 8,
"uint64_t size should be 8 bytes");
static_assert(KIT_BIGINT_SIZE > 0 && (KIT_BIGINT_SIZE % 8) == 0,
"Invalid big integer size");
#endif
typedef struct {
uint32_t v[KIT_BIGINT_SIZE / 4];
} kit_bigint_t;
typedef uint_fast8_t kit_bit_t;
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC push_options
# pragma GCC optimize("O3")
#endif
static kit_bigint_t kit_bi_uint32(uint32_t x) {
kit_bigint_t z;
memset(&z, 0, sizeof z);
z.v[0] = x;
return z;
}
static kit_bigint_t kit_bi_uint64(uint64_t x) {
kit_bigint_t z;
memset(&z, 0, sizeof z);
z.v[0] = (uint32_t) (x & 0xffffffff);
z.v[1] = (uint32_t) (x >> 32);
return z;
}
static kit_bigint_t kit_bi_int32(int32_t x) {
kit_bigint_t z;
memset(&z, x < 0 ? -1 : 0, sizeof z);
z.v[0] = x;
return z;
}
static kit_bigint_t kit_bi_int64(int64_t x) {
kit_bigint_t z;
memset(&z, x < 0 ? -1 : 0, sizeof z);
z.v[0] = (uint32_t) (((uint64_t) x) & 0xffffffff);
z.v[1] = (uint32_t) (((uint64_t) x) >> 32);
return z;
}
static int kit_bi_is_zero(kit_bigint_t x) {
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++)
if (x.v[i] != 0)
return 0;
return 1;
}
static int kit_bi_is_neg(kit_bigint_t x) {
return (x.v[KIT_BIGINT_SIZE / 4 - 1] & 0x80000000) != 0;
}
static int kit_bi_equal(kit_bigint_t x, kit_bigint_t y) {
return kit_ar_equal_bytes(1, KIT_BIGINT_SIZE, x.v, 1,
KIT_BIGINT_SIZE, y.v);
}
static int kit_bi_compare(kit_bigint_t x, kit_bigint_t y) {
ptrdiff_t i;
for (i = KIT_BIGINT_SIZE / 4 - 1; i >= 0; i--)
if (x.v[i] < y.v[i])
return -1;
else if (x.v[i] > y.v[i])
return 1;
return 0;
}
static ptrdiff_t kit_bi_significant_bit_count(kit_bigint_t x) {
ptrdiff_t n = KIT_BIGINT_SIZE / 4 - 1;
while (n > 0 && x.v[n] == 0) n--;
uint32_t val = x.v[n];
if (val == 0)
return 0;
ptrdiff_t bits = (val & 0x80000000u) != 0 ? 32
: (val & 0x40000000u) != 0 ? 31
: (val & 0x20000000u) != 0 ? 30
: (val & 0x10000000u) != 0 ? 29
: (val & 0x8000000u) != 0 ? 28
: (val & 0x4000000u) != 0 ? 27
: (val & 0x2000000u) != 0 ? 26
: (val & 0x1000000u) != 0 ? 25
: (val & 0x800000u) != 0 ? 24
: (val & 0x400000u) != 0 ? 23
: (val & 0x200000u) != 0 ? 22
: (val & 0x100000u) != 0 ? 21
: (val & 0x80000u) != 0 ? 20
: (val & 0x40000u) != 0 ? 19
: (val & 0x20000u) != 0 ? 18
: (val & 0x10000u) != 0 ? 17
: (val & 0x8000u) != 0 ? 16
: (val & 0x4000u) != 0 ? 15
: (val & 0x2000u) != 0 ? 14
: (val & 0x1000u) != 0 ? 13
: (val & 0x800u) != 0 ? 12
: (val & 0x400u) != 0 ? 11
: (val & 0x200u) != 0 ? 10
: (val & 0x100u) != 0 ? 9
: (val & 0x80u) != 0 ? 8
: (val & 0x40u) != 0 ? 7
: (val & 0x20u) != 0 ? 6
: (val & 0x10u) != 0 ? 5
: (val & 0x08u) != 0 ? 4
: (val & 0x04u) != 0 ? 3
: (val & 0x02u) != 0 ? 2
: 1;
return n * 32 + bits;
}
static kit_bigint_t kit_bi_and(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) z.v[i] = x.v[i] & y.v[i];
return z;
}
static kit_bigint_t kit_bi_or(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) z.v[i] = x.v[i] | y.v[i];
return z;
}
static kit_bigint_t kit_bi_xor(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) z.v[i] = x.v[i] ^ y.v[i];
return z;
}
static kit_bigint_t kit_bi_shl_uint(kit_bigint_t x, uint32_t y) {
kit_bigint_t z;
memset(&z, 0, sizeof z);
ptrdiff_t words = (ptrdiff_t) (y / 32);
ptrdiff_t bits = (ptrdiff_t) (y % 32);
ptrdiff_t i;
for (i = words; i < KIT_BIGINT_SIZE / 4; i++) {
z.v[i] |= x.v[i - words] << bits;
if (bits != 0 && i + 1 < KIT_BIGINT_SIZE / 4)
z.v[i + 1] = x.v[i - words] >> (32 - bits);
}
return z;
}
static kit_bigint_t kit_bi_shr_uint(kit_bigint_t x, uint32_t y) {
kit_bigint_t z;
memset(&z, 0, sizeof z);
ptrdiff_t words = (ptrdiff_t) (y / 32);
ptrdiff_t bits = (ptrdiff_t) (y % 32);
ptrdiff_t i;
for (i = KIT_BIGINT_SIZE / 4 - words - 1; i >= 0; i--) {
z.v[i] |= x.v[i + words] >> bits;
if (bits != 0 && i > 0)
z.v[i - 1] = x.v[i + words] << (32 - bits);
}
return z;
}
static kit_bit_t kit_bi_carry(uint32_t x, uint32_t y,
kit_bit_t carry) {
assert(carry == 0 || carry == 1);
return 0xffffffffu - x < y || 0xffffffffu - x - y < carry ? 1 : 0;
}
/* Increment.
*/
static kit_bigint_t kit_bi_inc(kit_bigint_t x) {
kit_bigint_t z;
kit_bit_t carry = 1;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
z.v[i] = x.v[i] + carry;
carry = kit_bi_carry(x.v[i], 0, carry);
}
return z;
}
/* Decrement
*/
static kit_bigint_t kit_bi_dec(kit_bigint_t x) {
kit_bigint_t z;
kit_bit_t carry = 0;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
z.v[i] = x.v[i] + 0xffffffff + carry;
carry = kit_bi_carry(x.v[i], 0xffffffff, carry);
}
return z;
}
/* Addition.
*/
static kit_bigint_t kit_bi_add(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
kit_bit_t carry = 0;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
z.v[i] = x.v[i] + y.v[i] + carry;
carry = kit_bi_carry(x.v[i], y.v[i], carry);
}
return z;
}
/* Negation.
*/
static kit_bigint_t kit_bi_neg(kit_bigint_t x) {
kit_bigint_t y;
kit_bit_t carry = 1;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
y.v[i] = (x.v[i] ^ 0xffffffff) + carry;
carry = kit_bi_carry(x.v[i] ^ 0xffffffff, 0, carry);
}
return y;
}
/* Subtraction.
*/
static kit_bigint_t kit_bi_sub(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
kit_bit_t carry = 1;
ptrdiff_t i;
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
z.v[i] = x.v[i] + (y.v[i] ^ 0xffffffff) + carry;
carry = kit_bi_carry(x.v[i], (y.v[i] ^ 0xffffffff), carry);
}
return z;
}
static kit_bigint_t kit_bi_mul_uint32(kit_bigint_t x, uint32_t y) {
kit_bigint_t z;
ptrdiff_t i, k;
memset(&z, 0, sizeof z);
if (y != 0)
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
if (x.v[i] == 0)
continue;
uint64_t carry = ((uint64_t) x.v[i]) * ((uint64_t) y);
for (k = i; k < KIT_BIGINT_SIZE / 4 && carry != 0; k++) {
uint64_t sum = ((uint64_t) z.v[k]) + carry;
z.v[k] = ((uint32_t) (sum & 0xffffffffull));
carry = sum >> 32;
}
}
return z;
}
/* Multiplication.
*/
static kit_bigint_t kit_bi_mul(kit_bigint_t x, kit_bigint_t y) {
kit_bigint_t z;
ptrdiff_t i, j, k;
memset(&z, 0, sizeof z);
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
if (x.v[i] == 0)
continue;
for (j = 0; i + j < KIT_BIGINT_SIZE / 4; j++) {
if (y.v[j] == 0)
continue;
uint64_t carry = ((uint64_t) x.v[i]) * ((uint64_t) y.v[j]);
for (k = i + j; k < KIT_BIGINT_SIZE / 4 && carry != 0; k++) {
uint64_t sum = ((uint64_t) z.v[k]) + carry;
z.v[k] = ((uint32_t) (sum & 0xffffffffull));
carry = sum >> 32;
}
}
}
return z;
}
typedef struct {
kit_bit_t undefined;
kit_bigint_t quotient;
kit_bigint_t remainder;
} kit_bi_division_t;
/* Unsigned division.
*/
static kit_bi_division_t kit_bi_udiv(kit_bigint_t x, kit_bigint_t y) {
kit_bi_division_t z;
memset(&z, 0, sizeof z);
ptrdiff_t y_bits = kit_bi_significant_bit_count(y);
if (y_bits == 0) {
z.undefined = 1;
return z;
}
ptrdiff_t x_bits = kit_bi_significant_bit_count(x);
ptrdiff_t shift = x_bits - y_bits;
z.remainder = x;
z.quotient = kit_bi_uint32(0);
y = kit_bi_shl_uint(y, (uint32_t) shift);
while (shift >= 0) {
if (kit_bi_compare(z.remainder, y) >= 0) {
z.remainder = kit_bi_sub(z.remainder, y);
z.quotient.v[shift / 32] |= (1u << (shift % 32));
}
y = kit_bi_shr_uint(y, 1);
shift--;
}
return z;
}
/* Signed division.
*
* Remainder is always a non-negative value less than absolute value
* of y.
*/
static kit_bi_division_t kit_bi_div(kit_bigint_t x, kit_bigint_t y) {
int x_neg = kit_bi_is_neg(x);
int y_neg = kit_bi_is_neg(y);
kit_bigint_t x_abs = x_neg ? kit_bi_neg(x) : x;
kit_bigint_t y_abs = y_neg ? kit_bi_neg(y) : y;
if (x_neg == y_neg)
return kit_bi_udiv(x_abs, y_abs);
kit_bi_division_t z = kit_bi_udiv(x_abs, y_abs);
if (!kit_bi_is_zero(z.remainder) && !y_neg)
z.quotient = kit_bi_dec(kit_bi_neg(z.quotient));
else
z.quotient = kit_bi_neg(z.quotient);
return z;
}
static void kit_bi_serialize(kit_bigint_t in, uint8_t *out) {
ptrdiff_t i;
assert(out != NULL);
for (i = 0; i < KIT_BIGINT_SIZE / 4; i++) {
out[i * 4] = (uint8_t) (in.v[i] & 0xff);
out[i * 4 + 1] = (uint8_t) ((in.v[i] >> 8) & 0xff);
out[i * 4 + 2] = (uint8_t) ((in.v[i] >> 16) & 0xff);
out[i * 4 + 3] = (uint8_t) ((in.v[i] >> 24) & 0xff);
}
}
static kit_bigint_t kit_bi_deserialize(uint8_t *in) {
ptrdiff_t i;
kit_bigint_t out;
assert(in != NULL);
memset(&out, 0, sizeof out);
for (i = 0; i < KIT_BIGINT_SIZE; i++)
out.v[i / 4] |= ((uint32_t) in[i]) << (8 * (i % 4));
return out;
}
static uint8_t kit_bin_digit(char hex) {
assert(hex == '0' || hex == '1');
return hex == '1' ? 1 : 0;
}
static kit_bigint_t kit_bi_from_bin(kit_str_t bin) {
kit_bigint_t z;
ptrdiff_t i;
memset(&z, 0, sizeof z);
for (i = 0; i < bin.size && i / 8 < KIT_BIGINT_SIZE; i++) {
uint8_t digit = kit_bin_digit(bin.values[bin.size - i - 1]);
z.v[i / 32] |= digit << (i % 32);
}
return z;
}
static uint8_t kit_dec_digit(char c) {
assert('c' >= '0' && c <= '9');
return c >= '0' && c <= '9' ? (uint8_t) (c - '0') : 0;
}
static kit_bigint_t kit_bi_from_dec(kit_str_t dec) {
kit_bigint_t z = kit_bi_uint32(0);
kit_bigint_t factor = kit_bi_uint32(1);
ptrdiff_t i;
for (i = 0; i < dec.size; i++) {
uint32_t digit = kit_dec_digit(dec.values[dec.size - i - 1]);
z = kit_bi_add(z, kit_bi_mul_uint32(factor, digit));
factor = kit_bi_mul_uint32(factor, 10);
}
return z;
}
static uint8_t kit_hex_digit(char hex) {
assert((hex >= '0' && hex <= '9') || (hex >= 'a' && hex <= 'f') ||
(hex >= 'A' && hex <= 'F'));
if (hex >= '0' && hex <= '9')
return hex - '0';
if (hex >= 'a' && hex <= 'f')
return hex - 'a';
if (hex >= 'A' && hex <= 'F')
return hex - 'A';
return 0;
}
static kit_bigint_t kit_bi_from_hex(kit_str_t hex) {
kit_bigint_t z;
ptrdiff_t i;
memset(&z, 0, sizeof z);
for (i = 0; i < hex.size && i / 2 < KIT_BIGINT_SIZE; i++) {
uint8_t digit = kit_hex_digit(hex.values[hex.size - i - 1]);
z.v[i / 8] |= digit << (4 * (i % 8));
}
return z;
}
static uint8_t KIT_BASE32_DIGITS[] = {
['1'] = 0, ['2'] = 1, ['3'] = 2, ['4'] = 3, ['5'] = 4,
['6'] = 5, ['7'] = 6, ['8'] = 7, ['9'] = 8, ['a'] = 9,
['b'] = 10, ['c'] = 11, ['d'] = 12, ['e'] = 13, ['f'] = 14,
['g'] = 15, ['h'] = 16, ['j'] = 17, ['k'] = 18, ['m'] = 19,
['n'] = 20, ['p'] = 21, ['q'] = 22, ['r'] = 23, ['s'] = 24,
['t'] = 25, ['u'] = 26, ['v'] = 27, ['w'] = 28, ['x'] = 29,
['y'] = 30, ['z'] = 31
};
static uint8_t kit_base32_digit(char c) {
assert(c >= '\0' && c < sizeof KIT_BASE32_DIGITS);
assert(c == '1' ||
KIT_BASE32_DIGITS[(size_t) (unsigned char) c] != 0);
return c >= '\0' && c < sizeof KIT_BASE32_DIGITS
? KIT_BASE32_DIGITS[(size_t) (unsigned char) c]
: 0;
}
static kit_bigint_t kit_bi_from_base32(kit_str_t base32) {
kit_bigint_t z;
ptrdiff_t i;
memset(&z, 0, sizeof z);
for (i = 0; i < base32.size; i++) {
z = kit_bi_shl_uint(z, 5 * i);
z.v[0] |= kit_base32_digit(base32.values[i]);
}
return z;
}
static uint8_t KIT_BASE58_DIGITS[] = {
['1'] = 0, ['2'] = 1, ['3'] = 2, ['4'] = 3, ['5'] = 4,
['6'] = 5, ['7'] = 6, ['8'] = 7, ['9'] = 8, ['A'] = 9,
['B'] = 10, ['C'] = 11, ['D'] = 12, ['E'] = 13, ['F'] = 14,
['G'] = 15, ['H'] = 16, ['J'] = 17, ['K'] = 18, ['L'] = 19,
['M'] = 20, ['N'] = 21, ['P'] = 22, ['Q'] = 23, ['R'] = 24,
['S'] = 25, ['T'] = 26, ['U'] = 27, ['V'] = 28, ['W'] = 29,
['X'] = 30, ['Y'] = 31, ['Z'] = 32, ['a'] = 33, ['b'] = 34,
['c'] = 35, ['d'] = 36, ['e'] = 37, ['f'] = 38, ['g'] = 39,
['h'] = 40, ['i'] = 41, ['j'] = 42, ['k'] = 43, ['m'] = 44,
['n'] = 45, ['o'] = 46, ['p'] = 47, ['q'] = 48, ['r'] = 49,
['s'] = 50, ['t'] = 51, ['u'] = 52, ['v'] = 53, ['w'] = 54,
['x'] = 55, ['y'] = 56, ['z'] = 57
};
static uint8_t kit_base58_digit(char c) {
assert(c >= '\0' && c < sizeof KIT_BASE58_DIGITS);
assert(c == '1' ||
KIT_BASE58_DIGITS[(size_t) (unsigned char) c] != 0);
return c >= '\0' && c < sizeof KIT_BASE58_DIGITS
? KIT_BASE58_DIGITS[(size_t) (unsigned char) c]
: 0;
}
static kit_bigint_t kit_bi_from_base58(kit_str_t base58) {
kit_bigint_t z = kit_bi_uint32(0);
kit_bigint_t factor = kit_bi_uint32(1);
ptrdiff_t i;
for (i = 0; i < base58.size; i++) {
uint32_t digit = kit_base58_digit(
base58.values[base58.size - i - 1]);
z = kit_bi_add(z, kit_bi_mul_uint32(factor, digit));
factor = kit_bi_mul_uint32(factor, 58);
}
return z;
}
#ifdef __GNUC__
# pragma GCC pop_options
# pragma GCC diagnostic pop
#endif
#define KIT_BIN(static_str_) \
kit_bi_from_bin(kit_str(sizeof(static_str_) - 1, (static_str_)))
#define KIT_DEC(static_str_) \
kit_bi_from_dec(kit_str(sizeof(static_str_) - 1, (static_str_)))
#define KIT_HEX(static_str_) \
kit_bi_from_hex(kit_str(sizeof(static_str_) - 1, (static_str_)))
#define KIT_BASE32(static_str_) \
kit_bi_from_base32(kit_str(sizeof(static_str_) - 1, (static_str_)))
#define KIT_BASE58(static_str_) \
kit_bi_from_base58(kit_str(sizeof(static_str_) - 1, (static_str_)))
#ifndef KIT_DISABLE_SHORT_NAMES
# define bigint_t kit_bigint_t
# define bi_uint32 kit_bi_uint32
# define bi_uint64 kit_bi_uint64
# define bi_int32 kit_bi_int32
# define bi_int64 kit_bi_int64
# define bi_is_zero kit_bi_is_zero
# define bi_is_neg kit_bi_is_neg
# define bi_equal kit_bi_equal
# define bi_compare kit_bi_compare
# define bi_carry kit_bi_carry
# define bi_inc kit_bi_inc
# define bi_dec kit_bi_dec
# define bi_add kit_bi_add
# define bi_neg kit_bi_neg
# define bi_sub kit_bi_sub
# define bi_mul kit_bi_mul
# define bi_div kit_bi_div
# define bi_serialize kit_bi_serialize
# define bi_deserialize kit_bi_deserialize
# define BIN KIT_BIN
# define DEC KIT_DEC
# define HEX KIT_HEX
# define BASE32 KIT_BASE32
# define BASE58 KIT_BASE58
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/input_stream.h *
* *
*********************************************************************/
#ifndef KIT_INPUT_STREAM_H
#define KIT_INPUT_STREAM_H
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef ptrdiff_t (*kit_is_read_fn)(void *state,
kit_str_t destination);
typedef struct {
void *state;
kit_is_read_fn read;
} kit_is_handle_t;
kit_is_handle_t kit_is_wrap_string(kit_str_t string,
kit_allocator_t alloc);
kit_is_handle_t kit_is_wrap_file(FILE *f, kit_allocator_t alloc);
void kit_is_destroy(kit_is_handle_t in);
#define KIT_IS_WRAP_STRING(string) \
kit_is_wrap_string((string), kit_alloc_default())
#define KIT_IS_WRAP_FILE(f) kit_is_wrap_file((f), kit_alloc_default())
#define KIT_IS_READ(in, destination) \
(in).read((in).state, (destination))
#ifndef KIT_DISABLE_SHORT_NAMES
# define is_read_fn kit_is_read_fn
# define is_handle_t kit_is_handle_t
# define is_wrap_string kit_is_wrap_string
# define is_wrap_file kit_is_wrap_file
# define is_destroy kit_is_destroy
# define IS_WRAP_STRING KIT_IS_WRAP_STRING
# define IS_WRAP_FILE KIT_IS_WRAP_FILE
# define IS_READ KIT_IS_READ
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/input_buffer.h *
* *
*********************************************************************/
#ifndef KIT_INPUT_BUFFER_H
#define KIT_INPUT_BUFFER_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
kit_status_t status;
ptrdiff_t offset;
void *internal;
kit_string_t data;
} kit_ib_handle_t;
kit_ib_handle_t kit_ib_wrap(kit_is_handle_t upstream,
kit_allocator_t alloc);
kit_ib_handle_t kit_ib_read(kit_ib_handle_t buf, ptrdiff_t size);
typedef int (*kit_ib_read_condition_fn)(kit_str_t data);
kit_ib_handle_t kit_ib_read_while(kit_ib_handle_t buf,
kit_ib_read_condition_fn condition);
void kit_ib_destroy(kit_ib_handle_t buf);
#define KIT_IB_WRAP(upstream) \
kit_ib_wrap(upstream, kit_alloc_default())
#ifndef KIT_DISABLE_SHORT_NAMES
# define ib_handle_t kit_ib_handle_t
# define ib_read_condition_fn kit_ib_read_condition_fn
# define ib_wrap kit_ib_wrap
# define ib_read kit_ib_read
# define ib_read_while kit_ib_read_while
# define ib_destroy kit_ib_destroy
# define IB_WRAP KIT_IB_WRAP
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/async_function.h *
* *
*********************************************************************/
#ifndef KIT_ASYNC_FUNCTION_H
#define KIT_ASYNC_FUNCTION_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
#endif
typedef struct {
int _;
} kit_af_void;
typedef void (*kit_af_state_machine)(void *self_void_);
#define KIT_AF_STATE_DATA \
struct { \
int _index; \
ptrdiff_t _id; \
kit_af_state_machine _state_machine; \
}
typedef struct {
KIT_AF_STATE_DATA;
} kit_af_type_void;
#define KIT_AF_INTERNAL(coro_) (*((kit_af_type_void *) (coro_)))
#ifdef KIT_ENABLE_CUSTOM_ASYNC_FUNCTION_DISPATCH
/* Application should implement this function if custom async
* function dispatch is enabled.
*
* See KIT_ENABLE_CUSTOM_ASYNC_FUNCTION_DISPATCH macro.
*/
void kit_async_function_dispatch(void *promise);
#else
static void kit_async_function_dispatch(void *promise) {
/* Dynamic dispatch by default.
*/
KIT_AF_INTERNAL(promise)._state_machine(promise);
}
#endif
#ifdef __GNUC__
# pragma GCC diagnostic pop
#endif
#define KIT_AF_STATE(ret_type_, name_, ...) \
struct name_##_coro_state_ { \
KIT_AF_STATE_DATA; \
ret_type_ return_value; \
__VA_ARGS__ \
}
#define KIT_AF_DECL(name_) void name_(void *self_void_)
#define KIT_CORO_IMPL(name_) \
KIT_AF_DECL(name_) { \
struct name_##_coro_state_ *self = \
(struct name_##_coro_state_ *) self_void_; \
switch (self->_index) { \
case 0:;
#define KIT_AF_LINE_() __LINE__
#define KIT_CORO_END \
} \
self->_index = -1; \
}
#define KIT_CORO_DECL(ret_type_, name_, ...) \
KIT_AF_STATE(ret_type_, name_, __VA_ARGS__); \
KIT_AF_DECL(name_)
#define KIT_CORO(ret_type_, name_, ...) \
KIT_AF_STATE(ret_type_, name_, __VA_ARGS__); \
KIT_CORO_IMPL(name_)
#define KIT_CORO_DECL_VOID(name_, ...) \
KIT_CORO_DECL(kit_af_void, name_, __VA_ARGS__)
#define KIT_CORO_VOID(name_, ...) \
KIT_CORO(kit_af_void, name_, __VA_ARGS__)
#define KIT_STATIC_CORO(ret_type_, name_, ...) \
KIT_AF_STATE(ret_type_, name_, __VA_ARGS__); \
static KIT_CORO_IMPL(name_)
#define KIT_STATIC_CORO_VOID(name_, ...) \
KIT_STATIC_CORO(kit_af_void, name_, __VA_ARGS__)
#define KIT_AF_EXECUTE(promise_) \
kit_async_function_dispatch(&(promise_))
#define KIT_AF_NEXT(promise_) \
(kit_async_function_dispatch(&(promise_)), (promise_).return_value)
#define KIT_AF_YIELD(...) \
do { \
self->_index = KIT_AF_LINE_(); \
self->return_value = __VA_ARGS__; \
return; \
case KIT_AF_LINE_():; \
} while (0)
#define KIT_AF_YIELD_VOID \
do { \
self->_index = KIT_AF_LINE_(); \
return; \
case KIT_AF_LINE_():; \
} while (0)
#define KIT_AF_RETURN(...) \
do { \
self->_index = -1; \
self->return_value = __VA_ARGS__; \
return; \
} while (0)
#define KIT_AF_RETURN_VOID \
do { \
self->_index = -1; \
return; \
} while (0)
#define KIT_AF_AWAIT(promise_) \
do { \
case KIT_AF_LINE_(): \
if ((promise_)._index != -1) { \
self->_index = KIT_AF_LINE_(); \
kit_async_function_dispatch(&(promise_)); \
} \
if ((promise_)._index != -1) \
return; \
} while (0)
#define KIT_AF_YIELD_AWAIT(promise_) \
do { \
case KIT_AF_LINE_(): \
if ((promise_)._index != -1) { \
self->_index = KIT_AF_LINE_(); \
kit_async_function_dispatch(&(promise_)); \
self->return_value = (promise_).return_value; \
return; \
} \
} while (0)
#define KIT_AF_TYPE(coro_) struct coro_##_coro_state_
#define KIT_AF_INITIAL(id_, coro_) \
._index = 0, ._id = (id_), ._state_machine = (coro_)
#define KIT_AF_CREATE(promise_, coro_, ...) \
KIT_AF_TYPE(coro_) \
promise_ = { KIT_AF_INITIAL(0, coro_), __VA_ARGS__ }
#define KIT_AF_CREATE_ID(promise_, id_, ...) \
KIT_AF_TYPE(coro_) \
promise_ = { KIT_AF_INITIAL(id_, NULL), __VA_ARGS__ }
#define KIT_AF_INIT(promise_, coro_, ...) \
do { \
KIT_AF_CREATE(kit_af_temp_, coro_, __VA_ARGS__); \
memcpy(&(promise_), &kit_af_temp_, sizeof kit_af_temp_); \
} while (0)
#define KIT_AF_INIT_ID(promise_, id_, ...) \
do { \
KIT_AF_CREATE_ID(kit_af_temp_, id_, __VA_ARGS__); \
memcpy(&(promise_), &kit_af_temp_, sizeof kit_af_temp_); \
} while (0)
#define KIT_AF_FINISHED(promise_) ((promise_)._index == -1)
#define KIT_AF_FINISHED_N(return_, promises_, size_) \
do { \
int kit_af_index_; \
(return_) = 1; \
for (kit_af_index_ = 0; kit_af_index_ < (size_); \
kit_af_index_++) \
if (!KIT_AF_FINISHED((promises_)[kit_af_index_])) { \
(return_) = 0; \
break; \
} \
} while (0)
#define KIT_AF_FINISHED_ALL(return_, promises_) \
KIT_AF_FINISHED_N((return_), (promises_), \
sizeof(promises_) / sizeof((promises_)[0]))
#ifndef KIT_DISABLE_SHORT_NAMES
# define af_void kit_af_void
# define af_state_machine kit_af_state_machine
# define af_type_void kit_af_type_void
# define AF_STATE_DATA KIT_AF_STATE_DATA
# define AF_STATE KIT_AF_STATE
# define AF_DECL KIT_AF_DECL
# define CORO_IMPL KIT_CORO_IMPL
# define CORO_END KIT_CORO_END
# define CORO_DECL KIT_CORO_DECL
# define CORO KIT_CORO
# define CORO_DECL_VOID KIT_CORO_DECL_VOID
# define STATIC_CORO KIT_STATIC_CORO
# define STATIC_CORO_VOID KIT_STATIC_CORO_VOID
# define CORO_VOID KIT_CORO_VOID
# define AF_EXECUTE KIT_AF_EXECUTE
# define AF_NEXT KIT_AF_NEXT
# define AF_YIELD KIT_AF_YIELD
# define AF_YIELD_VOID KIT_AF_YIELD_VOID
# define AF_RETURN KIT_AF_RETURN
# define AF_RETURN_VOID KIT_AF_RETURN_VOID
# define AF_AWAIT KIT_AF_AWAIT
# define AF_YIELD_AWAIT KIT_AF_YIELD_AWAIT
# define AF_TYPE KIT_AF_TYPE
# define AF_INITIAL KIT_AF_INITIAL
# define AF_CREATE KIT_AF_CREATE
# define AF_INIT KIT_AF_INIT
# define AF_FINISHED KIT_AF_FINISHED
# define AF_FINISHED_N KIT_AF_FINISHED_N
# define AF_FINISHED_ALL KIT_AF_FINISHED_ALL
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/file.h *
* *
*********************************************************************/
#ifndef KIT_FILE_H
#define KIT_FILE_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(_WIN32) && !defined(__CYGWIN__)
# define KIT_PATH_DELIM_C '\\'
# define KIT_PATH_DELIM "\\"
# define KIT_ENV_HOME "USERPROFILE"
#else
# define KIT_PATH_DELIM_C '/'
# define KIT_PATH_DELIM "/"
# define KIT_ENV_HOME "HOME"
#endif
kit_string_t kit_path_norm(kit_str_t path, kit_allocator_t alloc);
kit_string_t kit_path_join(kit_str_t left, kit_str_t right,
kit_allocator_t alloc);
kit_string_t kit_path_user(kit_allocator_t alloc);
kit_string_t kit_path_cache(kit_allocator_t alloc);
kit_str_t kit_path_index(kit_str_t path, ptrdiff_t index);
kit_str_t kit_path_take(kit_str_t path, ptrdiff_t count);
kit_status_t kit_file_create_folder(kit_str_t path);
kit_status_t kit_file_create_folder_recursive(kit_str_t path);
kit_status_t kit_file_remove(kit_str_t path);
kit_status_t kit_file_remove_folder(kit_str_t path);
kit_status_t kit_file_remove_recursive(kit_str_t path,
kit_allocator_t alloc);
typedef enum {
KIT_PATH_NONE,
KIT_PATH_FILE,
KIT_PATH_FOLDER
} kit_path_type_t;
kit_path_type_t kit_path_type(kit_str_t path);
typedef struct {
kit_status_t status;
int64_t time_modified_sec;
int32_t time_modified_nsec;
int64_t size;
} kit_file_info_t;
kit_file_info_t kit_file_info(kit_str_t path);
typedef struct {
kit_status_t status;
KIT_DA(kit_string_t) files;
} kit_path_list_t;
kit_path_list_t kit_file_enum_folder(kit_str_t path,
kit_allocator_t alloc);
void kit_path_list_destroy(kit_path_list_t list);
#ifndef KIT_DISABLE_SHORT_NAMES
# define path_norm kit_path_norm
# define path_join kit_path_join
# define path_user kit_path_user
# define path_cache kit_path_cache
# define path_index kit_path_index
# define path_take kit_path_take
# define file_create_folder kit_file_create_folder
# define file_create_folder_recursive \
kit_file_create_folder_recursive
# define file_remove kit_file_remove
# define file_remove_folder kit_file_remove_folder
# define file_remove_recursive kit_file_remove_recursive
# define path_type_t kit_path_type_t
# define path_type kit_path_type
# define file_info_t kit_file_info_t
# define file_info kit_file_info
# define path_list_t kit_path_list_t
# define file_enum_folder kit_file_enum_folder
# define path_list_destroy kit_path_list_destroy
# define PATH_DELIM_C KIT_PATH_DELIM_C
# define PATH_DELIM KIT_PATH_DELIM
# define ENV_HOME KIT_ENV_HOME
# define PATH_NONE KIT_PATH_NONE
# define PATH_FILE KIT_PATH_FILE
# define PATH_FOLDER KIT_PATH_FOLDER
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/mersenne_twister_64.h *
* *
*********************************************************************/
#ifndef KIT_MERSENNE_TWISTER_64_H
#define KIT_MERSENNE_TWISTER_64_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
KIT_MT64_N = 312,
};
typedef struct {
uint64_t mt[KIT_MT64_N];
uint64_t index;
} kit_mt64_state_t;
void kit_mt64_init_array(kit_mt64_state_t *state, ptrdiff_t size,
uint64_t *seed);
void kit_mt64_init(kit_mt64_state_t *state, uint64_t seed);
void kit_mt64_rotate(kit_mt64_state_t *state);
uint64_t kit_mt64_generate(kit_mt64_state_t *state);
#ifndef KIT_DISABLE_SHORT_NAMES
# define mt64_state_t kit_mt64_state_t
# define mt64_init_array kit_mt64_init_array
# define mt64_init kit_mt64_init
# define mt64_rotate kit_mt64_rotate
# define mt64_generate kit_mt64_generate
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/secure_random.h *
* *
*********************************************************************/
#ifndef KIT_SECURE_RANDOM_H
#define KIT_SECURE_RANDOM_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void kit_secure_random(ptrdiff_t size, void *data);
#ifndef KIT_DISABLE_SHORT_NAMES
# define secure_random kit_secure_random
#endif
#ifdef __cplusplus
}
#endif
#endif
/*********************************************************************
* *
* File: source/kit/sha256.h *
* *
*********************************************************************/
#ifndef KIT_SHA256_H
#define KIT_SHA256_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { KIT_SHA256_BLOCK_SIZE = 32 };
typedef struct {
uint8_t v[KIT_SHA256_BLOCK_SIZE];
} kit_sha256_hash_t;
kit_sha256_hash_t kit_sha256(ptrdiff_t size, uint8_t *data);
#ifdef __cplusplus
}
#endif
#ifndef KIT_DISABLE_SHORT_NAMES
# define SHA256_BLOCK_SIZE KIT_SHA256_BLOCK_SIZE
# define sha256_hash_t kit_sha256_hash_t
# define sha256 kit_sha256
#endif
#endif
/*********************************************************************
* *
* File: source/kit/sockets.h *
* *
*********************************************************************/
#ifndef KIT_SOCKETS_H
#define KIT_SOCKETS_H
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#ifndef KIT_DISABLE_SYSTEM_SOCKETS
# ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# endif
# if defined(_WIN32) && !defined(__CYGWIN__)
# define WIN32_LEAN_AND_MEAN
# include <winsock2.h>
# include <ws2tcpip.h>
# define socket_t SOCKET
# define socklen_t int
# ifdef __cplusplus
extern "C" {
# endif
static kit_status_t kit_sockets_init(void) {
WSADATA data;
memset(&data, 0, sizeof data);
WORD version = MAKEWORD(2, 2);
return WSAStartup(version, &data) == ERROR_SUCCESS
? KIT_OK
: KIT_ERROR_SOCKETS_STARTUP_FAILED;
}
static kit_status_t kit_sockets_cleanup(void) {
WSACleanup();
return KIT_OK;
}
static int kit_socket_set_blocking(socket_t s) {
u_long flag = 0;
return ioctlsocket(s, FIONBIO, &flag) == 0
? KIT_OK
: KIT_ERROR_SOCKET_CONTROL_FAILED;
}
static int kit_socket_set_nonblocking(socket_t s) {
u_long flag = 1;
return ioctlsocket(s, FIONBIO, &flag) == 0
? KIT_OK
: KIT_ERROR_SOCKET_CONTROL_FAILED;
}
# ifdef __cplusplus
}
# endif
# else
# include <arpa/inet.h>
# include <errno.h>
# include <fcntl.h>
# include <netinet/in.h>
# include <signal.h>
# include <sys/ioctl.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <unistd.h>
# define socket_t int
# define closesocket close
# define INVALID_SOCKET -1
# ifdef __cplusplus
extern "C" {
# endif
static kit_status_t kit_sockets_init(void) {
signal(SIGPIPE, SIG_IGN);
return KIT_OK;
}
static kit_status_t kit_sockets_cleanup(void) {
return KIT_OK;
}
static int kit_socket_set_blocking(socket_t s) {
int const flags = fcntl(s, F_GETFL, 0);
return fcntl(s, F_SETFL, flags & ~O_NONBLOCK) == 0
? KIT_OK
: KIT_ERROR_SOCKET_CONTROL_FAILED;
}
static int kit_socket_set_nonblocking(socket_t s) {
int const flags = fcntl(s, F_GETFL, 0);
return fcntl(s, F_SETFL, flags | O_NONBLOCK) == 0
? KIT_OK
: KIT_ERROR_SOCKET_CONTROL_FAILED;
}
# ifdef __cplusplus
}
# endif
# endif
# ifdef __GNUC__
# pragma GCC diagnostic pop
# endif
#endif
#endif
#ifdef KIT_IMPLEMENTATION
/*********************************************************************
* *
* File: source/kit/allocator.c *
* *
*********************************************************************/
#include <assert.h>
#ifndef KIT_DISABLE_SYSTEM_MALLOC
# include <stdlib.h>
#endif
static void *allocate(int request, void *state, ptrdiff_t size,
ptrdiff_t previous_size, void *pointer) {
#ifndef KIT_DISABLE_SYSTEM_MALLOC
switch (request) {
case KIT_ALLOCATE:
assert(previous_size == 0);
assert(pointer == NULL);
return malloc(size);
case KIT_DEALLOCATE:
assert(size == 0);
assert(pointer != NULL);
free(pointer);
return NULL;
case KIT_REALLOCATE:
/* FIXME
* Not implemented.
*/
assert(0);
return NULL;
default: assert(0);
}
#else
assert(0);
#endif
return NULL;
}
#ifndef KIT_ENABLE_CUSTOM_ALLOC_DISPATCH
void *kit_alloc_dispatch(kit_allocator_t alloc, int request,
ptrdiff_t size, ptrdiff_t previous_size,
void *pointer) {
assert(alloc.allocate != NULL);
if (alloc.allocate == NULL)
return NULL;
return alloc.allocate(request, alloc.state, size, previous_size,
pointer);
}
#endif
kit_allocator_t kit_alloc_default(void) {
kit_allocator_t alloc = { .state = NULL, .allocate = allocate };
return alloc;
}
/*********************************************************************
* *
* File: source/kit/thread.posix.c *
* *
*********************************************************************/
#ifndef KIT_DISABLE_SYSTEM_THREADS
# if !defined(_WIN32) || defined(__CYGWIN__)
# include <assert.h>
# include <errno.h>
# include <limits.h>
# include <sched.h>
# include <stdint.h> /* intptr_t */
# include <stdlib.h>
# include <unistd.h>
# ifndef PTHREAD_STACK_MIN
# define PTHREAD_STACK_MIN 16384
# endif
/*
Configuration macro:
EMULATED_THREADS_USE_NATIVE_TIMEDLOCK
Use pthread_mutex_timedlock() for `mtx_timedlock()'
Otherwise use mtx_trylock() + *busy loop* emulation.
*/
# if !defined(__CYGWIN__) && !defined(__APPLE__) && \
!defined(__NetBSD__)
# define EMULATED_THREADS_USE_NATIVE_TIMEDLOCK
# endif
/*
Implementation limits:
- Conditionally emulation for "mutex with timeout"
(see EMULATED_THREADS_USE_NATIVE_TIMEDLOCK macro)
*/
typedef struct {
thrd_start_t func;
void *arg;
kit_allocator_t alloc;
} impl_thrd_param_t;
static void *impl_thrd_routine(void *p) {
impl_thrd_param_t pack = *((impl_thrd_param_t *) p);
kit_alloc_dispatch(pack.alloc, KIT_DEALLOCATE, 0, 0, p);
return (void *) (intptr_t) pack.func(pack.arg);
}
void call_once(once_flag *flag, void (*func)(void)) {
pthread_once(flag, func);
}
int cnd_broadcast(cnd_t *cond) {
assert(cond != NULL);
return (pthread_cond_broadcast(cond) == 0) ? thrd_success
: thrd_error;
}
void cnd_destroy(cnd_t *cond) {
assert(cond);
pthread_cond_destroy(cond);
}
int cnd_init(cnd_t *cond) {
assert(cond != NULL);
return (pthread_cond_init(cond, NULL) == 0) ? thrd_success
: thrd_error;
}
int cnd_signal(cnd_t *cond) {
assert(cond != NULL);
return (pthread_cond_signal(cond) == 0) ? thrd_success : thrd_error;
}
int cnd_timedwait(cnd_t *cond, mtx_t *mtx,
struct timespec const *abs_time) {
int rt;
assert(mtx != NULL);
assert(cond != NULL);
assert(abs_time != NULL);
rt = pthread_cond_timedwait(cond, mtx, abs_time);
if (rt == ETIMEDOUT)
return thrd_timedout;
return (rt == 0) ? thrd_success : thrd_error;
}
int cnd_wait(cnd_t *cond, mtx_t *mtx) {
assert(mtx != NULL);
assert(cond != NULL);
return (pthread_cond_wait(cond, mtx) == 0) ? thrd_success
: thrd_error;
}
void mtx_destroy(mtx_t *mtx) {
assert(mtx != NULL);
pthread_mutex_destroy(mtx);
}
/*
* XXX: Workaround when building with -O0 and without pthreads link.
*
* In such cases constant folding and dead code elimination won't be
* available, thus the compiler will always add the pthread_mutexattr*
* functions into the binary. As we try to link, we'll fail as the
* symbols are unresolved.
*
* Ideally we'll enable the optimisations locally, yet that does not
* seem to work.
*
* So the alternative workaround is to annotate the symbols as weak.
* Thus the linker will be happy and things don't clash when building
* with -O1 or greater.
*/
# if defined(KIT_HAVE_FUNC_ATTRIBUTE_WEAK) && !defined(__CYGWIN__)
__attribute__((weak)) int pthread_mutexattr_init(
pthread_mutexattr_t *attr);
__attribute__((weak)) int pthread_mutexattr_settype(
pthread_mutexattr_t *attr, int type);
__attribute__((weak)) int pthread_mutexattr_destroy(
pthread_mutexattr_t *attr);
# endif
int mtx_init(mtx_t *mtx, int type) {
# ifdef KIT_HAVE_PTHREAD_MUTEXATTR_SETTYPE
pthread_mutexattr_t attr;
# endif
assert(mtx != NULL);
if (type != mtx_plain && type != mtx_timed &&
type != (mtx_plain | mtx_recursive) &&
type != (mtx_timed | mtx_recursive))
return thrd_error;
if ((type & mtx_recursive) == 0) {
pthread_mutex_init(mtx, NULL);
return thrd_success;
}
# ifdef KIT_HAVE_PTHREAD_MUTEXATTR_SETTYPE
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(mtx, &attr);
pthread_mutexattr_destroy(&attr);
return thrd_success;
# else
return thrd_error;
# endif
}
int mtx_lock(mtx_t *mtx) {
assert(mtx != NULL);
return (pthread_mutex_lock(mtx) == 0) ? thrd_success : thrd_error;
}
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) {
assert(mtx != NULL);
assert(ts != NULL);
{
# ifdef EMULATED_THREADS_USE_NATIVE_TIMEDLOCK
int rt;
rt = pthread_mutex_timedlock(mtx, ts);
if (rt == 0)
return thrd_success;
return (rt == ETIMEDOUT) ? thrd_timedout : thrd_error;
# else
time_t expire = time(NULL);
expire += ts->tv_sec;
while (mtx_trylock(mtx) != thrd_success) {
time_t now = time(NULL);
if (expire < now)
return thrd_timedout;
// busy loop!
thrd_yield();
}
return thrd_success;
# endif
}
}
int mtx_trylock(mtx_t *mtx) {
assert(mtx != NULL);
return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy;
}
int mtx_unlock(mtx_t *mtx) {
assert(mtx != NULL);
return (pthread_mutex_unlock(mtx) == 0) ? thrd_success : thrd_error;
}
int thrd_create_with_stack(thrd_t *thr, thrd_start_t func, void *arg,
ptrdiff_t const require_stack_size) {
impl_thrd_param_t *pack;
assert(thr != NULL);
assert(require_stack_size == 0 ||
require_stack_size >= PTHREAD_STACK_MIN);
pthread_attr_t attr;
pthread_attr_t *attr_p = NULL;
if (require_stack_size > 0) {
ptrdiff_t const page_size = (ptrdiff_t) sysconf(_SC_PAGESIZE);
ptrdiff_t const delta = require_stack_size % page_size;
ptrdiff_t const stack_size = delta == 0 ? require_stack_size
: require_stack_size +
page_size - delta;
if (pthread_attr_init(&attr) != 0)
return thrd_nomem;
if (pthread_attr_setstacksize(&attr, (size_t) stack_size) != 0)
return thrd_wrong_stack_size;
attr_p = &attr;
}
kit_allocator_t alloc = kit_alloc_default();
pack = (impl_thrd_param_t *) kit_alloc_dispatch(
alloc, KIT_ALLOCATE, sizeof(impl_thrd_param_t), 0, NULL);
if (!pack) {
if (attr_p)
pthread_attr_destroy(attr_p);
return thrd_nomem;
}
pack->func = func;
pack->arg = arg;
pack->alloc = alloc;
if (pthread_create(thr, attr_p, impl_thrd_routine, pack) != 0) {
kit_alloc_dispatch(alloc, KIT_DEALLOCATE, 0, 0, pack);
if (attr_p)
pthread_attr_destroy(attr_p);
return thrd_error;
}
if (attr_p)
pthread_attr_destroy(attr_p);
return thrd_success;
}
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) {
return thrd_create_with_stack(thr, func, arg, 0);
}
thrd_t thrd_current(void) {
return pthread_self();
}
int thrd_detach(thrd_t thr) {
return (pthread_detach(thr) == 0) ? thrd_success : thrd_error;
}
int thrd_equal(thrd_t thr0, thrd_t thr1) {
return pthread_equal(thr0, thr1);
}
_Noreturn void thrd_exit(int res) {
pthread_exit((void *) (intptr_t) res);
}
int thrd_join(thrd_t thr, int *res) {
void *code;
if (pthread_join(thr, &code) != 0)
return thrd_error;
if (res)
*res = (int) (intptr_t) code;
return thrd_success;
}
int thrd_sleep(const struct timespec *time_point,
struct timespec *remaining) {
assert(time_point != NULL);
return nanosleep(time_point, remaining);
}
void thrd_yield(void) {
sched_yield();
}
# endif
#endif
/*********************************************************************
* *
* File: source/kit/thread.win32.c *
* *
*********************************************************************/
#ifndef KIT_DISABLE_SYSTEM_THREADS
# if defined(_WIN32) && !defined(__CYGWIN__)
# include <assert.h>
# include <errno.h>
# include <limits.h>
# include <process.h>
# include <stdbool.h>
# include <stdlib.h>
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
# endif
# include <Windows.h>
/*
Configuration macro:
EMULATED_THREADS_USE_NATIVE_CALL_ONCE
Use native WindowsAPI one-time initialization function.
(requires WinVista or later)
Otherwise emulate by mtx_trylock() + *busy loop* for WinXP.
EMULATED_THREADS_TSS_DTOR_SLOTNUM
Max registerable TSS dtor number.
*/
# if _WIN32_WINNT >= 0x0600
/* Prefer native WindowsAPI on newer environment. */
# if !defined(__MINGW32__)
# define EMULATED_THREADS_USE_NATIVE_CALL_ONCE
# endif
# endif
# define EMULATED_THREADS_TSS_DTOR_SLOTNUM \
64 /* see TLS_MINIMUM_AVAILABLE */
/* check configuration */
# if defined(EMULATED_THREADS_USE_NATIVE_CALL_ONCE) && \
(_WIN32_WINNT < 0x0600)
# error EMULATED_THREADS_USE_NATIVE_CALL_ONCE requires _WIN32_WINNT>=0x0600
# endif
static_assert(sizeof(cnd_t) == sizeof(CONDITION_VARIABLE),
"The size of cnd_t must equal to CONDITION_VARIABLE");
static_assert(sizeof(thrd_t) == sizeof(HANDLE),
"The size of thrd_t must equal to HANDLE");
static_assert(sizeof(tss_t) == sizeof(DWORD),
"The size of tss_t must equal to DWORD");
static_assert(sizeof(mtx_t) == sizeof(CRITICAL_SECTION),
"The size of mtx_t must equal to CRITICAL_SECTION");
static_assert(sizeof(once_flag) == sizeof(INIT_ONCE),
"The size of once_flag must equal to INIT_ONCE");
/*
Implementation limits:
- Conditionally emulation for "Initialization functions"
(see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro)
- Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
*/
typedef struct {
thrd_start_t func;
void *arg;
thrd_t thrd;
kit_allocator_t alloc;
} impl_thrd_param_t;
struct thrd_state {
thrd_t thrd;
bool handle_need_close;
};
static thread_local struct thrd_state impl_current_thread = { 0 };
static unsigned __stdcall impl_thrd_routine(void *p) {
impl_thrd_param_t *pack_p = (impl_thrd_param_t *) p;
impl_thrd_param_t pack;
int code;
impl_current_thread.thrd = pack_p->thrd;
impl_current_thread.handle_need_close = false;
memcpy(&pack, pack_p, sizeof(impl_thrd_param_t));
kit_alloc_dispatch(pack.alloc, KIT_DEALLOCATE, 0, 0, p);
code = pack.func(pack.arg);
return (unsigned) code;
}
static time_t impl_timespec2msec(const struct timespec *ts) {
return (ts->tv_sec * 1000U) + (ts->tv_nsec / 1000000L);
}
static DWORD impl_abs2relmsec(const struct timespec *abs_time) {
const time_t abs_ms = impl_timespec2msec(abs_time);
struct timespec now;
timespec_get(&now, TIME_UTC);
const time_t now_ms = impl_timespec2msec(&now);
const DWORD rel_ms = (abs_ms > now_ms) ? (DWORD) (abs_ms - now_ms)
: 0;
return rel_ms;
}
# ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
struct impl_call_once_param {
void (*func)(void);
};
static BOOL CALLBACK impl_call_once_callback(PINIT_ONCE InitOnce,
PVOID Parameter,
PVOID *Context) {
struct impl_call_once_param *param = (struct impl_call_once_param *)
Parameter;
(param->func)();
((void) InitOnce);
((void) Context); /* suppress warning */
return TRUE;
}
# endif /* ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE */
static struct impl_tss_dtor_entry {
tss_t key;
tss_dtor_t dtor;
} impl_tss_dtor_tbl[EMULATED_THREADS_TSS_DTOR_SLOTNUM];
static int impl_tss_dtor_register(tss_t key, tss_dtor_t dtor) {
int i;
for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) {
if (!impl_tss_dtor_tbl[i].dtor)
break;
}
if (i == EMULATED_THREADS_TSS_DTOR_SLOTNUM)
return 1;
impl_tss_dtor_tbl[i].key = key;
impl_tss_dtor_tbl[i].dtor = dtor;
return 0;
}
static void impl_tss_dtor_invoke(void) {
int i;
for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) {
if (impl_tss_dtor_tbl[i].dtor) {
void *val = (void *) (size_t) TlsGetValue(
impl_tss_dtor_tbl[i].key);
if (val)
(impl_tss_dtor_tbl[i].dtor)(val);
}
}
}
void call_once(once_flag *flag, void (*func)(void)) {
assert(flag && func);
# ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
{
struct impl_call_once_param param;
param.func = func;
InitOnceExecuteOnce((PINIT_ONCE) flag, impl_call_once_callback,
(PVOID) ¶m, NULL);
}
# else
if (InterlockedCompareExchangePointer(
(PVOID volatile *) &flag->status, (PVOID) 1, (PVOID) 0) ==
0) {
(func)();
InterlockedExchangePointer((PVOID volatile *) &flag->status,
(PVOID) 2);
} else {
while (flag->status == 1) {
// busy loop!
thrd_yield();
}
}
# endif
}
int cnd_broadcast(cnd_t *cond) {
assert(cond != NULL);
WakeAllConditionVariable((PCONDITION_VARIABLE) cond);
return thrd_success;
}
void cnd_destroy(cnd_t *cond) {
assert(cond != NULL);
/* do nothing */
(void) cond;
}
int cnd_init(cnd_t *cond) {
assert(cond != NULL);
InitializeConditionVariable((PCONDITION_VARIABLE) cond);
return thrd_success;
}
int cnd_signal(cnd_t *cond) {
assert(cond != NULL);
WakeConditionVariable((PCONDITION_VARIABLE) cond);
return thrd_success;
}
int cnd_timedwait(cnd_t *cond, mtx_t *mtx,
const struct timespec *abs_time) {
assert(cond != NULL);
assert(mtx != NULL);
assert(abs_time != NULL);
const DWORD timeout = impl_abs2relmsec(abs_time);
if (SleepConditionVariableCS((PCONDITION_VARIABLE) cond,
(PCRITICAL_SECTION) mtx, timeout))
return thrd_success;
return (GetLastError() == ERROR_TIMEOUT) ? thrd_timedout
: thrd_error;
}
int cnd_wait(cnd_t *cond, mtx_t *mtx) {
assert(cond != NULL);
assert(mtx != NULL);
SleepConditionVariableCS((PCONDITION_VARIABLE) cond,
(PCRITICAL_SECTION) mtx, INFINITE);
return thrd_success;
}
void mtx_destroy(mtx_t *mtx) {
assert(mtx);
DeleteCriticalSection((PCRITICAL_SECTION) mtx);
}
int mtx_init(mtx_t *mtx, int type) {
assert(mtx != NULL);
if (type != mtx_plain && type != mtx_timed &&
type != (mtx_plain | mtx_recursive) &&
type != (mtx_timed | mtx_recursive))
return thrd_error;
InitializeCriticalSection((PCRITICAL_SECTION) mtx);
return thrd_success;
}
int mtx_lock(mtx_t *mtx) {
assert(mtx != NULL);
EnterCriticalSection((PCRITICAL_SECTION) mtx);
return thrd_success;
}
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) {
assert(mtx != NULL);
assert(ts != NULL);
while (mtx_trylock(mtx) != thrd_success) {
if (impl_abs2relmsec(ts) == 0)
return thrd_timedout;
/* busy loop! */
thrd_yield();
}
return thrd_success;
}
int mtx_trylock(mtx_t *mtx) {
assert(mtx != NULL);
return TryEnterCriticalSection((PCRITICAL_SECTION) mtx)
? thrd_success
: thrd_busy;
}
int mtx_unlock(mtx_t *mtx) {
assert(mtx != NULL);
LeaveCriticalSection((PCRITICAL_SECTION) mtx);
return thrd_success;
}
int thrd_create_with_stack(thrd_t *thr, thrd_start_t func, void *arg,
ptrdiff_t const stack_size) {
impl_thrd_param_t *pack;
uintptr_t handle;
assert(thr != NULL);
assert(stack_size >= 0 && stack_size < 0x100000000);
kit_allocator_t alloc = kit_alloc_default();
pack = (impl_thrd_param_t *) kit_alloc_dispatch(
alloc, KIT_ALLOCATE, (sizeof(impl_thrd_param_t)), 0, NULL);
if (!pack)
return thrd_nomem;
pack->func = func;
pack->arg = arg;
pack->alloc = alloc;
handle = _beginthreadex(NULL, (unsigned) stack_size,
impl_thrd_routine, pack, CREATE_SUSPENDED,
NULL);
if (handle == 0) {
kit_alloc_dispatch(alloc, KIT_DEALLOCATE, 0, 0, pack);
if (errno == EAGAIN || errno == EACCES)
return thrd_nomem;
return thrd_error;
}
thr->handle = (void *) handle;
pack->thrd = *thr;
ResumeThread((HANDLE) handle);
return thrd_success;
}
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) {
return thrd_create_with_stack(thr, func, arg, 0);
}
thrd_t thrd_current(void) {
/* GetCurrentThread() returns a pseudo-handle, which we need
* to pass to DuplicateHandle(). Only the resulting handle can be
* used from other threads.
*
* Note that neither handle can be compared to the one by
* thread_create. Only the thread IDs - as returned by GetThreadId()
* and GetCurrentThreadId() can be compared directly.
*
* Other potential solutions would be:
* - define thrd_t as a thread Ids, but this would mean we'd need to
* OpenThread for many operations
* - use malloc'ed memory for thrd_t. This would imply using TLS for
* current thread.
*
* Neither is particularly nice.
*
* Life would be much easier if C11 threads had different
* abstractions for threads and thread IDs, just like C++11 threads
* does...
*/
struct thrd_state *state = &impl_current_thread;
if (state->thrd.handle == NULL) {
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
GetCurrentProcess(), &(state->thrd.handle),
0, FALSE, DUPLICATE_SAME_ACCESS)) {
abort();
}
state->handle_need_close = true;
}
return state->thrd;
}
int thrd_detach(thrd_t thr) {
CloseHandle(thr.handle);
return thrd_success;
}
int thrd_equal(thrd_t thr0, thrd_t thr1) {
return GetThreadId(thr0.handle) == GetThreadId(thr1.handle);
}
_Noreturn void thrd_exit(int res) {
_endthreadex((unsigned) res);
}
int thrd_join(thrd_t thr, int *res) {
DWORD w, code;
if (thr.handle == NULL) {
return thrd_error;
}
w = WaitForSingleObject(thr.handle, INFINITE);
if (w != WAIT_OBJECT_0)
return thrd_error;
if (res) {
if (!GetExitCodeThread(thr.handle, &code)) {
CloseHandle(thr.handle);
return thrd_error;
}
*res = (int) code;
}
CloseHandle(thr.handle);
return thrd_success;
}
int thrd_sleep(const struct timespec *time_point,
struct timespec *remaining) {
(void) remaining;
assert(time_point);
assert(!remaining); /* not implemented */
Sleep((DWORD) impl_timespec2msec(time_point));
return 0;
}
void thrd_yield(void) {
SwitchToThread();
}
# endif
#endif
/*********************************************************************
* *
* File: source/kit/atomic.win32.c *
* *
*********************************************************************/
#ifdef _MSC_VER
static_assert(sizeof(char) == 1, "Wrong char size");
static_assert(sizeof(short) == 2, "Wrong short size");
static_assert(sizeof(int) == 4, "Wrong int size");
# include <intrin.h>
void kit_atomic_store_explicit_8(uint8_t volatile *var, uint8_t value,
int memory_order) {
char volatile *dst = (char volatile *) var;
char src = (char) value;
switch (memory_order) {
case memory_order_relaxed: *dst = src; break;
default: _InterlockedExchange8(dst, src);
}
}
void kit_atomic_store_explicit_16(uint16_t volatile *var,
uint16_t value, int memory_order) {
short volatile *dst = (short volatile *) var;
short src = (short) value;
switch (memory_order) {
case memory_order_relaxed: *dst = src; break;
default: _InterlockedExchange16(dst, src);
}
}
void kit_atomic_store_explicit_32(uint32_t volatile *var,
uint32_t value, int memory_order) {
int volatile *dst = (int volatile *) var;
int src = (int) value;
switch (memory_order) {
case memory_order_relaxed: *dst = src; break;
default: _InterlockedExchange(dst, src);
}
}
void kit_atomic_store_explicit_64(uint64_t volatile *var,
uint64_t value, int memory_order) {
__int64 volatile *dst = (__int64 volatile *) var;
__int64 src = (__int64) value;
switch (memory_order) {
case memory_order_relaxed: *dst = src; break;
default:
# ifdef _WIN64
_InterlockedExchange64(dst, src);
# else
_InterlockedExchange((int volatile *) dst, (int) src);
# endif
}
}
uint8_t kit_atomic_load_explicit_8(volatile uint8_t *var,
int memory_order) {
char volatile *dst = (char volatile *) var;
if (memory_order == memory_order_relaxed)
return (uint8_t) *dst;
return (uint8_t) _InterlockedOr8(dst, 0);
}
uint16_t kit_atomic_load_explicit_16(uint16_t volatile *var,
int memory_order) {
short volatile *dst = (short volatile *) var;
if (memory_order == memory_order_relaxed)
return (uint16_t) *dst;
return (uint16_t) _InterlockedOr16(dst, 0);
}
uint32_t kit_atomic_load_explicit_32(uint32_t volatile *var,
int memory_order) {
int volatile *dst = (int volatile *) var;
if (memory_order == memory_order_relaxed)
return (uint32_t) *dst;
return (uint32_t) _InterlockedOr(dst, 0);
}
uint64_t kit_atomic_load_explicit_64(uint64_t volatile *var,
int memory_order) {
__int64 volatile *dst = (__int64 volatile *) var;
if (memory_order == memory_order_relaxed)
return (uint64_t) *dst;
# ifdef _WIN64
return (uint64_t) _InterlockedOr64(dst, 0);
# else
return (uint64_t) _InterlockedOr((int volatile *) dst, 0);
# endif
}
uint8_t kit_atomic_exchange_explicit_8(volatile uint8_t *var,
uint8_t value,
int memory_order) {
char volatile *dst = (char volatile *) var;
char src = (char) value;
return (uint8_t) _InterlockedExchange8(dst, src);
}
uint16_t kit_atomic_exchange_explicit_16(uint16_t volatile *var,
uint16_t value,
int memory_order) {
short volatile *dst = (short volatile *) var;
short src = (short) value;
return (uint16_t) _InterlockedExchange16(dst, src);
}
uint32_t kit_atomic_exchange_explicit_32(uint32_t volatile *var,
uint32_t value,
int memory_order) {
int volatile *dst = (int volatile *) var;
int src = (int) value;
return (uint32_t) _InterlockedExchange(dst, src);
}
uint64_t kit_atomic_exchange_explicit_64(uint64_t volatile *var,
uint64_t value,
int memory_order) {
__int64 volatile *dst = (__int64 volatile *) var;
__int64 src = (__int64) value;
# ifdef _WIN64
return (uint64_t) _InterlockedExchange64(dst, src);
# else
return (uint64_t) _InterlockedExchange((int volatile *) dst,
(int) src);
# endif
}
uint8_t kit_atomic_fetch_add_explicit_8(volatile uint8_t *var,
uint8_t value,
int memory_order) {
char volatile *dst = (char volatile *) var;
char src = (char) value;
return (uint8_t) _InterlockedExchangeAdd8(dst, src);
}
uint16_t kit_atomic_fetch_add_explicit_16(uint16_t volatile *var,
uint16_t value,
int memory_order) {
short volatile *dst = (short volatile *) var;
short src = (short) value;
return (uint16_t) _InterlockedExchangeAdd16(dst, src);
}
uint32_t kit_atomic_fetch_add_explicit_32(uint32_t volatile *var,
uint32_t value,
int memory_order) {
int volatile *dst = (int volatile *) var;
int src = (int) value;
return (uint32_t) _InterlockedExchangeAdd(dst, src);
}
uint64_t kit_atomic_fetch_add_explicit_64(uint64_t volatile *var,
uint64_t value,
int memory_order) {
__int64 volatile *dst = (__int64 volatile *) var;
__int64 src = (__int64) value;
# ifdef _WIN64
return (uint64_t) _InterlockedExchangeAdd64(dst, src);
# else
return (uint64_t) _InterlockedExchangeAdd((int volatile *) dst,
(int) src);
# endif
}
#endif
/*********************************************************************
* *
* File: source/kit/mutex.c *
* *
*********************************************************************/
/*********************************************************************
* *
* File: source/kit/condition_variable.c *
* *
*********************************************************************/
/*********************************************************************
* *
* File: source/kit/dynamic_array.c *
* *
*********************************************************************/
#include <assert.h>
#include <string.h>
void kit_da_init(kit_da_void_t *array, ptrdiff_t element_size,
ptrdiff_t size, kit_allocator_t alloc) {
assert(array != NULL);
assert(element_size > 0);
assert(size >= 0);
memset(array, 0, sizeof(kit_da_void_t));
if (size > 0)
array->values = kit_alloc_dispatch(alloc, KIT_ALLOCATE,
element_size * size, 0, NULL);
if (array->values != NULL) {
array->capacity = size;
array->size = size;
}
array->alloc = alloc;
}
static ptrdiff_t eval_capacity(ptrdiff_t current_cap,
ptrdiff_t required_cap) {
if (current_cap == 0)
return required_cap;
ptrdiff_t cap = current_cap;
while (cap < required_cap) cap *= 2;
return cap;
}
void kit_da_resize(kit_da_void_t *array, ptrdiff_t element_size,
ptrdiff_t size) {
assert(array != NULL);
assert(element_size > 0);
assert(size >= 0);
if (size <= array->capacity) {
array->size = size;
} else {
ptrdiff_t capacity = eval_capacity(array->capacity, size);
void *bytes = kit_alloc_dispatch(
array->alloc, KIT_ALLOCATE, element_size * capacity, 0, NULL);
if (bytes != NULL) {
if (array->size > 0)
memcpy(bytes, array->values, element_size * array->size);
if (array->values != NULL)
kit_alloc_dispatch(array->alloc, KIT_DEALLOCATE, 0, 0,
array->values);
array->capacity = capacity;
array->size = size;
array->values = bytes;
}
}
}
/*********************************************************************
* *
* File: source/kit/input_stream.c *
* *
*********************************************************************/
#include <string.h>
enum { KIT_INPUT_STREAM_STR, KIT_INPUT_STREAM_FILE };
typedef struct {
ptrdiff_t type;
kit_allocator_t alloc;
} kit_is_state_basic_t;
typedef struct {
ptrdiff_t type;
kit_allocator_t alloc;
kit_str_t string;
} kit_is_state_str_t;
typedef struct {
ptrdiff_t type;
kit_allocator_t alloc;
FILE *file;
} kit_is_state_file_t;
static int kit_is_check_type_(void *state, ptrdiff_t type) {
kit_is_state_basic_t *basic = (kit_is_state_basic_t *) state;
return basic != NULL && basic->type == type;
}
static ptrdiff_t kit_read_str_(void *state, kit_str_t destination) {
if (!kit_is_check_type_(state, KIT_INPUT_STREAM_STR))
return 0;
kit_is_state_str_t *str = (kit_is_state_str_t *) state;
ptrdiff_t size = destination.size < str->string.size
? destination.size
: str->string.size;
memcpy(destination.values, str->string.values, size);
str->string.values += size;
str->string.size -= size;
return size;
}
static ptrdiff_t kit_read_file_(void *state, kit_str_t destination) {
if (!kit_is_check_type_(state, KIT_INPUT_STREAM_FILE))
return 0;
kit_is_state_file_t *f = (kit_is_state_file_t *) state;
if (f->file == NULL || feof(f->file))
return 0;
ptrdiff_t size = (ptrdiff_t) fread(destination.values, 1,
destination.size, f->file);
if (size <= 0)
return 0;
return size;
}
kit_is_handle_t kit_is_wrap_string(kit_str_t string,
kit_allocator_t alloc) {
kit_is_handle_t in;
memset(&in, 0, sizeof in);
kit_is_state_str_t *state = (kit_is_state_str_t *)
kit_alloc_dispatch(alloc, KIT_ALLOCATE,
sizeof(kit_is_state_str_t), 0, NULL);
if (state != NULL) {
memset(state, 0, sizeof *state);
state->type = KIT_INPUT_STREAM_STR;
state->string = string;
state->alloc = alloc;
in.state = state;
in.read = kit_read_str_;
}
return in;
}
kit_is_handle_t kit_is_wrap_file(FILE *f, kit_allocator_t alloc) {
kit_is_handle_t in;
memset(&in, 0, sizeof in);
kit_is_state_file_t *state = (kit_is_state_file_t *)
kit_alloc_dispatch(alloc, KIT_ALLOCATE,
sizeof(kit_is_state_file_t), 0, NULL);
if (state != NULL) {
memset(state, 0, sizeof *state);
state->type = KIT_INPUT_STREAM_FILE;
state->file = f;
state->alloc = alloc;
in.state = state;
in.read = kit_read_file_;
}
return in;
}
void kit_is_destroy(kit_is_handle_t in) {
kit_is_state_basic_t *basic = (kit_is_state_basic_t *) in.state;
if (basic != NULL)
kit_alloc_dispatch(basic->alloc, KIT_DEALLOCATE, 0, 0, in.state);
}
/*********************************************************************
* *
* File: source/kit/input_buffer.c *
* *
*********************************************************************/
#include <assert.h>
#include <string.h>
typedef struct {
ptrdiff_t ref_count;
kit_is_handle_t upstream;
kit_allocator_t alloc;
kit_string_t data;
} internal_buffer_t;
static internal_buffer_t *buf_init(kit_is_handle_t upstream,
kit_allocator_t alloc) {
assert(alloc.allocate != NULL);
internal_buffer_t *buf = kit_alloc_dispatch(alloc, KIT_ALLOCATE,
sizeof *buf, 0, NULL);
if (buf != NULL) {
memset(buf, 0, sizeof *buf);
buf->ref_count = 1;
buf->upstream = upstream;
buf->alloc = alloc;
DA_INIT(buf->data, 0, alloc);
}
return buf;
}
static kit_allocator_t buf_alloc(void *p) {
assert(p != NULL);
return ((internal_buffer_t *) p)->alloc;
}
static void buf_acquire(void *p) {
assert(p != NULL);
((internal_buffer_t *) p)->ref_count++;
}
static void buf_release(void *p) {
assert(p != NULL);
internal_buffer_t *buf = (internal_buffer_t *) p;
if (--buf->ref_count == 0) {
DA_DESTROY(buf->data);
kit_alloc_dispatch(buf->alloc, KIT_DEALLOCATE, 0, 0, buf);
}
}
static void buf_adjust(void *p, ptrdiff_t size) {
assert(p != NULL);
assert(size >= 0);
internal_buffer_t *buf = (internal_buffer_t *) p;
ptrdiff_t offset = buf->data.size;
if (offset < size) {
DA_RESIZE(buf->data, size);
kit_str_t destination = { .size = size - offset,
.values = buf->data.values + offset };
ptrdiff_t n = KIT_IS_READ(buf->upstream, destination);
DA_RESIZE(buf->data, offset + n);
}
}
static ptrdiff_t buf_read(void *p, ptrdiff_t offset,
kit_str_t destination) {
internal_buffer_t *buf = (internal_buffer_t *) p;
ptrdiff_t n = destination.size < buf->data.size - offset
? destination.size
: buf->data.size - offset;
memcpy(destination.values, buf->data.values + offset, n);
return n;
}
kit_ib_handle_t kit_ib_wrap(kit_is_handle_t upstream,
kit_allocator_t alloc) {
kit_ib_handle_t buf;
memset(&buf, 0, sizeof buf);
buf.status = KIT_OK;
DA_INIT(buf.data, 0, alloc);
buf.internal = buf_init(upstream, alloc);
if (buf.internal == NULL)
buf.status = KIT_ERROR_BAD_ALLOC;
return buf;
}
kit_ib_handle_t kit_ib_read(kit_ib_handle_t buf, ptrdiff_t size) {
kit_ib_handle_t next;
memset(&next, 0, sizeof next);
if (buf.status != KIT_OK) {
next.status = buf.status;
return next;
}
buf_acquire(buf.internal);
buf_adjust(buf.internal, buf.offset + size);
DA_INIT(next.data, size, buf_alloc(buf.internal));
if (next.data.size != size)
next.status = KIT_ERROR_BAD_ALLOC;
kit_str_t destination = { .size = next.data.size,
.values = next.data.values };
ptrdiff_t n = buf_read(buf.internal, buf.offset, destination);
next.offset = buf.offset + n;
next.internal = buf.internal;
DA_RESIZE(next.data, n);
if (next.data.size != n)
next.status = KIT_ERROR_BAD_ALLOC;
return next;
}
kit_ib_handle_t kit_ib_read_while(
kit_ib_handle_t buf, kit_ib_read_condition_fn condition) {
kit_ib_handle_t next;
memset(&next, 0, sizeof next);
if (buf.status != KIT_OK) {
next.status = buf.status;
return next;
}
buf_acquire(buf.internal);
DA_INIT(next.data, 0, buf_alloc(buf.internal));
ptrdiff_t size = 0;
for (;; ++size) {
buf_adjust(buf.internal, buf.offset + size + 1);
DA_RESIZE(next.data, size + 1);
if (next.data.size != size + 1)
next.status = KIT_ERROR_BAD_ALLOC;
kit_str_t destination = { .size = 1,
.values = next.data.values + size };
ptrdiff_t n = buf_read(buf.internal, buf.offset + size,
destination);
kit_str_t data = { .size = size + 1, .values = next.data.values };
if (n != 1 || condition == NULL || condition(data) == 0)
break;
}
next.offset = buf.offset + size;
next.internal = buf.internal;
DA_RESIZE(next.data, size);
if (next.data.size != size)
next.status = KIT_ERROR_BAD_ALLOC;
return next;
}
void kit_ib_destroy(kit_ib_handle_t buf) {
buf_release(buf.internal);
DA_DESTROY(buf.data);
}
/*********************************************************************
* *
* File: source/kit/file.c *
* *
*********************************************************************/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
enum { PATH_BUF_SIZE = 4096 };
#if defined(_WIN32) && !defined(__CYGWIN__)
# include <stdint.h>
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
# endif
# include <Windows.h>
# include <Shlwapi.h>
#else
# include <dirent.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
#ifdef __APPLE__
# define st_mtim st_mtimespec
#endif
static int is_delim(char c) {
return c == '/' || c == '\\';
}
static kit_string_t kit_get_env_(char *name, kit_allocator_t alloc) {
char *val = getenv(name);
ptrdiff_t size = val != NULL ? (ptrdiff_t) strlen(val) : 0;
string_t result;
DA_INIT(result, size, alloc);
assert(result.size == size);
if (result.size == size && size > 0)
memcpy(result.values, val, result.size);
else
DA_RESIZE(result, 0);
return result;
}
kit_string_t kit_path_norm(kit_str_t path, kit_allocator_t alloc) {
str_t parent = SZ("..");
ptrdiff_t i, i1, j;
string_t norm;
DA_INIT(norm, path.size, alloc);
assert(norm.size == path.size);
if (norm.size != path.size)
return norm;
memcpy(norm.values, path.values, path.size);
for (i1 = 0, i = 0; i < path.size; i++) {
if (!is_delim(path.values[i]))
continue;
str_t s = { .size = i - i1 - 1, .values = path.values + i1 + 1 };
if (AR_EQUAL(s, parent)) {
int have_parent = 0;
ptrdiff_t i0 = 0;
for (j = 0; j < i1; j++) {
if (norm.values[j] != '\0')
have_parent = 1;
if (is_delim(norm.values[j]))
i0 = j;
}
if (have_parent) {
memset(norm.values + i0, '\0', i - i0);
if (!is_delim(path.values[i0]))
norm.values[i] = '\0';
}
}
i1 = i;
}
ptrdiff_t size = 0;
for (i = 0; i < norm.size; i++) {
if (norm.values[i] != '\0') {
if (is_delim(norm.values[i]))
norm.values[size] = KIT_PATH_DELIM_C;
else
norm.values[size] = norm.values[i];
size++;
}
}
norm.size = size;
return norm;
}
kit_string_t kit_path_join(kit_str_t left, kit_str_t right,
kit_allocator_t alloc) {
ptrdiff_t left_size = left.size;
ptrdiff_t right_size = right.size;
char *right_values = right.values;
if (left_size > 0 && is_delim(left.values[left_size - 1]))
left_size--;
if (right_size > 0 && is_delim(right.values[0])) {
right_size--;
right_values++;
}
kit_string_t joined;
DA_INIT(joined, left_size + right_size + 1, alloc);
assert(joined.size == left_size + right_size + 1);
if (joined.size != left_size + right_size + 1)
return joined;
memcpy(joined.values, left.values, left_size);
joined.values[left_size] = KIT_PATH_DELIM_C;
memcpy(joined.values + left_size + 1, right_values, right_size);
return joined;
}
kit_string_t kit_path_user(kit_allocator_t alloc) {
kit_string_t user = kit_get_env_(KIT_ENV_HOME, alloc);
if (user.size == 0) {
DA_RESIZE(user, 1);
if (user.size == 1)
user.values[0] = '.';
}
return user;
}
kit_string_t kit_path_cache(kit_allocator_t alloc) {
kit_string_t cache, user;
#if defined(_WIN32) && !defined(__CYGWIN__)
cache = kit_get_env_("LOCALAPPDATA", alloc);
if (cache.size != 0)
return cache;
DA_DESTROY(cache);
#endif
cache = kit_get_env_("XDG_CACHE_HOME", alloc);
if (cache.size != 0)
return cache;
DA_DESTROY(cache);
user = kit_path_user(alloc);
cache =
#ifdef __APPLE__
kit_path_join(WRAP_STR(user), SZ("Library" PATH_DELIM "Caches"),
alloc);
#else
kit_path_join(WRAP_STR(user), SZ(".cache"), alloc);
#endif
DA_DESTROY(user);
return cache;
}
kit_str_t kit_path_index(kit_str_t path, ptrdiff_t index) {
str_t s = { .size = 0, .values = NULL };
ptrdiff_t i0 = 0;
ptrdiff_t i = 0;
ptrdiff_t n = 0;
for (; i < path.size; i++) {
if (!is_delim(path.values[i]))
continue;
if (i0 < i) {
if (n++ == index) {
s.values = path.values + i0;
s.size = i - i0;
return s;
}
}
i0 = i + 1;
}
if (n == index) {
s.values = path.values + i0;
s.size = i - i0;
}
return s;
}
kit_str_t kit_path_take(kit_str_t path, ptrdiff_t count) {
str_t s = { .size = 0, .values = path.values };
ptrdiff_t i0 = 0;
ptrdiff_t i = 0;
ptrdiff_t n = 0;
for (; i < path.size; i++) {
if (!is_delim(path.values[i]))
continue;
if (i0 < i) {
if (n++ == count) {
s.size = i;
return s;
}
}
i0 = i + 1;
}
if (n == count)
s.size = i;
return s;
}
#if defined(_WIN32) && !defined(__CYGWIN__)
static void win32_prepare_path_(WCHAR *buf, kit_str_t path) {
assert(path.size == 0 || path.values != NULL);
assert(path.size + 5 < PATH_BUF_SIZE);
memset(buf, 0, PATH_BUF_SIZE);
buf[0] = L'\\';
buf[1] = L'\\';
buf[2] = L'?';
buf[3] = L'\\';
if (path.size > 0 && path.size + 5 < PATH_BUF_SIZE)
for (ptrdiff_t i = 0; i < path.size; i++) {
if (path.values[i] == '/')
buf[4 + i] = L'\\';
else
buf[4 + i] = path.values[i];
}
}
# define PREPARE_PATH_BUF_ \
WCHAR buf[PATH_BUF_SIZE]; \
win32_prepare_path_(buf, path)
#else
static void unix_prepare_path_(char *buf, kit_str_t path) {
assert(path.size == 0 || path.values != NULL);
assert(path.size + 1 < PATH_BUF_SIZE);
memset(buf, 0, PATH_BUF_SIZE);
if (path.size > 0 && path.size + 1 < PATH_BUF_SIZE)
memcpy(buf, path.values, path.size);
}
# define PREPARE_PATH_BUF_ \
char buf[PATH_BUF_SIZE]; \
unix_prepare_path_(buf, path)
#endif
kit_status_t kit_file_create_folder(kit_str_t path) {
PREPARE_PATH_BUF_;
#if defined(_WIN32) && !defined(__CYGWIN__)
return CreateDirectoryW(buf, NULL) ? KIT_OK
: KIT_ERROR_MKDIR_FAILED;
#else
return mkdir(buf, 0755) == 0 ? KIT_OK : KIT_ERROR_MKDIR_FAILED;
#endif
}
kit_status_t kit_file_create_folder_recursive(kit_str_t path) {
ptrdiff_t i;
for (i = 0;; i++) {
str_t part = kit_path_take(path, i);
int type = kit_path_type(part);
if (type == KIT_PATH_FILE)
return KIT_ERROR_FILE_ALREADY_EXISTS;
if (type == KIT_PATH_NONE) {
kit_status_t s = kit_file_create_folder(part);
if (s != KIT_OK)
return s;
}
if (part.size == path.size)
break;
}
return KIT_OK;
}
kit_status_t kit_file_remove(kit_str_t path) {
PREPARE_PATH_BUF_;
#if defined(_WIN32) && !defined(__CYGWIN__)
return DeleteFileW(buf) ? KIT_OK : KIT_ERROR_UNLINK_FAILED;
#else
return unlink(buf) == 0 ? KIT_OK : KIT_ERROR_UNLINK_FAILED;
#endif
}
kit_status_t kit_file_remove_folder(kit_str_t path) {
PREPARE_PATH_BUF_;
#if defined(_WIN32) && !defined(__CYGWIN__)
return RemoveDirectoryW(buf) ? KIT_OK : KIT_ERROR_RMDIR_FAILED;
#else
return rmdir(buf) == 0 ? KIT_OK : KIT_ERROR_RMDIR_FAILED;
#endif
}
kit_status_t kit_file_remove_recursive(kit_str_t path,
kit_allocator_t alloc) {
int type = kit_path_type(path);
ptrdiff_t i;
switch (type) {
case KIT_PATH_FILE: return kit_file_remove(path);
case KIT_PATH_FOLDER: {
kit_path_list_t list = kit_file_enum_folder(path, alloc);
if (list.status != KIT_OK) {
kit_path_list_destroy(list);
return list.status;
}
for (i = 0; i < list.files.size; i++) {
str_t s = { .size = list.files.values[i].size,
.values = list.files.values[i].values };
kit_file_remove_recursive(s, alloc);
}
kit_path_list_destroy(list);
return kit_file_remove_folder(path);
}
default:;
}
return KIT_ERROR_FILE_DO_NOT_EXIST;
}
kit_path_type_t kit_path_type(kit_str_t path) {
PREPARE_PATH_BUF_;
#if defined(_WIN32) && !defined(__CYGWIN__)
if (PathFileExistsW(buf)) {
if ((GetFileAttributesW(buf) & FILE_ATTRIBUTE_DIRECTORY) != 0)
return KIT_PATH_FOLDER;
else
return KIT_PATH_FILE;
}
#else
struct stat info;
if (stat(buf, &info) == 0) {
if (S_ISREG(info.st_mode))
return KIT_PATH_FILE;
if (S_ISDIR(info.st_mode))
return KIT_PATH_FOLDER;
}
#endif
return KIT_PATH_NONE;
}
kit_file_info_t kit_file_info(kit_str_t path) {
kit_file_info_t result;
memset(&result, 0, sizeof result);
PREPARE_PATH_BUF_;
#if defined(_WIN32) && !defined(__CYGWIN__)
HANDLE f = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (f != INVALID_HANDLE_VALUE) {
FILETIME ft;
if (GetFileTime(f, NULL, NULL, &ft) != 0) {
uint64_t nsec100 = (((uint64_t) ft.dwHighDateTime) << 32) |
(uint64_t) ft.dwLowDateTime;
result.time_modified_sec = (int64_t) (nsec100 / 10000000);
result.time_modified_nsec = (int32_t) (100 *
(nsec100 % 10000000));
} else {
assert(0);
}
DWORD high;
DWORD low = GetFileSize(f, &high);
result.size = (int64_t) ((((uint64_t) high) << 32) |
(uint64_t) low);
result.status = KIT_OK;
CloseHandle(f);
return result;
}
#else
struct stat info;
if (stat(buf, &info) == 0 && S_ISREG(info.st_mode)) {
result.size = (int64_t) info.st_size;
# ifndef st_mtime
/* No support for nanosecond timestamps.
*/
result.time_modified_sec = (int64_t) info.st_mtime;
# else
result.time_modified_sec = (int64_t) info.st_mtim.tv_sec;
result.time_modified_nsec = (int32_t) info.st_mtim.tv_nsec;
# endif
result.status = KIT_OK;
return result;
}
#endif
result.status = KIT_ERROR_FILE_DO_NOT_EXIST;
return result;
}
kit_path_list_t kit_file_enum_folder(kit_str_t path,
kit_allocator_t alloc) {
PREPARE_PATH_BUF_;
kit_path_list_t result = { .status = KIT_OK };
DA_INIT(result.files, 0, alloc);
#if defined(_WIN32) && !defined(__CYGWIN__)
if (path.size + 7 >= PATH_BUF_SIZE) {
result.status = KIT_ERROR_PATH_TOO_LONG;
return result;
}
buf[path.size + 4] = '\\';
buf[path.size + 5] = '*';
WIN32_FIND_DATAW data;
HANDLE find = FindFirstFileW(buf, &data);
if (find == INVALID_HANDLE_VALUE)
return result;
do {
ptrdiff_t n = result.files.size;
DA_RESIZE(result.files, n + 1);
if (result.files.size != n + 1) {
result.status = KIT_ERROR_BAD_ALLOC;
break;
}
ptrdiff_t size = 0;
while (size < MAX_PATH && data.cFileName[size] != L'\0') size++;
DA_INIT(result.files.values[n], size, alloc);
if (result.files.values[n].size != size) {
DA_RESIZE(result.files, n);
result.status = KIT_ERROR_BAD_ALLOC;
break;
}
for (ptrdiff_t i = 0; i < size; i++)
result.files.values[n].values[i] = data.cFileName[i];
} while (FindNextFileW(find, &data) != 0);
FindClose(find);
#else
DIR *directory = opendir(buf);
if (directory == NULL)
return result;
for (;;) {
struct dirent *entry = readdir(directory);
if (entry == NULL)
break;
if (entry->d_name[0] == '.')
continue;
ptrdiff_t n = result.files.size;
DA_RESIZE(result.files, n + 1);
if (result.files.size != n + 1) {
result.status = KIT_ERROR_BAD_ALLOC;
break;
}
ptrdiff_t size = (ptrdiff_t) strlen(entry->d_name);
DA_INIT(result.files.values[n], size, alloc);
if (result.files.values[n].size != size) {
DA_RESIZE(result.files, n);
result.status = KIT_ERROR_BAD_ALLOC;
break;
}
if (size > 0)
memcpy(result.files.values[n].values, entry->d_name, size);
}
closedir(directory);
#endif
return result;
}
void kit_path_list_destroy(kit_path_list_t list) {
ptrdiff_t i;
for (i = 0; i < list.files.size; i++)
DA_DESTROY(list.files.values[i]);
DA_DESTROY(list.files);
}
/*********************************************************************
* *
* File: source/kit/mersenne_twister_64.c *
* *
*********************************************************************/
#define MM 156
#define MATRIX_A 0xb5026f5aa96619e9ull
#define UM 0xffffffff80000000ull
#define LM 0x7fffffffull
void kit_mt64_init_array(kit_mt64_state_t *state, ptrdiff_t size,
uint64_t *seed) {
ptrdiff_t i;
for (i = 0; i < size && i < KIT_MT64_N; i++) state->mt[i] = seed[i];
for (state->index = size; state->index < KIT_MT64_N; state->index++)
state->mt[state->index] = (6364136223846793005ull *
(state->mt[state->index - 1] ^
(state->mt[state->index - 1] >>
62u)) +
state->index);
}
void kit_mt64_init(kit_mt64_state_t *state, uint64_t seed) {
kit_mt64_init_array(state, 1, &seed);
}
void kit_mt64_rotate(kit_mt64_state_t *state) {
static uint64_t mag01[2] = { 0ull, MATRIX_A };
uint64_t x;
int i;
for (i = 0; i < KIT_MT64_N - MM; i++) {
x = (state->mt[i] & UM) | (state->mt[i + 1] & LM);
state->mt[i] = state->mt[i + MM] ^ (x >> 1u) ^
mag01[(int) (x & 1ull)];
}
for (; i < KIT_MT64_N - 1; i++) {
x = (state->mt[i] & UM) | (state->mt[i + 1] & LM);
state->mt[i] = state->mt[i + (MM - KIT_MT64_N)] ^ (x >> 1u) ^
mag01[(int) (x & 1ull)];
}
x = (state->mt[KIT_MT64_N - 1] & UM) | (state->mt[0] & LM);
state->mt[KIT_MT64_N - 1] = state->mt[MM - 1] ^ (x >> 1u) ^
mag01[(int) (x & 1ull)];
state->index = 0;
}
uint64_t kit_mt64_generate(kit_mt64_state_t *state) {
if (state->index >= KIT_MT64_N)
kit_mt64_rotate(state);
uint64_t x = state->mt[state->index++];
x ^= (x >> 29u) & 0x5555555555555555ull;
x ^= (x << 17u) & 0x71d67fffeda60000ull;
x ^= (x << 37u) & 0xfff7eee000000000ull;
x ^= (x >> 43u);
return x;
}
/*********************************************************************
* *
* File: source/kit/secure_random.c *
* *
*********************************************************************/
#include <assert.h>
#include <stdio.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
# endif
# include <Windows.h>
#else
# include <unistd.h>
#endif
static uint64_t get_available_memory(void) {
#if defined(_WIN32) && !defined(__CYGWIN__)
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return (uint64_t) status.ullTotalPhys;
#else
uint64_t pages = (uint64_t) sysconf(_SC_PHYS_PAGES);
uint64_t page_size = (uint64_t) sysconf(_SC_PAGE_SIZE);
return pages * page_size;
#endif
}
#ifndef KIT_DISABLE_SYSTEM_THREADS
static once_flag kit_secure_random_fallback_flag;
static mtx_t kit_secure_random_fallback_mutex;
static void secure_random_fallback_init(void) {
mtx_init(&kit_secure_random_fallback_mutex, mtx_plain);
}
#endif
static void secure_random_fallback(ptrdiff_t size, void *data) {
#ifndef KIT_DISABLE_SYSTEM_THREADS
call_once(&kit_secure_random_fallback_flag,
secure_random_fallback_init);
mtx_lock(&kit_secure_random_fallback_mutex);
#endif
/* Try to get some unpredictable system properties and use them to
* seed the pseudo random number generator.
*/
static int8_t first_run = 1;
static uint64_t n = 0;
static uint64_t time_sec = 0;
static uint64_t time_nsec = 0;
struct timespec t;
timespec_get(&t, TIME_UTC);
kit_mt64_state_t state;
if (first_run) {
first_run = 0;
uint64_t seed[] = { n, get_available_memory(),
(uint64_t) t.tv_sec, (uint64_t) t.tv_nsec };
kit_mt64_init_array(&state, sizeof seed / sizeof *seed, seed);
} else {
uint64_t seed[] = { n,
get_available_memory(),
(uint64_t) t.tv_sec,
(uint64_t) t.tv_nsec,
(uint64_t) t.tv_sec - time_sec,
(uint64_t) t.tv_nsec - time_nsec };
kit_mt64_init_array(&state, sizeof seed / sizeof *seed, seed);
}
kit_mt64_rotate(&state);
n = kit_mt64_generate(&state);
time_sec = (uint64_t) t.tv_sec;
time_nsec = (uint64_t) t.tv_nsec;
for (ptrdiff_t i = 0; i < size; i++)
((uint8_t *) data)[i] = (uint8_t) (kit_mt64_generate(&state) >>
56);
#ifndef KIT_DISABLE_SYSTEM_THREADS
mtx_unlock(&kit_secure_random_fallback_mutex);
#endif
}
void kit_secure_random(ptrdiff_t size, void *data) {
assert(size > 0);
assert(data != NULL);
if (size <= 0 || data == NULL)
return;
#if defined(_WIN32) && !defined(__CYGWIN__)
secure_random_fallback(size, data);
#else
FILE *f = fopen("/dev/urandom", "rb");
assert(f != NULL);
if (f == NULL) {
secure_random_fallback(size, data);
return;
}
size_t n = fread(data, 1, size, f);
fclose(f);
assert(n == size);
if (n != size)
secure_random_fallback(size, data);
#endif
}
/*********************************************************************
* *
* File: source/kit/sha256.c *
* *
*********************************************************************/
#include <assert.h>
#include <string.h>
#define ROTLEFT(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
#define ROTRIGHT(a, b) (((a) >> (b)) | ((a) << (32 - (b))))
#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTRIGHT(x, 2) ^ ROTRIGHT(x, 13) ^ ROTRIGHT(x, 22))
#define EP1(x) (ROTRIGHT(x, 6) ^ ROTRIGHT(x, 11) ^ ROTRIGHT(x, 25))
#define SIG0(x) (ROTRIGHT(x, 7) ^ ROTRIGHT(x, 18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x, 17) ^ ROTRIGHT(x, 19) ^ ((x) >> 10))
static uint32_t kit_sha256_k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
static void kit_sha256_transform(uint32_t *state, uint8_t *data) {
assert(state != NULL);
assert(data != NULL);
uint32_t a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
for (i = 0, j = 0; i < 16; ++i, j += 4)
m[i] = ((uint32_t) data[j] << 24) |
((uint32_t) data[j + 1] << 16) |
((uint32_t) data[j + 2] << 8) | ((uint32_t) data[j + 3]);
for (; i < 64; ++i)
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
for (i = 0; i < 64; ++i) {
t1 = h + EP1(e) + CH(e, f, g) + kit_sha256_k[i] + m[i];
t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
kit_sha256_hash_t kit_sha256(ptrdiff_t in_size, uint8_t *in_data) {
assert(in_size >= 0);
assert(in_data != NULL);
uint32_t state[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372,
0xa54ff53a, 0x510e527f, 0x9b05688c,
0x1f83d9ab, 0x5be0cd19 };
uint8_t data[64];
ptrdiff_t i;
ptrdiff_t datalen = 0;
uint64_t bitlen = 0;
if (in_data != NULL)
for (i = 0; i < in_size; ++i) {
data[datalen] = in_data[i];
datalen++;
if (datalen != 64)
continue;
kit_sha256_transform(state, data);
bitlen += 512;
datalen = 0;
}
i = datalen;
if (datalen < 56) {
data[i++] = 0x80;
while (i < 56) data[i++] = 0x00;
} else {
data[i++] = 0x80;
while (i < 64) data[i++] = 0x00;
kit_sha256_transform(state, data);
memset(data, 0, 56);
}
bitlen += datalen * 8;
data[63] = bitlen;
data[62] = bitlen >> 8;
data[61] = bitlen >> 16;
data[60] = bitlen >> 24;
data[59] = bitlen >> 32;
data[58] = bitlen >> 40;
data[57] = bitlen >> 48;
data[56] = bitlen >> 56;
kit_sha256_transform(state, data);
kit_sha256_hash_t hash;
memset(&hash, 0, sizeof hash);
for (i = 0; i < 4; ++i) {
hash.v[i] = (state[0] >> (24 - i * 8)) & 0xff;
hash.v[i + 4] = (state[1] >> (24 - i * 8)) & 0xff;
hash.v[i + 8] = (state[2] >> (24 - i * 8)) & 0xff;
hash.v[i + 12] = (state[3] >> (24 - i * 8)) & 0xff;
hash.v[i + 16] = (state[4] >> (24 - i * 8)) & 0xff;
hash.v[i + 20] = (state[5] >> (24 - i * 8)) & 0xff;
hash.v[i + 24] = (state[6] >> (24 - i * 8)) & 0xff;
hash.v[i + 28] = (state[7] >> (24 - i * 8)) & 0xff;
}
return hash;
}
#endif
#endif
|