-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathth.c
More file actions
11981 lines (10518 loc) · 402 KB
/
th.c
File metadata and controls
11981 lines (10518 loc) · 402 KB
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
#define TH_WITH_AMALGAMATION 1
#include "th.h"
/* Start of th_config.h */
#if defined(__GNUC__)
// Buggy warning in GCC
// TODO: Check the exact versions where these warnings are fixed
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#pragma GCC diagnostic ignored "-Wmissing-braces"
#endif
/* feature configuration begin */
#ifndef TH_WITH_SSL
#define TH_WITH_SSL 0
#endif
#ifndef TH_WITH_SENDFILE
#define TH_WITH_SENDFILE 1
#endif
#ifndef TH_WITH_MMAP
#define TH_WITH_MMAP 1
#endif
#ifndef TH_LOG_LEVEL
#define TH_LOG_LEVEL TH_LOG_LEVEL_INFO
#endif
#ifndef TH_MAX_BODY_LEN
#define TH_MAX_BODY_LEN (4 * 1024 * 1024)
#endif
/* feature configuration end */
#ifndef TH_CONFIG_OS_MOCK
#if defined(__APPLE__)
#define TH_CONFIG_OS_OSX 1
#define TH_CONFIG_OS_POSIX 1
#define TH_CONFIG_OS_BSD 1
#endif
#if defined(__FreeBSD__)
#define TH_CONFIG_OS_FreeBSD 1
#define TH_CONFIG_OS_POSIX 1
#define TH_CONFIG_OS_BSD 1
#endif
#if defined(__NetBSD__)
#define TH_CONFIG_OS_NetBSD 1
#define TH_CONFIG_OS_POSIX 1
#define TH_CONFIG_OS_BSD 1
#endif
#if defined(__OpenBSD__)
#define TH_CONFIG_OS_OpenBSD 1
#define TH_CONFIG_OS_POSIX 1
#define TH_CONFIG_OS_BSD 1
#endif
#if defined(__linux__)
#define TH_CONFIG_OS_LINUX 1
#define TH_CONFIG_OS_POSIX 1
#endif
#if defined(_WIN32)
#define TH_CONFIG_OS_WIN 1
#endif
#endif
/* IO service config begin */
#if defined(TH_CONFIG_OS_POSIX)
#define TH_CONFIG_WITH_POLL 1
#endif
#if defined(TH_CONFIG_OS_OSX)
#define TH_CONFIG_WITH_KQUEUE 1
#endif
#if defined(TH_CONFIG_OS_FreeBSD)
#define TH_CONFIG_WITH_KQUEUE 1
#endif
/* IO service config end */
/* sendfile config begin */
#if TH_WITH_SENDFILE
#if defined(TH_CONFIG_OS_LINUX)
// #define TH_CONFIG_WITH_LINUX_SENDFILE 1
#elif defined(TH_CONFIG_OS_OSX) || defined(TH_CONFIG_OS_FreeBSD) || defined(TH_CONFIG_OS_NetBSD) || defined(TH_CONFIG_OS_OpenBSD)
#define TH_CONFIG_WITH_BSD_SENDFILE 1
#endif
#endif
/* Unused attribute is platform dependent */
#define TH_MAYBE_UNUSED __attribute__((unused))
/* Helper macros for defining public and private functions */
#define TH_PUBLIC(type) type
#ifdef TH_WITH_AMALGAMATION
#define TH_PRIVATE(type) static type
#else
#define TH_PRIVATE(type) type
#endif
#define TH_LOCAL(type) static type
#define TH_INLINE(type) static inline type
/* Server related config begin */
#ifndef TH_CONFIG_MAX_HANDLES
#define TH_CONFIG_MAX_HANDLES (8 * 1024)
#endif
#ifndef TH_CONFIG_MAX_CONNECTIONS
#define TH_CONFIG_MAX_CONNECTIONS 512
#endif
#ifndef TH_CONFIG_SMALL_HEADER_LEN
#define TH_CONFIG_SMALL_HEADER_LEN 1024
#endif
#ifndef TH_CONFIG_LARGE_HEADER_LEN
#define TH_CONFIG_LARGE_HEADER_LEN (4 * 1024)
#endif
#ifndef TH_CONFIG_MAX_CONTENT_LEN
#define TH_CONFIG_MAX_CONTENT_LEN (1024 * 1024)
#endif
#ifndef TH_CONFIG_MAX_HEADER_NUM
#define TH_CONFIG_MAX_HEADER_NUM 64
#endif
#ifndef TH_CONFIG_MAX_PATH_LEN
#define TH_CONFIG_MAX_PATH_LEN 512
#endif
#ifndef TH_CONFIG_MAX_CACHED_FDS
#define TH_CONFIG_MAX_CACHED_FDS 64
#endif
#ifndef TH_CONFIG_SENDFILE_CHUNK_LEN
#define TH_CONFIG_SENDFILE_CHUNK_LEN (4 * 1024 * 1024)
#endif
#ifndef TH_CONFIG_LARGE_BUF_LEN
#define TH_CONFIG_LARGE_BUF_LEN (4 * 1024)
#endif
#ifndef TH_CONFIG_SMALL_SSL_BUF_LEN
#define TH_CONFIG_SMALL_SSL_BUF_LEN (2 * 1024)
#endif
#ifndef TH_CONFIG_LARGE_SSL_BUF_LEN
#define TH_CONFIG_LARGE_SSL_BUF_LEN (8 * 1024)
#endif
#ifndef TH_CONFIG_MAX_SSL_READ_BUF_LEN
#define TH_CONFIG_MAX_SSL_READ_BUF_LEN (1024 * 1024)
#endif
#ifndef TH_CONFIG_MAX_SSL_WRITE_BUF_LEN
#define TH_CONFIG_MAX_SSL_WRITE_BUF_LEN (4 * 1024 * 1024)
#endif
/* Socket related configuration */
#ifndef TH_CONFIG_REUSE_ADDR
#define TH_CONFIG_REUSE_ADDR 1
#endif
#ifndef TH_CONFIG_REUSE_PORT
#define TH_CONFIG_REUSE_PORT 0
#endif
#ifndef TH_CONFIG_TCP_NODELAY
#define TH_CONFIG_TCP_NODELAY 0
#endif
// Socket timeout in seconds
#ifndef TH_CONFIG_IO_TIMEOUT
#define TH_CONFIG_IO_TIMEOUT 10
#endif
/* Server related config end */
/* End of th_config.h */
/* Start of th_fmt.h */
#include <stddef.h>
#include <stdint.h>
#include <time.h>
TH_PRIVATE(const char*)
th_fmt_uint_to_str(char* buf, size_t len, unsigned int val);
TH_PRIVATE(const char*)
th_fmt_uint_to_str_ex(char* buf, size_t len, unsigned int val, size_t* out_len);
/** th_fmt_str_append
* @brief Append a string to a buffer.
* @param buf The buffer to append to.
* @param pos The current position in the buffer (where to append).
* @param len The length of the buffer.
* @param str The string to append.
* @return The number of characters appended.
*/
TH_PRIVATE(size_t)
th_fmt_str_append(char* buf, size_t pos, size_t len, const char* str);
TH_PRIVATE(size_t)
th_fmt_strn_append(char* buf, size_t pos, size_t len, const char* str, size_t n);
TH_PRIVATE(size_t)
th_fmt_strtime(char* buf, size_t len, th_date date);
/* End of th_fmt.h */
/* Start of th_system_error.h */
#if defined(TH_CONFIG_OS_POSIX)
#include <errno.h>
#include <string.h>
#elif defined(TH_CONFIG_OS_WIN)
#include <windows.h>
#endif
TH_INLINE(const char*)
th_system_strerror(int errc) TH_MAYBE_UNUSED;
TH_INLINE(const char*)
th_system_strerror(int errc)
{
#if defined(TH_CONFIG_OS_POSIX)
return strerror(errc);
#elif defined(TH_CONFIG_OS_WIN)
static char buf[256];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errc, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), NULL);
return buf;
#elif defined(TH_CONFIG_OS_MOCK)
(void)errc;
return "mock error";
#endif
}
/* Define the system error codes that we use */
#if defined(TH_CONFIG_OS_POSIX)
#define TH_ENOENT ENOENT
#define TH_EINTR EINTR
#define TH_EIO EIO
#define TH_EBADF EBADF
#define TH_EBUSY EBUSY
#define TH_EAGAIN EAGAIN
#define TH_EWOULDBLOCK EWOULDBLOCK
#define TH_ENOMEM ENOMEM
#define TH_ENOSYS ENOSYS
#define TH_ETIMEDOUT ETIMEDOUT
#define TH_ECANCELED ECANCELED
#elif defined(TH_CONFIG_OS_WIN)
#define TH_ENOENT ERROR_FILE_NOT_FOUND
#define TH_EINTR ERROR_INTERRUPT
#define TH_EIO ERROR_IO_DEVICE
#define TH_EBADF ERROR_BAD_FORMAT
#define TH_EBUSY ERROR_BUSY
#define TH_EAGAIN ERROR_RETRY
#define TH_EWOULDBLOCK ERROR_RETRY
#define TH_ENOMEM ERROR_OUTOFMEMORY
#define TH_ENOSYS ERROR_NOT_SUPPORTED
#define TH_ETIMEDOUT ERROR_TIMEOUT
#define TH_ECANCELED ERROR_CANCELLED
#elif defined(TH_CONFIG_OS_MOCK)
#define TH_ENOENT 1
#define TH_EINTR 2
#define TH_EIO 3
#define TH_EBUSY 4
#define TH_EAGAIN 5
#define TH_EWOULDBLOCK 6
#define TH_ENOMEM 7
#define TH_ENOSYS 8
#define TH_ETIMEDOUT 9
#define TH_ECANCELED 10
#define TH_EBADF 11
#endif
/* End of th_system_error.h */
/* Start of th_http_error.h */
#include <errno.h>
/** th_http_err
* @brief Converts a error code to a equivalent HTTP error code.
*/
TH_INLINE(th_err)
th_http_error(th_err err)
{
if (err == TH_ERR_OK)
return TH_ERR_HTTP(TH_CODE_OK);
switch (TH_ERR_CATEGORY(err)) {
case TH_ERR_CATEGORY_SYSTEM:
switch (TH_ERR_CODE(err)) {
case TH_ENOENT:
return TH_ERR_HTTP(TH_CODE_NOT_FOUND);
break;
case TH_ETIMEDOUT:
return TH_ERR_HTTP(TH_CODE_REQUEST_TIMEOUT);
break;
default:
return TH_ERR_HTTP(TH_CODE_INTERNAL_SERVER_ERROR);
break;
}
break;
case TH_ERR_CATEGORY_HTTP:
return err;
break;
}
return TH_ERR_HTTP(TH_CODE_INTERNAL_SERVER_ERROR);
}
TH_INLINE(const char*)
th_http_strerror(int code)
{
switch (code) {
case TH_CODE_OK:
return "OK";
break;
case TH_CODE_MOVED_PERMANENTLY:
return "Moved Permanently";
break;
case TH_CODE_BAD_REQUEST:
return "Bad Request";
break;
case TH_CODE_NOT_FOUND:
return "Not Found";
break;
case TH_CODE_METHOD_NOT_ALLOWED:
return "Method Not Allowed";
break;
case TH_CODE_PAYLOAD_TOO_LARGE:
return "Payload Too Large";
break;
case TH_CODE_INTERNAL_SERVER_ERROR:
return "Internal Server Error";
break;
case TH_CODE_SERVICE_UNAVAILABLE:
return "Service Unavailable";
break;
case TH_CODE_NOT_IMPLEMENTED:
return "Method Not Implemented";
break;
case TH_CODE_REQUEST_TIMEOUT:
return "Request Timeout";
break;
case TH_CODE_TOO_MANY_REQUESTS:
return "Too Many Requests";
break;
case TH_CODE_URI_TOO_LONG:
return "URI Too Long";
break;
case TH_CODE_UNSUPPORTED_MEDIA_TYPE:
return "Unsupported Media Type";
break;
case TH_CODE_RANGE_NOT_SATISFIABLE:
return "Range Not Satisfiable";
break;
case TH_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE:
return "Request Header Fields Too Large";
break;
case TH_CODE_UNAUTHORIZED:
return "Unauthorized";
break;
case TH_CODE_FORBIDDEN:
return "Forbidden";
break;
default:
return "Unknown";
break;
}
}
typedef enum th_http_code_type {
TH_HTTP_CODE_TYPE_INFORMATIONAL,
TH_HTTP_CODE_TYPE_SUCCESS,
TH_HTTP_CODE_TYPE_REDIRECT,
TH_HTTP_CODE_TYPE_CLIENT_ERROR,
TH_HTTP_CODE_TYPE_SERVER_ERROR,
} th_http_code_type;
TH_INLINE(th_http_code_type)
th_http_code_get_type(int code)
{
if (code >= 100 && code < 200)
return TH_HTTP_CODE_TYPE_INFORMATIONAL;
if (code >= 200 && code < 300)
return TH_HTTP_CODE_TYPE_SUCCESS;
if (code >= 300 && code < 400)
return TH_HTTP_CODE_TYPE_REDIRECT;
if (code >= 400 && code < 500)
return TH_HTTP_CODE_TYPE_CLIENT_ERROR;
if (code >= 500 && code < 600)
return TH_HTTP_CODE_TYPE_SERVER_ERROR;
return TH_HTTP_CODE_TYPE_SERVER_ERROR;
}
/* End of th_http_error.h */
/* Start of th_io_op.h */
#include <stddef.h>
TH_PRIVATE(th_err)
th_io_op_read(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_readv(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_write(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_writev(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_send(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_sendv(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_accept(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_sendfile(void* self, size_t* result) TH_MAYBE_UNUSED;
/* End of th_io_op.h */
/* Start of th_io_op_bsd.h */
#if defined(TH_CONFIG_WITH_BSD_SENDFILE)
TH_PRIVATE(th_err)
th_io_op_bsd_sendfile(void* self, size_t* result) TH_MAYBE_UNUSED;
#endif
/* End of th_io_op_bsd.h */
/* Start of th_io_op_linux.h */
#if defined(TH_CONFIG_WITH_LINUX_SENDFILE)
TH_PRIVATE(th_err)
th_io_op_linux_sendfile(void* self, size_t* result) TH_MAYBE_UNUSED;
#endif
/* End of th_io_op_linux.h */
/* Start of th_io_op_mock.h */
#if defined(TH_CONFIG_OS_MOCK)
TH_PRIVATE(th_err)
th_io_op_mock_read(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_readv(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_write(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_writev(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_send(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_sendv(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_accept(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_mock_sendfile(void* self, size_t* result);
#endif
/* End of th_io_op_mock.h */
/* Start of th_io_op_posix.h */
#if defined(TH_CONFIG_OS_POSIX)
TH_PRIVATE(th_err)
th_io_op_posix_read(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_readv(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_write(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_writev(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_send(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_sendv(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_accept(void* self, size_t* result);
TH_PRIVATE(th_err)
th_io_op_posix_sendfile_mmap(void* self, size_t* result) TH_MAYBE_UNUSED;
TH_PRIVATE(th_err)
th_io_op_posix_sendfile_buffered(void* self, size_t* result) TH_MAYBE_UNUSED;
#endif
/* End of th_io_op_posix.h */
/* Start of th_log.h */
#include <stdarg.h>
#include <stdio.h>
#ifndef TH_LOG_LEVEL
#define TH_LOG_LEVEL TH_LOG_LEVEL_INFO
#endif
#define TH_LOG_TAG "default"
TH_PRIVATE(th_log*)
th_default_log_get(void);
TH_PRIVATE(void)
th_log_printf(int level, const char* fmt, ...) TH_MAYBE_UNUSED;
#if TH_LOG_LEVEL <= TH_LOG_LEVEL_TRACE
#define TH_LOG_TRACE(...) th_log_printf(TH_LOG_LEVEL_TRACE, "TRACE: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_TRACE(...) ((void)0)
#endif
#if TH_LOG_LEVEL <= TH_LOG_LEVEL_DEBUG
#define TH_LOG_DEBUG(...) th_log_printf(TH_LOG_LEVEL_DEBUG, "DEBUG: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_DEBUG(...) ((void)0)
#endif
#if (TH_LOG_LEVEL <= TH_LOG_LEVEL_INFO)
#define TH_LOG_INFO(...) th_log_printf(TH_LOG_LEVEL_INFO, "INFO: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_INFO(...) ((void)0)
#endif
#if TH_LOG_LEVEL <= TH_LOG_LEVEL_WARN
#define TH_LOG_WARN(...) th_log_printf(TH_LOG_LEVEL_WARN, "WARN: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_WARN(...) ((void)0)
#endif
#if TH_LOG_LEVEL <= TH_LOG_LEVEL_ERROR
#define TH_LOG_ERROR(...) th_log_printf(TH_LOG_LEVEL_ERROR, "ERROR: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_ERROR(...) ((void)0)
#endif
#if TH_LOG_LEVEL <= TH_LOG_LEVEL_FATAL
#define TH_LOG_FATAL(...) th_log_printf(TH_LOG_LEVEL_FATAL, "FATAL: [" TH_LOG_TAG "] " __VA_ARGS__)
#else
#define TH_LOG_FATAL(...) ((void)0)
#endif
/* End of th_log.h */
/* Start of th_utility.h */
#include <stdlib.h>
#define TH_MIN(a, b) ((a) < (b) ? (a) : (b))
#define TH_MAX(a, b) ((a) > (b) ? (a) : (b))
#define TH_ABS(a) ((a) < 0 ? -(a) : (a))
#define TH_ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
// Move a pointer from src to dst and set src to NULL
TH_INLINE(void*)
th_move_ptr(void** src)
{
void* dst = *src;
*src = NULL;
return dst;
}
#define TH_MOVE_PTR(ptr) th_move_ptr((void**)&(ptr))
// Custom assert macros
#ifndef NDEBUG
#define TH_ASSERT(cond) \
do { \
if (!(cond)) { \
TH_LOG_FATAL("Assertion failed: %s at %s:%d", #cond, __FILE__, __LINE__); \
abort(); \
} \
} while (0)
#else
#define TH_ASSERT(cond) ((void)0)
#endif
// Mathematical utility functions
TH_INLINE(size_t)
th_next_pow2(size_t n)
{
TH_ASSERT(n > 0);
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
/* End of th_utility.h */
/* Start of th_list.h */
/** Generic doubly linked list implementation.
* that works with any struct that has a next and prev pointer.
*/
#define TH_DEFINE_LIST(NAME, T, PREV, NEXT) \
typedef struct NAME { \
T* head; \
T* tail; \
} NAME; \
\
TH_INLINE(void) \
NAME##_push_back(NAME* list, T* item) TH_MAYBE_UNUSED; \
\
TH_INLINE(T*) \
NAME##_pop_front(NAME* list) TH_MAYBE_UNUSED; \
\
TH_INLINE(T*) \
NAME##_front(NAME* list) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_erase(NAME* list, T* item) TH_MAYBE_UNUSED; \
\
TH_INLINE(T*) \
NAME##_next(T* item) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_push_back(NAME* list, T* item) \
{ \
TH_ASSERT(item != NULL); \
if (list->head == NULL) { \
list->head = item; \
item->PREV = NULL; \
} else { \
list->tail->NEXT = item; \
item->PREV = list->tail; \
} \
list->tail = item; \
item->NEXT = NULL; \
} \
\
TH_INLINE(T*) \
NAME##_pop_front(NAME* list) \
{ \
T* item = list->head; \
if (item) { \
list->head = item->NEXT; \
if (list->head) { \
list->head->PREV = NULL; \
} else { \
list->tail = NULL; \
} \
item->NEXT = NULL; \
} \
return item; \
} \
\
TH_INLINE(T*) \
NAME##_front(NAME* list) \
{ \
return list->head; \
} \
\
TH_INLINE(void) \
NAME##_erase(NAME* list, T* item) \
{ \
TH_ASSERT(item != NULL); \
TH_ASSERT((item->NEXT || item == list->tail) && "Item is not in the list"); \
TH_ASSERT((item->PREV || item == list->head) && "Item is not in the list"); \
T* next = item->NEXT; \
T* prev = item->PREV; \
if (prev) { \
prev->NEXT = next; \
item->PREV = NULL; \
} else { \
list->head = next; \
} \
if (next) { \
next->PREV = prev; \
item->NEXT = NULL; \
} else { \
list->tail = prev; \
} \
} \
\
TH_INLINE(T*) \
NAME##_next(T* item) \
{ \
return item->NEXT; \
}
/* End of th_list.h */
/* Start of th_allocator.h */
#include <stddef.h>
#include <stdint.h>
TH_INLINE(void*)
th_allocator_alloc(th_allocator* allocator, size_t size)
{
return allocator->alloc(allocator, size);
}
TH_INLINE(void*)
th_allocator_realloc(th_allocator* allocator, void* ptr, size_t size)
{
return allocator->realloc(allocator, ptr, size);
}
TH_INLINE(void)
th_allocator_free(th_allocator* allocator, void* ptr)
{
allocator->free(allocator, ptr);
}
TH_PRIVATE(th_allocator*)
th_default_allocator_get(void);
/* th_arena_allocator begin */
typedef struct th_arena_allocator {
th_allocator base;
th_allocator* allocator;
void* buf;
size_t size;
size_t pos;
size_t prev_pos;
uint16_t alignment;
} th_arena_allocator;
/** th_arena_allocator_init
* @brief The arena allocator is a simple allocator that allocates memory from a fixed-size buffer.
* It only frees memory when the free operation is called on the previously allocated memory.
* If no memory is available in the buffer, it will fall back to the default allocator.
* @param allocator The arena allocator to initialize.
* @param buf The buffer to use for allocations.
* @param size The size of the buffer.
*/
TH_PRIVATE(void)
th_arena_allocator_init(th_arena_allocator* allocator, void* buf, size_t size, th_allocator* fallback);
/** th_arena_allocator_init_with_alignment
* @brief Just like th_arena_allocator_init, but allows specifying the alignment of the allocations.
*/
TH_PRIVATE(void)
th_arena_allocator_init_with_alignment(th_arena_allocator* allocator, void* buf, size_t size, size_t alignment, th_allocator* fallback);
/* th_arena_allocator end */
/* th_pool_allocator begin */
typedef struct th_pool_allocator_node th_pool_allocator_node;
struct th_pool_allocator_node {
th_pool_allocator_node* next;
th_pool_allocator_node* prev;
};
TH_DEFINE_LIST(th_pool_allocator_list, th_pool_allocator_node, prev, next)
typedef struct th_pool_allocator {
th_allocator base;
th_pool_allocator_list free_list;
th_pool_allocator_list used_list;
th_allocator* allocator;
size_t block_size;
} th_pool_allocator;
TH_PRIVATE(void)
th_pool_allocator_init(th_pool_allocator* pool, th_allocator* allocator, size_t block_size);
TH_PRIVATE(void)
th_pool_allocator_deinit(th_pool_allocator* pool);
/** Generic object pool allocator.
* The pool allocator is a allocator that allocates objects from a pool of fixed-size blocks.
* It can be used with any object that has a next and prev pointer.
*/
#define TH_DEFINE_OBJ_POOL_ALLOCATOR(NAME, T, PREV, NEXT) \
TH_DEFINE_LIST(NAME##_list, T, PREV, NEXT) \
typedef struct NAME { \
th_allocator base; \
NAME##_list free_list; \
NAME##_list used_list; \
th_allocator* allocator; \
size_t count; \
size_t max; \
} NAME; \
\
TH_INLINE(void) \
NAME##_init(NAME* pool, th_allocator* allocator, size_t initial, size_t max) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_deinit(NAME* pool) TH_MAYBE_UNUSED; \
\
TH_INLINE(void*) \
NAME##_alloc(void* self, size_t) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_free(void* self, void* ptr) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_init(NAME* pool, th_allocator* allocator, size_t initial, size_t max) \
{ \
TH_ASSERT(allocator != NULL && "Invalid allocator"); \
TH_ASSERT(max > 0 && "Invalid max"); \
pool->base.alloc = NAME##_alloc; \
pool->base.realloc = NULL; \
pool->base.free = NAME##_free; \
pool->allocator = allocator; \
pool->count = 0; \
pool->max = max; \
pool->used_list = (NAME##_list){0}; \
pool->free_list = (NAME##_list){0}; \
for (size_t i = 0; i < initial; i++) { \
T* item = (T*)th_allocator_alloc(pool->allocator, sizeof(T)); \
if (item) { \
NAME##_list_push_back(&pool->free_list, item); \
++pool->count; \
} \
} \
} \
\
TH_INLINE(void) \
NAME##_deinit(NAME* pool) \
{ \
T* item = NULL; \
while ((item = NAME##_list_pop_front(&pool->free_list))) { \
th_allocator_free(pool->allocator, item); \
} \
item = NAME##_list_pop_front(&pool->used_list); \
TH_ASSERT(item == NULL); \
} \
\
TH_INLINE(void*) \
NAME##_alloc(void* self, size_t size) \
{ \
TH_ASSERT(size == sizeof(T) && "Invalid size"); \
(void)size; \
NAME* pool = (NAME*)self; \
T* item = NAME##_list_pop_front(&pool->free_list); \
if (item == NULL) { \
if (pool->count < pool->max) { \
item = (T*)th_allocator_alloc(pool->allocator, sizeof(T)); \
if (item) { \
pool->count++; \
} \
} \
} \
if (item) { \
NAME##_list_push_back(&pool->used_list, item); \
} \
return item; \
} \
\
TH_INLINE(void) \
NAME##_free(void* self, void* ptr) \
{ \
NAME* pool = (NAME*)self; \
T* item = (T*)ptr; \
if (item) { \
NAME##_list_erase(&pool->used_list, item); \
NAME##_list_push_back(&pool->free_list, item); \
} \
}
/* End of th_allocator.h */
/* Start of th_hash.h */
#include <stddef.h>
#include <stdint.h>
#include <string.h>
/** th_hash_bytes
* @brief Fowler-Noll-Vo hash function (FNV-1a).
* See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*/
TH_INLINE(size_t)
th_hash_bytes(const void* data, size_t len)
{
size_t hash = 2166136261u;
const uint8_t* bytes = (const uint8_t*)data;
for (size_t i = 0; i < len; ++i) {
hash ^= bytes[i];
hash *= 16777619;
}
return hash;
}
TH_INLINE(size_t)
th_hash_cstr(const char* str)
{
return th_hash_bytes(str, strlen(str));
}
/* End of th_hash.h */
/* Start of th_hashmap.h */
#include <string.h>
#define TH_DEFINE_HASHMAP(NAME, K, V, HASH, K_EQ, K_NULL) \
typedef struct NAME##_entry { \
K key; \
V value; \
} NAME##_entry; \
\
typedef struct NAME { \
NAME##_entry* entries; \
size_t size; \
size_t capacity; \
size_t end; \
size_t begin; \
th_allocator* allocator; \
} NAME; \
\
TH_INLINE(void) \
NAME##_init(NAME* map, th_allocator* allocator) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_reset(NAME* map) TH_MAYBE_UNUSED; \
\
TH_INLINE(th_err) \
NAME##_reserve(NAME* map, size_t capacity) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_deinit(NAME* map) TH_MAYBE_UNUSED; \
\
TH_INLINE(th_err) \
NAME##_set(NAME* map, K key, V value) TH_MAYBE_UNUSED; \
\
TH_INLINE(V*) \
NAME##_try_get(const NAME* map, K key) TH_MAYBE_UNUSED; \
\
typedef NAME##_entry* NAME##_iter; \
\
TH_INLINE(NAME##_entry*) \
NAME##_find(const NAME* map, K key) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_erase(NAME* map, NAME##_entry* entry) TH_MAYBE_UNUSED; \
\
TH_INLINE(NAME##_entry*) \
NAME##_begin(NAME* map) TH_MAYBE_UNUSED; \
\
TH_INLINE(NAME##_entry*) \
NAME##_next(NAME* map, NAME##_entry* entry) TH_MAYBE_UNUSED; \
\
TH_INLINE(NAME##_entry*) \
NAME##_prev(NAME* map, NAME##_entry* entry) TH_MAYBE_UNUSED; \
\
TH_INLINE(void) \
NAME##_init(NAME* map, th_allocator* allocator) \
{ \
map->allocator = allocator; \
if (map->allocator == NULL) { \
map->allocator = th_default_allocator_get(); \
} \
map->entries = NULL; \
map->size = 0; \
map->capacity = 0; \