Repository navigation
Expand file tree
/
Copy pathmate.h
More file actions
7022 lines (6357 loc) · 244 KB
/
Copy pathmate.h
File metadata and controls
7022 lines (6357 loc) · 244 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
/* MIT License
mate.h - A single-header library for compiling your C code in C
Version - 2025-05-29 (0.2.1):
https://github.com/TomasBorquez/mate.h
Guide on the `README.md`
*/
#pragma once
#ifdef MATE_IMPLEMENTATION
# define BASE_IMPLEMENTATION
#endif
// --- BASE.H START ---
/* MIT License
base.h - Better cross-platform STD
Version - 2025-06-06 (0.2.3):
https://github.com/TomasBorquez/base.h
Usage:
#define BASE_IMPLEMENTATION
#include "base.h"
More on the the `README.md`
*/
/* --- Platform MACROS and includes --- */
#if defined(__clang__)
# define COMPILER_CLANG
#elif defined(_MSC_VER)
# define COMPILER_MSVC
#elif defined(__GNUC__)
# define COMPILER_GCC
#elif defined(__TINYC__)
# define COMPILER_TCC
#else
# error "The codebase only supports GCC, Clang, TCC and MSVC"
#endif
#if defined(COMPILER_GCC) || defined(COMPILER_CLANG)
# define NORETURN __attribute__((noreturn))
# define UNLIKELY(x) __builtin_expect(!!(x), 0)
# define ALLOC_ATTR2(sz, al) __attribute__((malloc, alloc_size(sz), alloc_align(al)))
# define ALLOC_ATTR(sz) __attribute__((malloc, alloc_size(sz)))
# define FORMAT_CHECK(fmt_pos, args_pos) __attribute__((format(printf, fmt_pos, args_pos)))
# define WARN_UNUSED __attribute__((warn_unused_result))
#elif defined(COMPILER_MSVC)
# define NORETURN __declspec(noreturn)
# define UNLIKELY(x) x
# define ALLOC_ATTR2(sz, al)
# define ALLOC_ATTR(sz)
# define FORMAT_CHECK(fmt_pos, args_pos)
# define WARN_UNUSED _Check_return_
#else
# define NORETURN __declspec(noreturn)
# define UNLIKELY(x) x
# define ALLOC_ATTR2(sz, al)
# define ALLOC_ATTR(sz)
# define FORMAT_CHECK(fmt_pos, args_pos)
# define WARN_UNUSED
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
# define PLATFORM_WIN
#else
# define PLATFORM_UNIX
# if defined(__ANDROID__)
# define PLATFORM_ANDROID
# elif defined(__linux__) || defined(__gnu_linux__)
# define PLATFORM_LINUX
# elif defined(__APPLE__) || defined(__MACH__)
# define PLATFORM_MACOS
# elif defined(__FreeBSD__)
# define PLATFORM_FREEBSD
# elif defined(__EMSCRIPTEN__)
# define PLATFORM_EMSCRIPTEN
# else
# error "The codebase only supports linux, macos, FreeBSD, windows, android and emscripten"
# endif
#endif
#if defined(COMPILER_CLANG)
# define FILE_NAME __FILE_NAME__
#else
# define FILE_NAME __FILE__
#endif
#if defined(PLATFORM_WIN)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) // Old SDKs sometimes dont have it
# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
# endif
#else
# define _POSIX_C_SOURCE 200809L
# define _GNU_SOURCE
# include <dirent.h>
# include <errno.h>
# include <fcntl.h>
# include <limits.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
#endif
#if defined(__STDC_VERSION__)
# if (__STDC_VERSION__ >= 202311L)
# define C_STANDARD_C23
# define C_STANDARD "C23"
# elif (__STDC_VERSION__ >= 201710L)
# define C_STANDARD_C17
# define C_STANDARD "C17"
# elif (__STDC_VERSION__ >= 201112L)
# define C_STANDARD_C11
# define C_STANDARD "C11"
# elif (__STDC_VERSION__ >= 199901L)
# define C_STANDARD_C99
# define C_STANDARD "C99"
# else
# error "Why C89 if you have C99"
# endif
#else
# if defined(COMPILER_MSVC)
# if defined(_MSC_VER) && _MSC_VER >= 1920 // >= Visual Studio 2019
# define C_STANDARD_C17
# define C_STANDARD "C17"
# else
# define C_STANDARD_C11
# define C_STANDARD "C11"
# endif
# endif
#endif
#include <ctype.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* --- Platform Specific --- */
#if defined(PLATFORM_WIN)
/* Process functions */
# define popen _popen
# define pclose _pclose
/* File I/O functions */
# define fileno _fileno
# define fdopen _fdopen
# define access _access
# define unlink _unlink
# define isatty _isatty
# define dup _dup
# define dup2 _dup2
# define ftruncate _chsize
# define fsync _commit
/* Directory functions */
# define mkdir(path, mode) _mkdir(path)
# define rmdir _rmdir
# define getcwd _getcwd
# define chdir _chdir
/* Process/Threading */
# define getpid _getpid
# define sleep(x) Sleep((x) * 1000)
# define usleep(x) Sleep((x) / 1000)
/* String functions */
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
# define strdup _strdup
/* File modes */
# define R_OK 4
# define W_OK 2
# define X_OK 0 /* Windows doesn't have explicit X_OK */
# define F_OK 0
/* File descriptors */
# define STDIN_FILENO 0
# define STDOUT_FILENO 1
# define STDERR_FILENO 2
/* Some functions need complete replacements */
# if defined(COMPILER_MSVC)
# define snprintf _snprintf
# define vsnprintf _vsnprintf
# endif
#endif
/* --- Types and MACRO types --- */
// Unsigned int types
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
// Signed int types
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
// Regular int types
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
// Floating point types
typedef float f32;
typedef double f64;
typedef struct {
size_t length; // Does not include null terminator
char *data;
} String;
#define FMT_I8 "%" PRIi8
#define FMT_I16 "%" PRIi16
#define FMT_I32 "%" PRIi32
#define FMT_I64 "%" PRIi64
#define FMT_U8 "%" PRIu8
#define FMT_U16 "%" PRIu16
#define FMT_U32 "%" PRIu32
#define FMT_U64 "%" PRIu64
// Maximum values for integer types
#define U8_MAX UINT8_MAX
#define U16_MAX UINT16_MAX
#define U32_MAX UINT32_MAX
#define U64_MAX UINT64_MAX
#define S8_MAX INT8_MAX
#define S8_MIN INT8_MIN
#define S16_MAX INT16_MAX
#define S16_MIN INT16_MIN
#define S32_MAX INT32_MAX
#define S32_MIN INT32_MIN
#define S64_MAX INT64_MAX
#define S64_MIN INT64_MIN
#define I8_MAX INT8_MAX
#define I8_MIN INT8_MIN
#define I16_MAX INT16_MAX
#define I16_MIN INT16_MIN
#define I32_MAX INT32_MAX
#define I32_MIN INT32_MIN
#define I64_MAX INT64_MAX
#define I64_MIN INT64_MIN
/* --- Assertions --- */
void _custom_assert(const char *expr, const char *file, unsigned line, const char *format, ...) FORMAT_CHECK(4, 5);
#define Assert(expression, ...) (void)((!!(expression)) || (_custom_assert(#expression, __FILE__, __LINE__, __VA_ARGS__), 0))
void _custom_unreachable(const char *file, unsigned line, const char *format, ...) FORMAT_CHECK(3, 4);
#define Unreachable(...) (void)((_custom_unreachable(__FILE__, __LINE__, __VA_ARGS__), 0))
/* --- Vector --- */
typedef i32 (*CompareFunc)(const void *a, const void *b);
i32 __base_vec_partition(void **data, size_t element_size, CompareFunc compare, i32 low, i32 high);
void __base_vec_quicksort(void **data, size_t element_size, CompareFunc compare, i32 low, i32 high);
#define VecSort(vector, compare) __base_vec_quicksort((void **)&(vector).data, sizeof(*(vector).data), compare, 0, (vector).length - 1)
#define VEC_TYPE(typeName, valueType) \
typedef struct { \
valueType *data; \
size_t length; \
size_t capacity; \
} typeName
#define VecReserve(vector, count) \
do { \
vector.capacity = (count); \
vector.data = Malloc((count) * sizeof(*(vector).data)); \
} while (0)
#define VecPush(vector, value) __base_vec_push((void **)&(vector).data, &(vector).length, &(vector).capacity, sizeof(*(vector).data), &(value));
void __base_vec_push(void **data, size_t *length, size_t *capacity, size_t element_size, void *value);
#define VecPop(vector) __base_vec_pop((vector).data, &(vector).length, sizeof(*(vector).data));
void *__base_vec_pop(void *data, size_t *length, size_t element_size);
#define VecShift(vector) __base_vec_shift((void **)&(vector).data, &(vector).length, sizeof(*(vector).data))
void __base_vec_shift(void **data, size_t *length, size_t element_size);
#define VecUnshift(vector, value) __base_vec_unshift((void **)&(vector).data, &(vector).length, &(vector).capacity, sizeof(*(vector).data), &(value))
void __base_vec_unshift(void **data, size_t *length, size_t *capacity, size_t element_size, const void *value);
#define VecInsert(vector, value, index) __base_vec_insert((void **)&(vector).data, &(vector).length, &(vector).capacity, sizeof(*(vector).data), &(value), (index))
void __base_vec_insert(void **data, size_t *length, size_t *capacity, size_t element_size, void *value, size_t index);
#define VecAt(vector, index) (*(__typeof__(*(vector).data) *)__base_vec_at((void **)&(vector).data, &(vector).length, index, sizeof(*(vector).data)))
void *__base_vec_at(void **data, size_t *length, size_t index, size_t elementSize);
#define VecAtPtr(vector, index) (__base_vec_at((void **)&(vector).data, &(vector).length, (index), sizeof(*(vector).data)))
#define VecFree(vector) __base_vec_free((void **)&(vector).data, &(vector).length, &(vector).capacity)
void __base_vec_free(void **data, size_t *length, size_t *capacity);
#define VecForEach(vector, it) for (__typeof__(*(vector).data) *(it) = (vector).data; it < (vector).data + (vector).length; it++)
/* --- Time and Platforms --- */
i64 TimeNow(void);
void WaitTime(i64 ms);
bool isLinux(void);
bool isMacOs(void);
bool isWindows(void);
bool isUnix(void);
bool isAndroid(void);
bool isEmscripten(void);
bool isFreeBSD(void);
typedef enum { WINDOWS = 1, LINUX, MACOS, FREEBSD } Platform;
Platform GetPlatform(void);
typedef enum { GCC = 1, CLANG, TCC, MSVC } Compiler;
Compiler GetCompiler(void);
/* --- Error --- */
typedef i32 errno_t;
typedef enum {
SUCCESS = 0,
} GeneralError;
String ErrToStr(errno_t err);
/* --- Arena --- */
typedef struct __ArenaChunk {
struct __ArenaChunk *next;
size_t cap;
char buffer[];
} __ArenaChunk;
typedef struct {
__ArenaChunk *current;
size_t offset;
__ArenaChunk *root;
size_t chunkSize;
} Arena;
// This makes sure right alignment on 86/64 bits
#define DEFAULT_ALIGNMENT (2 * sizeof(void *))
Arena *ArenaCreate(size_t chunkSize);
ALLOC_ATTR2(2, 3) void *ArenaAllocAligned(Arena *arena, size_t size, size_t align);
ALLOC_ATTR(2) char *ArenaAllocChars(Arena *arena, size_t count);
ALLOC_ATTR(2) void *ArenaAlloc(Arena *arena, size_t size);
void ArenaFree(Arena *arena);
void ArenaReset(Arena *arena);
/* --- Memory Allocations --- */
void *Realloc(void *block, size_t size);
void *Malloc(size_t size);
void Free(void *address);
/* --- String and Macros --- */
#define TYPE_INIT(type) (type)
#define STRING_LENGTH(s) ((sizeof((s)) / sizeof((s)[0])) - sizeof((s)[0])) // NOTE: Inspired from clay.h
#define ENSURE_STRING_LITERAL(x) ("" x "")
// NOTE: If an error led you here, it's because `S` can only be used with string literals, i.e. `S("SomeString")` and not `S(yourString)` - for that use `s()`
#define S(string) (TYPE_INIT(String){.length = STRING_LENGTH(ENSURE_STRING_LITERAL(string)), .data = (char *)(uintptr_t)(string)})
String s(char *msg);
String F(Arena *arena, const char *format, ...) FORMAT_CHECK(2, 3);
VEC_TYPE(StringVector, String);
#define StringVectorPushMany(vector, ...) \
do { \
char *values[] = {__VA_ARGS__}; \
size_t count = sizeof(values) / sizeof(values[0]); \
for (size_t i = 0; i < count; i++) { \
String value = s(values[i]); \
VecPush((vector), value); \
} \
} while (0)
void SetMaxStrSize(size_t size);
String StrNew(Arena *arena, char *str);
String StrNewSize(Arena *arena, char *str, size_t len); // Without null terminator
void StrCopy(String destination, String source);
StringVector StrSplit(Arena *arena, String string, String delimiter);
StringVector StrSplitNewLine(Arena *arena, String str);
bool StrEq(String string1, String string2);
String StrConcat(Arena *arena, String string1, String string2);
void StrToLower(String string1);
void StrToUpper(String string1);
bool StrIsNull(String string);
void StrTrim(String *string);
String StrSlice(Arena *arena, String str, size_t start, size_t end);
String NormalizePath(Arena *arena, String path);
String NormalizeExePath(Arena *arena, String path);
String NormalizeExtension(Arena *arena, String path);
String NormalizeStaticLibPath(Arena *arena, String path);
String NormalizePathStart(Arena *arena, String path);
String NormalizePathEnd(Arena *arena, String path);
typedef struct {
size_t capacity;
String buffer;
} StringBuilder;
StringBuilder StringBuilderCreate(Arena *arena);
StringBuilder StringBuilderReserve(Arena *arena, size_t capacity);
void StringBuilderAppend(Arena *arena, StringBuilder *builder, String *string);
/* --- Random --- */
void RandomInit(void);
u64 RandomGetSeed(void);
void RandomSetSeed(u64 newSeed);
i32 RandomInteger(i32 min, i32 max);
f32 RandomFloat(f32 min, f32 max);
/* --- File System --- */
#define MAX_FILES 200
typedef struct {
char *name;
char *extension;
i64 size;
i64 createTime;
i64 modifyTime;
} File;
char *GetCwd(void);
void SetCwd(char *destination);
bool Mkdir(String path); // NOTE: Mkdir if not exist
StringVector ListDir(Arena *arena, String path);
typedef enum { FILE_STATS_SUCCESS = 0, FILE_GET_ATTRIBUTES_FAILED = 100, FILE_STATS_FILE_NOT_EXIST } FileStatsError;
WARN_UNUSED FileStatsError FileStats(String path, File *file);
typedef enum { FILE_READ_SUCCESS = 0, FILE_NOT_EXIST = 200, FILE_OPEN_FAILED, FILE_GET_SIZE_FAILED, FILE_READ_FAILED } FileReadError;
WARN_UNUSED FileReadError FileRead(Arena *arena, String path, String *result);
typedef enum { FILE_WRITE_SUCCESS = 0, FILE_WRITE_OPEN_FAILED = 300, FILE_WRITE_ACCESS_DENIED, FILE_WRITE_NO_MEMORY, FILE_WRITE_NOT_FOUND, FILE_WRITE_DISK_FULL, FILE_WRITE_IO_ERROR } FileWriteError;
WARN_UNUSED FileWriteError FileWrite(String path, String data);
typedef enum { FILE_ADD_SUCCESS = 0, FILE_ADD_OPEN_FAILED = 400, FILE_ADD_ACCESS_DENIED, FILE_ADD_NO_MEMORY, FILE_ADD_NOT_FOUND, FILE_ADD_DISK_FULL, FILE_ADD_IO_ERROR } FileAddError;
WARN_UNUSED FileAddError FileAdd(String path, String data); // NOTE: Adds `\n` at the end always
typedef enum { FILE_DELETE_SUCCESS = 0, FILE_DELETE_ACCESS_DENIED = 500, FILE_DELETE_NOT_FOUND, FILE_DELETE_IO_ERROR } FileDeleteError;
WARN_UNUSED FileDeleteError FileDelete(String path);
typedef enum { FILE_RENAME_SUCCESS = 0, FILE_RENAME_ACCESS_DENIED = 600, FILE_RENAME_NOT_FOUND, FILE_RENAME_IO_ERROR } FileRenameError;
WARN_UNUSED FileRenameError FileRename(String oldPath, String newPath);
typedef enum { FILE_COPY_SUCCESS = 0, FILE_COPY_SOURCE_NOT_FOUND = 700, FILE_COPY_DEST_ACCESS_DENIED, FILE_COPY_SOURCE_ACCESS_DENIED, FILE_COPY_DISK_FULL, FILE_COPY_IO_ERROR } FileCopyError;
WARN_UNUSED FileCopyError FileCopy(String sourcePath, String destPath);
// NOTE: Same error enum since it uses `FileWrite("")` under the hood
WARN_UNUSED FileWriteError FileReset(String path);
/* --- Logger --- */
#define _RESET "\x1b[0m"
#define _GRAY "\x1b[0;36m"
#define _RED "\x1b[0;31m"
#define _GREEN "\x1b[0;32m"
#define _ORANGE "\x1b[0;33m"
void LogInit(void);
void LogInfo(const char *format, ...) FORMAT_CHECK(1, 2);
void LogWarn(const char *format, ...) FORMAT_CHECK(1, 2);
void LogError(const char *format, ...) FORMAT_CHECK(1, 2);
void logErrorV(const char *format, va_list args) FORMAT_CHECK(1, 0);
void LogSuccess(const char *format, ...) FORMAT_CHECK(1, 2);
/* --- Math --- */
#define Min(a, b) (((a) < (b)) ? (a) : (b))
#define Max(a, b) (((a) > (b)) ? (a) : (b))
#define Clamp(a, x, b) (((x) < (a)) ? (a) : ((b) < (x)) ? (b) : (x))
#define Swap(a, b) \
do { \
a ^= b; \
b ^= a; \
a ^= b; \
} while (0);
/* --- Defer Macros --- */
#if defined(DEFER_MACRO)
/* [GCC implementation] Must use C23 (depending on the platform) */
# if defined(COMPILER_GCC)
# define defer __DEFER(__COUNTER__)
# define __DEFER(N) __DEFER_(N)
# define __DEFER_(N) __DEFER__(__DEFER_FUNCTION_##N, __DEFER_VARIABLE_##N)
# define __DEFER__(F, V) \
auto void F(int *); \
[[gnu::cleanup(F)]] int V; \
auto void F(int *)
/* [Clang implementation] Must compile with flag `-fblocks` */
# elif defined(COMPILER_CLANG)
typedef void (^const __df_t)(void);
[[maybe_unused]]
static inline void __df_cb(__df_t *__fp) {
(*__fp)();
}
# define defer __DEFER(__COUNTER__)
# define __DEFER(N) __DEFER_(N)
# define __DEFER_(N) __DEFER__(__DEFER_VARIABLE_##N)
# define __DEFER__(V) [[gnu::cleanup(__df_cb)]] __df_t V = ^void(void)
/* [MSVC implementation] */
# elif defined(COMPILER_MSVC)
# error "Not available yet in MSVC, use `_try/_finally`"
# endif
#endif
/* --- INI Parser --- */
typedef struct {
String key;
String value;
} IniEntry;
VEC_TYPE(IniEntryVector, IniEntry);
typedef struct {
IniEntryVector data;
Arena *arena;
} IniFile;
WARN_UNUSED errno_t IniParse(String path, IniFile *result);
WARN_UNUSED errno_t IniWrite(String path, IniFile *iniFile); // NOTE: Updates/Creates .ini file
void IniFree(IniFile *iniFile);
String IniGet(IniFile *ini, String key);
String IniSet(IniFile *ini, String key, String value);
i32 IniGetInt(IniFile *ini, String key);
i64 IniGetLong(IniFile *ini, String key);
f64 IniGetDouble(IniFile *ini, String key);
bool IniGetBool(IniFile *ini, String key);
/* MIT License
base.h - Implementation of base.h
https://github.com/TomasBorquez/base.h
*/
#if defined(BASE_IMPLEMENTATION)
/* --- Vector Implementation --- */
i32 __base_vec_partition(void **data, size_t element_size, CompareFunc compare, i32 low, i32 high) {
void *pivot = (char *)(*data) + (high * element_size);
i32 i = low - 1;
for (i32 j = low; j < high; j++) {
void *current = (char *)(*data) + (j * element_size);
if (compare(current, pivot) < 0) {
i++;
void *temp = (char *)(*data) + (i * element_size);
char *temp_buffer = Malloc(element_size);
memcpy(temp_buffer, temp, element_size);
memcpy(temp, current, element_size);
memcpy(current, temp_buffer, element_size);
Free(temp_buffer);
}
}
i++;
void *temp = (char *)(*data) + (i * element_size);
char *temp_buffer = Malloc(element_size);
memcpy(temp_buffer, temp, element_size);
memcpy(temp, pivot, element_size);
memcpy(pivot, temp_buffer, element_size);
Free(temp_buffer);
return i;
}
void __base_vec_quicksort(void **data, size_t element_size, CompareFunc compare, i32 low, i32 high) {
if (low < high) {
i32 pi = __base_vec_partition(data, element_size, compare, low, high);
__base_vec_quicksort(data, element_size, compare, low, pi - 1);
__base_vec_quicksort(data, element_size, compare, pi + 1, high);
}
}
void __base_vec_push(void **data, size_t *length, size_t *capacity, size_t element_size, void *value) {
// WARNING: Vector must always be initialized to zero `Vector vector = {0}`
Assert(*length <= *capacity, "VecPush: Possible memory corruption or vector not initialized, `Vector vector = {0}`");
Assert(!(*length > 0 && *data == NULL), "VecPush: Possible memory corruption, data should be NULL only if length == 0");
if (*length >= *capacity) {
if (*capacity == 0) *capacity = 128;
else *capacity *= 2;
*data = Realloc(*data, *capacity * element_size);
}
void *address = (char *)(*data) + (*length * element_size);
memcpy(address, value, element_size);
(*length)++;
}
void *__base_vec_pop(void *data, size_t *length, size_t element_size) {
Assert(*length > 0, "VecPop: Cannot pop from empty vector");
(*length)--;
return (char *)data + (*length * element_size);
}
void __base_vec_shift(void **data, size_t *length, size_t element_size) {
Assert(*length != 0, "VecShift: Length should at least be >= 1");
memmove(*data, (char *)(*data) + element_size, ((*length) - 1) * element_size);
(*length)--;
}
void __base_vec_unshift(void **data, size_t *length, size_t *capacity, size_t element_size, const void *value) {
if (*length >= *capacity) {
if (*capacity == 0) *capacity = 2;
else *capacity *= 2;
*data = Realloc(*data, *capacity * element_size);
}
if (*length > 0) {
memmove((char *)(*data) + element_size, *data, (*length) * element_size);
}
memcpy(*data, value, element_size);
(*length)++;
}
void __base_vec_insert(void **data, size_t *length, size_t *capacity, size_t element_size, void *value, size_t index) {
Assert(index <= *length, "VecInsert: Index out of bounds for insertion");
if (*length >= *capacity) {
if (*capacity == 0) *capacity = 2;
else *capacity *= 2;
*data = Realloc(*data, *capacity * element_size);
}
if (index < *length) {
memmove((char *)(*data) + ((index + 1) * element_size), (char *)(*data) + (index * element_size), (*length - index) * element_size);
}
memcpy((char *)(*data) + (index * element_size), value, element_size);
(*length)++;
}
void *__base_vec_at(void **data, size_t *length, size_t index, size_t elementSize) {
Assert(index >= 0 && index < *length, "VecAt: Index out of bounds");
void *address = (char *)(*data) + (index * elementSize);
return address;
}
void __base_vec_free(void **data, size_t *length, size_t *capacity) {
free(*data);
*data = NULL;
*length = 0;
*capacity = 0;
}
/* --- Time and Platforms Implementation --- */
# if !defined(PLATFORM_WIN)
# if !defined(EINVAL)
# define EINVAL 22 // Invalid argument
# endif
# if !defined(ERANGE)
# define ERANGE 34 // Result too large
# endif
WARN_UNUSED errno_t memcpy_s(void *dest, size_t destSize, const void *src, size_t count) {
if (dest == NULL) {
return EINVAL;
}
if (src == NULL || destSize < count) {
memset(dest, 0, destSize);
return EINVAL;
}
memcpy(dest, src, count);
return 0;
}
WARN_UNUSED errno_t fopen_s(FILE **streamptr, const char *filename, const char *mode) {
if (streamptr == NULL) {
return EINVAL;
}
*streamptr = NULL;
if (filename == NULL || mode == NULL) {
return EINVAL;
}
if (*filename == '\0') {
return EINVAL;
}
const char *valid_modes = "rwa+btx";
size_t mode_len = strlen(mode);
if (mode_len == 0) {
return EINVAL;
}
for (size_t i = 0; i < mode_len; i++) {
if (strchr(valid_modes, mode[i]) == NULL) {
return EINVAL;
}
}
*streamptr = fopen(filename, mode);
if (*streamptr == NULL) {
return errno;
}
return 0;
}
# endif
bool isLinux(void) {
# if defined(PLATFORM_LINUX)
return true;
# else
return false;
# endif
}
bool isMacOs(void) {
# if defined(PLATFORM_MACOS)
return true;
# else
return false;
# endif
}
bool isWindows(void) {
# if defined(PLATFORM_WIN)
return true;
# else
return false;
# endif
}
bool isUnix(void) {
# if defined(PLATFORM_UNIX)
return true;
# else
return false;
# endif
}
bool isAndroid(void) {
# if defined(PLATFORM_EMSCRIPTEN)
return true;
# else
return false;
# endif
}
bool isEmscripten(void) {
# if defined(PLATFORM_EMSCRIPTEN)
return true;
# else
return false;
# endif
}
bool isFreeBSD(void) {
# if defined(PLATFORM_FREEBSD)
return true;
# else
return false;
# endif
}
Compiler GetCompiler(void) {
# if defined(COMPILER_CLANG)
return CLANG;
# elif defined(COMPILER_GCC)
return GCC;
# elif defined(COMPILER_TCC)
return TCC;
# elif defined(COMPILER_MSVC)
return MSVC;
# endif
}
Platform GetPlatform(void) {
# if defined(PLATFORM_WIN)
return WINDOWS;
# elif defined(PLATFORM_LINUX)
return LINUX;
# elif defined(PLATFORM_MACOS)
return MACOS;
# elif defined(PLATFORM_FREEBSD)
return FREEBSD;
# endif
}
i64 TimeNow(void) {
# if defined(PLATFORM_WIN)
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
LARGE_INTEGER li;
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
// Convert Windows FILETIME (100-nanosecond intervals since January 1, 1601)
// to UNIX timestamp in milliseconds
i64 currentTime = (li.QuadPart - 116444736000000000LL) / 10000;
# else
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
i64 currentTime = (ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
# endif
Assert(currentTime != -1, "TimeNow: currentTime should never be -1");
return currentTime;
}
void WaitTime(i64 ms) {
# if defined(PLATFORM_WIN)
sleep(ms);
# else
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000;
nanosleep(&ts, NULL);
# endif
}
/* --- Error Implementation --- */
String ErrToStr(errno_t err) {
if (err < 100) {
# if defined(PLATFORM_WIN)
char buffer[256];
DWORD msgLen = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, sizeof(buffer), NULL);
// Trim message
if (msgLen > 0) {
while (msgLen > 0 && (buffer[msgLen - 1] == '\r' || buffer[msgLen - 1] == '\n')) {
buffer[--msgLen] = '\0';
}
if (msgLen > 0 && buffer[msgLen - 1] == '.') {
buffer[--msgLen] = '\0';
}
return s(buffer);
}
return S("Unknown system error");
# else
return s(strerror(err));
# endif
}
switch (err) {
// FileStats errors (100-199)
case FILE_GET_ATTRIBUTES_FAILED:
return S("Failed to get file attributes");
case FILE_STATS_FILE_NOT_EXIST:
return S("File does not exist");
// FileRead errors (200-299)
case FILE_NOT_EXIST:
return S("File does not exist");
case FILE_OPEN_FAILED:
return S("Failed to open file for reading");
case FILE_GET_SIZE_FAILED:
return S("Failed to get file size");
case FILE_READ_FAILED:
return S("Failed to read file");
// FileWrite errors (300-399)
case FILE_WRITE_OPEN_FAILED:
return S("Failed to open file for writing");
case FILE_WRITE_ACCESS_DENIED:
return S("Access denied when writing file");
case FILE_WRITE_NO_MEMORY:
return S("Not enough memory to write file");
case FILE_WRITE_NOT_FOUND:
return S("File not found for writing");
case FILE_WRITE_DISK_FULL:
return S("Disk full when writing file");
case FILE_WRITE_IO_ERROR:
return S("I/O error when writing file");
// FileAdd errors (400-499)
case FILE_ADD_OPEN_FAILED:
return S("Failed to open file for appending");
case FILE_ADD_ACCESS_DENIED:
return S("Access denied when appending to file");
case FILE_ADD_NO_MEMORY:
return S("Not enough memory to append to file");
case FILE_ADD_NOT_FOUND:
return S("File not found for appending");
case FILE_ADD_DISK_FULL:
return S("Disk full when appending to file");
case FILE_ADD_IO_ERROR:
return S("I/O error when appending to file");
// FileDelete errors (500-599)
case FILE_DELETE_ACCESS_DENIED:
return S("Access denied when deleting file");
case FILE_DELETE_NOT_FOUND:
return S("File not found for deletion");
case FILE_DELETE_IO_ERROR:
return S("I/O error when deleting file");
// FileRename errors (600-699)
case FILE_RENAME_ACCESS_DENIED:
return S("Access denied when renaming file");
case FILE_RENAME_NOT_FOUND:
return S("File not found for renaming");
case FILE_RENAME_IO_ERROR:
return S("I/O error when renaming file");
default:
return S("Unknown file error");
}
}
void _custom_assert(const char *expr, const char *file, unsigned line, const char *format, ...) {
printf("%sAssertion failed: %s, file %s, line %u %s\n", _RED, expr, file, line, _RESET);
if (format) {
va_list args;
va_start(args, format);
logErrorV(format, args);
va_start(args, format);
}
abort();
}
void _custom_unreachable(const char *file, unsigned line, const char *format, ...) {
printf("%sReached Unreachable code at file %s, line %u %s\n", _RED, file, line, _RESET);
if (format) {
va_list args;
va_start(args, format);
logErrorV(format, args);
va_start(args, format);
}
abort();
}
/* --- Arena Implementation --- */
// Allocate or iterate to next chunk that can fit `bytes`
static void __ArenaNextChunk(Arena *arena, size_t bytes) {
__ArenaChunk *next = arena->current ? arena->current->next : NULL;
while (next) {
arena->current = next;
if (arena->current->cap > bytes) {
return;
}
next = arena->current->next;
}
next = (__ArenaChunk *)Malloc(sizeof(__ArenaChunk) + bytes);
next->cap = bytes;
next->next = NULL;
if (arena->current) arena->current->next = next;
arena->current = next;
}
void *ArenaAllocAligned(Arena *arena, size_t size, size_t al) {
void *current_pos = arena->current->buffer + arena->offset;
intptr_t mask = al - 1;
intptr_t misalignment = ((intptr_t)current_pos & mask);
intptr_t padding = misalignment ? al - misalignment : 0;
arena->offset += padding;
void *result;
if (arena->offset + size > arena->current->cap) {
size_t bytes = size > arena->chunkSize ? size : arena->chunkSize;
__ArenaNextChunk(arena, bytes);
current_pos = arena->current->buffer;
misalignment = ((intptr_t)current_pos & mask);
padding = misalignment ? al - misalignment : 0;
arena->offset = padding;
result = arena->current->buffer + arena->offset;
arena->offset += size;
} else {
result = arena->current->buffer + arena->offset;
arena->offset += size;
}
if (size) memset(result, 0, size);