-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviclib.h
More file actions
2140 lines (1859 loc) · 68.5 KB
/
viclib.h
File metadata and controls
2140 lines (1859 loc) · 68.5 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
/* date = December 29th 2024 10:12 pm
--Author: Víctor López Cortés
--version: 1.6.1
--Usage:
Defines: To have any of these take effect, you must define them _before_ including this file
- VICLIB_IMPLEMENTATION: If you want to have the implementation (only in one file)
- READ_ENTIRE_FILE_MAX: If you want to have a max file read size, default is 0xFFFFFFFF (4GB)
- QUIET_ASSERT: If you want the assertions to add a breakpoint but not print
- RELEASE_MODE: Have some stuff work faster, right now, assertions get compiled out when this is defined
- VICLIB_PROC: Define to 'static' or some kind of export as needed
- VICLIB_TEMP_SIZE: ArenaTemp size, default is 4*1024*1024 bytes
- VICLIB_NO*: If you want to remove parts of the library:
- VICLIB_NO_TEMP_ARENA: remove ArenaTemp
- VICLIB_NO_SORT: remove Sort and all functions used by it
Check VL_ErrorNumber when errors occur.
--Many thanks to the inspirations for this library:
- Mr4th's 4ed_base_types.h - https://mr-4th.itch.io/4coder (find the file in 'custom' directory)
- stb header-only libraries - https://github.com/nothings/stb
- tsoding's string view implementation - https://github.com/tsoding/sv
I modified tsoding's string view so that it doesn't use the stdlib by implementing the couple
functions it uses
LICENCES:
tsoding string view implementation:
Copyright 2021 Alexey Kutepov <reximkut@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License to viclib.h:
Copyright (c) 2024 Víctor López
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef VICLIB_H
#define VICLIB_H
#if defined(_WIN32)
# define OS_WINDOWS 1
#endif
#if defined(__gnu_linux__)
# define OS_LINUX 1
#endif
#if defined(__APPLE__) && defined(__MACH__)
# define OS_MAC 1
#endif
#if defined(_MSC_VER) && !defined(__clang__)
# define COMPILER_CL 1
# define PRAGMA(x) __pragma(x)
# define thread_local __declspec(thread)
#elif defined(__clang__)
# define COMPILER_CLANG 1
# define PRAGMA(x) _Pragma(#x)
# define thread_local __thread
#elif defined(__GNUC__) || defined(__GNUG__)
# define COMPILER_GCC 1
# define PRAGMA(x) _Pragma(#x)
# define thread_local __thread
#elif defined(__TINYC__)
# define COMPILER_TCC 1
# define PRAGMA(x) _Pragma(#x)
// NOTE: tcc doesn't support thread-local storage
// TODO: thread local storage using win32/unistd?
// using VL_Init() to start it up?
# define thread_local
#else
/* unsupported compiler, to support, define:
necessary:
- thread_local
useful:
- PUSH_IGNORE_UNINITIALIZED
- RESTORE_WARNINGS
*/
# define thread_local
#endif
#if defined(__x86_64__) || defined(_M_AMD64)
# define ARCH_X64 1
#elif defined(__aarch64__) || defined(_M_ARM64)
# define ARCH_ARM64 1
#include <arm_neon.h>
#endif
#if !defined(__COLUMN__)
# define __COLUMN__ 0
#endif
#if COMPILER_CL || COMPILER_GCC || COMPILER_CLANG
/* gcc and clang define __FUNCTION__ as a string constant,
which means it cannot be concatenated to a string literal at compile time */
# define __PROC__ __FUNCTION__
#endif
#if defined(_UNISTD_H_) && defined(_SYS_STAT_H_)
# define VL_FILE_LINUX
#endif
#if !defined(VL_INC_STDLIB_H) && (defined(_STDLIB_H_) || defined(_STDLIB_H) || defined(_INC_STDLIB))
# define VL_INC_STDLIB_H
#endif
#if !defined(VL_INC_STDIO_H) && (defined(_STDIO_H_) || defined(_STDIO_H) || defined(_INC_STDIO))
# define VL_INC_STDIO_H
#endif
#if !defined(VL_INC_STRING_H) && (defined(_STRING_H_) || defined(_INC_STRING))
# define VL_INC_STRING_H
#endif
#if !defined(VICLIB_NO_PLATFORM)
#if OS_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if defined(_MSC_VER)
#include <intrin.h>
#endif
#elif OS_LINUX
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#elif OS_MAC // I think it works with the same includes as linux for now...?
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#else
#error Unsupported OS
#endif // OS
#endif // !defined(VICLIB_NO_PLATFORM)
/* DebugBreakpoint for different platforms.
Implementation by SDL3 (sdl wiki says SDL2 also had this but code says since SDL3.1.3) */
#if defined(SDL_h_)
# define DebugBreakpoint SDL_TriggerBreakpoint()
#elif defined(_MSC_VER)
/* Don't include intrin.h here because it contains C++ code */
extern void __cdecl __debugbreak(void);
# define DebugBreakpoint __debugbreak()
#elif defined(ANDROID)
# include <assert.h>
# define DebugBreakpoint assert(0)
#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
# define DebugBreakpoint __asm__ __volatile__ ( "int $3\n\t" )
#elif (defined(__GNUC__) || defined(__clang__)) && defined(__riscv)
# define DebugBreakpoint __asm__ __volatile__ ( "ebreak\n\t" )
#elif (defined(OS_MAC) && (defined(__arm64__) || defined(__aarch64__)) ) /* this might work on other ARM targets, but this is a known quantity... */
# define DebugBreakpoint __asm__ __volatile__ ( "brk #22\n\t" )
#elif defined(OS_MAC) && defined(__arm__)
# define DebugBreakpoint __asm__ __volatile__ ( "bkpt #22\n\t" )
#elif defined(_WIN32) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__arm64__) || defined(__aarch64__)) )
# define DebugBreakpoint __asm__ __volatile__ ( "brk #0xF000\n\t" )
#elif defined(__386__) && defined(__WATCOMC__)
# define DebugBreakpoint { _asm { int 0x03 } }
#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__)
# include <signal.h>
# define DebugBreakpoint raise(SIGTRAP)
#else
/* How do we trigger breakpoints on this platform? */
# define DebugBreakpoint Assert(false)
#endif
#if COMPILER_GCC || COMPILER_CLANG
// gcc and cl (haven't tried clang)
// don't understand how functions like ReadEntireFile work
// but I want to keep the warnings for other functions
# define PUSH_IGNORE_UNINITIALIZED PRAGMA(GCC diagnostic push) PRAGMA(GCC diagnostic ignored "-Wuninitialized")
# define RESTORE_WARNINGS PRAGMA(GCC diagnostic pop)
#elif COMPILER_CL
# define PUSH_IGNORE_UNINITIALIZED PRAGMA(warning(push)) PRAGMA(warning(disable: 4701)) PRAGMA(warning(disable: 4703))
# define RESTORE_WARNINGS PRAGMA(warning(pop))
#else
// compiler specific implementation
# define PUSH_IGNORE_UNINITIALIZED
# define RESTORE_WARNINGS
#endif
// only works with static arrays!
#define ArrayLen(arr) sizeof(arr)/sizeof(arr[0])
#if !defined(stringify)
# define stringify_(a) #a
# define stringify(a) stringify_(a)
#endif
#if !defined(glue)
# define glue_(a,b) a##b
# define glue(a,b) glue_(a,b)
#endif
#ifndef min
# define min(A, B) ((A) < (B) ? (A) : (B))
#endif
#ifndef max
# define max(A, B) ((A) > (B) ? (A) : (B))
#endif
#define VL_ReturnDefer(value) do { result = (value); goto defer; } while(0)
#if defined(__cplusplus)
# if __cplusplus >= 201703L
# define fallthrough [[fallthrough]]
# elif defined(__GNUC__) && __GNUC__ >= 7
# define fallthrough __attribute__((fallthrough))
# else
# define fallthrough /* fall through */
# endif
#else
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
# define fallthrough [[fallthrough]]
# elif defined(__GNUC__) && __GNUC__ >= 7
# define fallthrough __attribute__((fallthrough))
# else
# define fallthrough /* fall through */
# endif
#endif
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
typedef uint32_t b32;
typedef float f32;
typedef double f64;
// Any windows compiler
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
# define U64_Fmt "%llu"
# define S64_Fmt "%lld"
#else
# define U64_Fmt "%lu"
# define S64_Fmt "%ld"
#endif
// TODO: Print for different platforms...?
#if !defined(AssertAlways) || !defined(AssertMsgAlways)
# if defined(SDL_h_)
# define AssertAlways(e) do{ if(!(e)){ \
SDL_Log(__FILE__"("stringify(__LINE__)"): Assert fail: "#e "\n"); \
DebugBreakpoint; } }while(0)
# define AssertMsgAlways(e, msglit) do{ if(!(e)){ \
SDL_Log(__FILE__"("stringify(__LINE__)"): " msglit "\n"); \
DebugBreakpoint; } }while(0)
# elif defined(VL_INC_STDIO_H)
# define AssertAlways(e) do{ if(!(e)){ \
printf(__FILE__"("stringify(__LINE__)"): Assert fail: "#e "\n"); \
fflush(stdout); DebugBreakpoint; } }while(0)
# define AssertMsgAlways(e, msglit) do{ if(!(e)){ \
printf(__FILE__"("stringify(__LINE__)"): " msglit "\n"); \
fflush(stdout); DebugBreakpoint; } }while(0)
# else
# if !defined(QUIET_ASSERT)
# define QUIET_ASSERT
# pragma message("Warning: Using quiet assert since stdio.h is not included")
# define AssertAlways(e) do{ if(!(e)) { DebugBreakpoint; } }while(0)
# define AssertMsgAlways(e, msg) AssertAlways(e)
# endif
# endif
#endif // !defined(AssertAlways) || !defined(AssertMsgAlways)
#if RELEASE_MODE
# define Assert(expr)
# define AssertMsg(expr, msg)
#else
# define Assert(expr) AssertAlways(expr)
# define AssertMsg(expr, msg) AssertMsgAlways(expr, msg)
#endif
typedef enum {
ERROR_NO_ERROR = 0,
ERROR_READ_UNKNOWN,
ERROR_WRITE_UNKNOWN,
ERROR_READ_FILE_NOT_FOUND,
ERROR_WRITE_PATH_NOT_FOUND,
ERROR_FILE_ACCESS_DENIED,
ERROR_NO_MEM,
ERROR_READ_FILE_TOO_BIG, /* READ_ENTIRE_FILE_MAX exceeded */
} error_number_value;
thread_local error_number_value VL_ErrorNumber = 0;
#ifndef VLIBPROC
# define VLIBPROC
#endif
/* bool found = false;
* LinearSearch(string_view_array, string_view, view_Eq);
* if(found) {...}
*
* string_view_array must have count and items attributes
*/
#define LinearSearch(arr, item, equal) \
for(size_t glue(i, glue(_, __LINE__)) = 0; \
glue(i, glue(_, __LINE__)) < (arr)->count; \
glue(i, glue(_, __LINE__))++) { \
if(equal((item), (arr)->items[glue(i, glue(_, __LINE__))])) { found = true; break; } \
}
////////////////////////////////
// intrinsics
////////////////////////////////
/* Returns the number of leading 0-bits in val, starting at the most significant bit position
* If val is 0, the result is undefined
*/
static inline uint32_t CountLeadingZerosU32(uint32_t val);
/* Returns the number of leading 0-bits in val, starting at the most significant bit position
* If val is 0, the result is undefined
*/
static inline uint32_t CountLeadingZerosU64(uint64_t val);
/* Returns the number of leading 0-bits in val, starting at the least significant bit position
* If val is 0, the result is undefined
*/
static inline uint32_t CountTrailingZerosU32(uint32_t val);
/* Returns the number of leading 0-bits in val, starting at the least significant bit position
* If val is 0, the result is undefined
*/
static inline uint32_t CountTrailingZerosU64(uint64_t val);
/* Returns the number of leading 0-bits in val, starting at the most significant bit position
* If val is 0, returns 32
*/
static inline uint32_t CountLeadingZerosSafeU32(uint32_t val);
/* Returns the number of leading 0-bits in val, starting at the most significant bit position
* If val is 0, returns 64
*/
static inline uint32_t CountLeadingZerosSafeU64(uint64_t val);
/* Returns the number of leading 0-bits in val, starting at the least significant bit position
* If val is 0, returns 32
*/
static inline uint32_t CountTrailingZerosSafeU32(uint32_t val);
/* Returns the number of leading 0-bits in val, starting at the least significant bit position
* If val is 0, returns 64
*/
static inline uint32_t CountTrailingZerosSafeU64(uint64_t val);
#if defined(VL_INC_STRING_H)
# define mem_copy_non_overlapping(dst, src, len) memcpy(dst, src, len)
# define mem_copy(dst, src, len) memmove(dst, src, len)
# define mem_zero(data, len) memset(data, 0, len)
# define mem_compare(str1, str2, count) memcmp(str1, str2, count)
#elif defined(SDL_h_)
# define mem_copy_non_overlapping(dst, src, len) SDL_memcpy(dst, src, len)
# define mem_copy(dst, src, len) SDL_memmove(dst, src, len)
# define mem_zero(data, len) SDL_memset(data, 0, len)
# define mem_compare(str1, str2, count) SDL_memcmp(str1, str2, count)
#else
VLIBPROC void mem_copy_non_overlapping(void *dst, const void *src, size_t len);
VLIBPROC void mem_copy(void *dst, const void *src, size_t len);
VLIBPROC void mem_zero(void *data, size_t len);
VLIBPROC int mem_compare(const void *str1, const void *str2, size_t count);
#endif
#define ZeroStruct(S) mem_zero(&(S), sizeof(S))
////////////////////////////////
typedef struct {
const char *items;
size_t count;
} view;
#define VIEW(cstr_lit) ViewFromParts((cstr_lit), sizeof(cstr_lit) - 1)
#if defined(__cplusplus)
#define VIEW_STATIC(cstr_lit) {(const char*)(cstr_lit), sizeof(cstr_lit) - 1}
#else
#define VIEW_STATIC(cstr_lit) (view){(const char*)(cstr_lit), sizeof(cstr_lit) - 1}
#endif
#define VIEW_FMT "%.*s"
#define VIEW_ARG(v) (int)(v).count, (v).items
#ifndef VIEWPROC
# define VIEWPROC VLIBPROC
#endif
#ifndef VL_INC_STRING_H
size_t strlen(const char *s);
#endif // VL_INC_STRING_H
int is_space(int _c); // only checks ascii space characters
VIEWPROC view ViewFromParts(const char *data, size_t count);
VIEWPROC view ViewFromCstr(const char *cstr);
VIEWPROC view ViewSlice(view v, size_t start, size_t end); // won't include end -> [start, end)
VIEWPROC int ViewCompare(view a, view b); // result = A - B
VIEWPROC bool ViewEq(view a, view b);
VIEWPROC bool ViewStartsWith(view v, view start);
// Chops start from v when it gets found
VIEWPROC bool ViewChopStartsWith(view *v, view start);
VIEWPROC const char *ViewFind(view haystack, view needle); // result = pointer to where the needle is in haystack or null
// If the needle gets found, chop the haystack until the first ocurrence of needle in haystack
VIEWPROC bool ViewFindChop(view *haystack, view needle, view *chopped);
VIEWPROC bool ViewFindCharacter(view v, char c, size_t *n);
VIEWPROC bool ViewFindChopCharacter(view *v, char c, view *chopped);
#define ViewEndWith ViewEndsWith /* in case of singular/plural annoyance */
VIEWPROC bool ViewEndsWith(view v, view end);
VIEWPROC view ViewChopByDelim(view *v, char delim);
VIEWPROC view ViewChopByLine(view *v); // '\n' or "\r\n"
VIEWPROC view ViewChopByAnyDelim(view *v, view delims, char *delimiter); // checks for any character in Delims, stores found delimiter in Delimiter
VIEWPROC view ViewChopByView(view *v, view delim); // full view is the delim
VIEWPROC view ViewChopLeft(view *v, size_t n);
VIEWPROC view ViewChopRight(view *v, size_t n);
VIEWPROC view ViewTrimLeft(view v);
VIEWPROC view ViewTrimRight(view v);
VIEWPROC view ViewTrim(view v);
#define ViewIterateLines(src, idxName, lineName) \
view lineName = ViewChopByLine(src); \
for(size_t idxName = 0; (src)->count > 0 || lineName.count > 0; lineName = ViewChopByLine(src), idxName++)
#define ViewIterateSpaces(src, idxName, wordName) \
view wordName = ViewChopByAnyDelim((src), VIEW_STATIC(" \n\t\v\f\r"), 0); \
for(size_t idxName = 0; (src)->count > 0 || wordName.count > 0; wordName = ViewChopByAnyDelim((src), VIEW_STATIC(" \n\t\v\f\r"), 0), idxName++) \
if(word.count > 0)
#define ViewIterateDelimiters(src, delims, idxName, tokName, delimName) \
char delimName; \
view tokName = ViewChopByAnyDelim((src), delims, &delimName); \
for(size_t idxName = 0; (src)->count > 0 || tokName.count > 0 || delimName != '\0'; \
tokName = ViewChopByAnyDelim((src), delims, &delimName), idxName++)
#define PARSE_FAIL 0
#define PARSE_NO_DECIMALS 1 // for when you might want integer precision
#define PARSE_OK 2
VIEWPROC bool ViewParseS64(view v, s64 *result, view *remaining);
// TODO: Better exp parsing
VIEWPROC int ViewParseF64(view v, f64 *result, view *remaining);
typedef struct {
view file;
s32 line;
s32 column;
view proc;
} code_location;
#define CURR_LOC \
(code_location){VIEW_STATIC(__FILE__), __LINE__, __COLUMN__, VIEW_STATIC(__PROC__)}
// odin style, unix style would be :%d:%d
// prefer LOC_STR to fmt + arg if possible
#define LOC_UNIX_STR __FILE__":" stringify(__LINE__)":" stringify(__COLUMN__)
#define LOC_MSVC_STR __FILE__"(" stringify(__LINE__)")"
#define LOC_STR __FILE__"(" stringify(__LINE__)":" stringify(__COLUMN__)")"
#define LOC_FMT VIEW_FMT"(%d:%d)"
#define LOC_ARG(loc) VIEW_ARG((loc).file), (loc).line, (loc.column)
////////////////////////////////
typedef struct {
size_t size;
u8 *base;
size_t used;
s32 scratchCount;
s32 splitCount;
} memory_arena;
typedef struct {
memory_arena *Arena;
size_t startMemOffset;
} scratch_arena;
#ifndef ARENAPROC
# define ARENAPROC VLIBPROC
#endif
struct ArenaGetRemaining_opts {
memory_arena *Arena;
size_t Alignment;
};
struct ArenaPushSize_opts {
memory_arena *Arena;
size_t RequestSize;
size_t Alignment;
};
struct ArenaSplit_opts {
memory_arena *Arena;
memory_arena *SplitArena;
size_t SplitSize;
};
// NOTE: Thanks Vjekoslav for the idea! (https://twitter.com/vkrajacic/status/1749816169736073295)
#define ArenaGetRemaining(arena, ...) ArenaGetRemaining_Opt((struct ArenaGetRemaining_opts){.Arena = (arena), __VA_ARGS__})
#define ArenaPushSize(arena, size, ...) ArenaPushSize_Opt((struct ArenaPushSize_opts){.Arena = (arena), .RequestSize = (size), __VA_ARGS__})
#define PushStruct(arena, type, ...) ArenaPushSize_Opt((struct ArenaPushSize_opts){.Arena = (arena), .RequestSize = sizeof(type), __VA_ARGS__})
#define PushArray(arena, count, type, ...) ArenaPushSize_Opt((struct ArenaPushSize_opts){.Arena = (arena), .RequestSize = (count)*sizeof(type), __VA_ARGS__})
#define ArenaClear(arena, ZeroMem) do{ \
if(ZeroMem) { mem_zero((arena)->base, (arena)->size); } \
(arena)->used = 0; \
} while(0)
ARENAPROC char *Arena_strndup(memory_arena *Arena, const char *s, size_t n);
// s MUST be null terminated
ARENAPROC char *Arena_strdup(memory_arena *Arena, const char *s);
/* Split arenas work like a stack, you must rejoin them as first in last out.
* When you call ArenaSplit, it will remove the size requested from the original at (Base + Size - SplitSize)
* Calling ArenaSplit without SplitSize will split the arena into two equal parts (*they could be different sizes due to alignment)
**/
#define ArenaSplit(arena, split, ...) ArenaSplit_Opt((struct ArenaSplit_opts){.Arena = (arena), .SplitArena = (split), __VA_ARGS__})
// Split an arena into multiple equal parts
#define ArenaSplitMultiple(arena, split, ...) ArenaSplitMultiple_Impl((arena), \
(memory_arena*[]){(split), __VA_ARGS__}, sizeof((memory_arena*[]){(split), __VA_ARGS__})/sizeof(memory_arena*))
#define ArenaRejoinMultiple(arena, split, ...) ArenaRejoinMultiple_Impl((arena), \
(memory_arena*[]){(split), __VA_ARGS__}, sizeof((memory_arena*[]){(split), __VA_ARGS__})/sizeof(memory_arena*))
ARENAPROC void ArenaInit(memory_arena *Arena, size_t Size, void *Base);
ARENAPROC scratch_arena ArenaBeginScratch(memory_arena *Arena);
ARENAPROC void ArenaEndScratch(scratch_arena Scratch, bool ZeroMem);
ARENAPROC size_t ArenaGetAlignmentOffset(memory_arena *Arena, size_t Alignment);
ARENAPROC size_t ArenaGetRemaining_Opt(struct ArenaGetRemaining_opts opt);
ARENAPROC void *ArenaPushSize_Opt(struct ArenaPushSize_opts opt);
ARENAPROC void ArenaSplit_Opt(struct ArenaSplit_opts opt);
ARENAPROC void ArenaRejoin(memory_arena *Arena, memory_arena *SplitArena);
ARENAPROC void ArenaSplitMultiple_Impl(memory_arena *Arena, memory_arena **SplitArenas, size_t SplitArenaCount);
ARENAPROC void ArenaRejoinMultiple_Impl(memory_arena *Arena, memory_arena **SplitArenas, size_t SplitArenaCount);
#ifndef VICLIB_NO_TEMP_ARENA
# define temp_reset() ArenaClear(&ArenaTemp, true)
// will align to 4 bytes
# define temp_alloc(size, ...) ArenaPushSize_Opt((struct ArenaPushSize_opts){.Arena = &ArenaTemp, .RequestSize = (size), __VA_ARGS__})
# define temp_strdup(s) Arena_strdup(&ArenaTemp, s)
# define temp_strndup(s, n) Arena_strndup(&ArenaTemp, s, n)
# define temp_save() ArenaTemp.used
# define temp_rewind(checkpoint) ArenaTemp.used = checkpoint;
#endif
////////////////////////////////
#ifdef RADDBG_MARKUP_H
#if COMPILER_CL
raddbg_type_view(view, array($.items, $.count));
#if defined(SDL_h_)
raddbg_type_view(SDL_Surface, $.format == SDL_PixelFormat.SDL_PIXELFORMAT_RGBA32 ?
bitmap($.pixels, $.w, $.h, RGBA32) : $);
#endif
#endif // COMPILER_CL
#endif // RADDBG_MARKUP_H
////////////////////////////////
struct vl_globalcontext {
bool initted; // called VL_Init()
s64 initTime;
#if !defined(VICLIB_NO_PLATFORM)
#if OS_WINDOWS
LARGE_INTEGER performanceFrequency;
#else
#endif
#endif // !defined(VICLIB_NO_PLATFORM)
};
extern struct vl_globalcontext VL_globalContext;
VLIBPROC bool VL_Init(void);
#define VL_HadError() (VL_ErrorNumber != ERROR_NO_ERROR)
#if !defined(VICLIB_NO_PLATFORM)
#ifndef READ_ENTIRE_FILE_MAX
#define READ_ENTIRE_FILE_MAX 0xFFFFFFFF
#endif
VLIBPROC bool VL_SetCurrentDir(const char *path);
VLIBPROC bool VL_FileExists(const char *path);
#if !OS_WINDOWS
bool IsDebuggerPresent(void);
#endif
typedef enum {
VL_FILE_INVALID = -1,
VL_FILE_REGULAR = 0,
VL_FILE_DIRECTORY,
VL_FILE_SYMLINK,
VL_FILE_OTHER,
} file_type;
VLIBPROC bool GetLastWriteTime(const char *file, u64 *WriteTime);
VLIBPROC file_type VL_GetFileType(const char *path);
#define VL_NANOS_PER_SEC 1000000000
// Gets nanoseconds since the time VL_Init() was called,
// if it wasn't called, it will get nanoseconds since unspecified epoch
VLIBPROC u64 VL_GetNanos(void);
#if !defined(VICLIB_NO_FILE_IO)
typedef struct {
#if OS_WINDOWS
HANDLE File;
#elif OS_LINUX || OS_MAC
int fd;
bool didFirstIteration; // Need because fd could be 0 (stdin)
#endif
u32 BufferSize;
u8 *Buffer;
size_t RemainingFileSize;
} vl_file_chunk;
VLIBPROC bool ReadFileChunk(vl_file_chunk *Chunk, const char *File, u32 *ChunkSize);
VLIBPROC char *ReadEntireFile(memory_arena *Arena, char *File, size_t *Size);
VLIBPROC bool WriteEntireFile(const char *File, const void *Data, size_t Size);
#endif // !defined(VICLIB_NO_FILE_IO)
VLIBPROC const char *VL_GetError(void);
#endif // !defined(VICLIB_NO_PLATFORM)
// TODO(vic): I think the sort doesn't work 100% of the time? test this
#if !defined(VICLIB_NO_SORT)
bool int_less_than(const void *A, const void *B);
#define VL_Swap(A,B) temp = (A); (A) = (B); (B) = temp
#define VL_SwapType(A,B,T) VL_SwapSize(&(A), &(B), sizeof(T))
void VL_SwapSize(void *A, void *B, size_t Size);
// introsort
void Sort(void *Data, size_t Count, size_t ElementSize, bool (*less_than)(const void *, const void *));
void VL_IntroSort(void *Data, size_t lo, size_t hi, int Depth, size_t ElementSize, bool (*less_than)(const void *, const void *));
void VL_InsertionSort(void *Data, size_t Count, size_t ElementSize, bool (*less_than)(const void *, const void *));
void VL_HeapSort(void *Data, size_t Count, size_t ElementSize, bool (*less_than)(const void *, const void *));
#endif // !defined(VICLIB_NO_SORT)
#ifdef VICLIB_IMPLEMENTATION
int is_space(int _c)
{
char c = (char)_c;
return(c == ' ' || c == '\n' || c == '\t' ||
c == '\v' || c == '\f' || c == '\r');
}
#ifndef strlen
size_t strlen(const char *s)
{
size_t n = 0;
for(; *s != 0; s++) n++;
return n;
}
#endif // strlen
VIEWPROC view ViewFromParts(const char *data, size_t count)
{
view v;
v.items = data;
v.count = count;
return v;
}
VIEWPROC view ViewFromCstr(const char *cstr)
{
view v;
v.items = cstr;
v.count = strlen(cstr);
return v;
}
VIEWPROC view ViewSlice(view a, size_t start, size_t end)
{
AssertMsg(start <= end, "start must be smaller or equal to end");
AssertMsg(end <= a.count, "end must be less or equal to the source view count");
return ViewFromParts(a.items + start, end - start);
}
VIEWPROC view ViewTrimLeft(view v)
{
size_t i = 0;
for(;i < v.count && is_space(v.items[i]);) i += 1;
return ViewFromParts((const char*)(v.items + i), v.count - i);
}
VIEWPROC view ViewTrimRight(view v)
{
size_t i = 0;
for(;i < v.count && is_space(v.items[v.count - 1 - i]);) i += 1;
return ViewFromParts((const char*)v.items, v.count - i);
}
VIEWPROC view ViewTrim(view v)
{
return ViewTrimRight(ViewTrimLeft(v));
}
VIEWPROC int ViewCompare(view a, view b)
{
char res = 0;
for(size_t i = 0; i < min(a.count, b.count); i++)
{
res = a.items[i] - b.items[i];
if(res != 0) return res;
}
return (int)a.count - (int)b.count;
}
VIEWPROC bool ViewEq(view a, view b)
{
if(a.count != b.count) return false;
else return mem_compare(a.items, b.items, a.count) == 0;
}
VIEWPROC bool ViewStartsWith(view v, view start)
{
if(start.count > v.count) return false;
else return ViewEq(ViewFromParts(v.items, start.count), start);
}
VIEWPROC bool ViewChopStartsWith(view *v, view start)
{
bool found = ViewStartsWith(*v, start);
if(found) {
v->items += start.count;
v->count -= start.count;
}
return found;
}
VIEWPROC const char *ViewFind(view haystack, view needle)
{
if(needle.count == 0) return haystack.items;
if(needle.count > haystack.count) return (const char*)0;
else if(needle.count == haystack.count) {
return mem_compare(haystack.items, needle.items, haystack.count) == 0 ?
haystack.items : 0;
}
size_t i = 0;
for(; i < haystack.count && haystack.items[i] != needle.items[0]; i++);
if(i == haystack.count || needle.count == 1) return (const char*)0;
haystack.items += i;
haystack.count -= i;
if(haystack.count < needle.count) return (const char*)0;
// Stolen from the musl's implementation of memmem
switch(needle.count) {
case 2: {
// twobyte_memmem
uint16_t nw = needle.items[0] << 8 | needle.items[1];
uint16_t hw = haystack.items[0] << 8 | haystack.items[1];
for (haystack.items += 2, haystack.count -= 2; haystack.count; haystack.count--, hw = hw << 8 | *haystack.items++)
if(hw == nw) return (const char*)(haystack.items - 2);
return hw == nw ? (const char*)(haystack.items - 2) : (const char*)0;
} break;
case 3: {
// threebyte_memmem
uint32_t nw = (uint32_t)needle.items[0] << 24 | needle.items[1] << 16 | needle.items[2] << 8;
uint32_t hw = (uint32_t)haystack.items[0] << 24 | haystack.items[1] << 16 | haystack.items[2] << 8;
for (haystack.items += 3, haystack.count -= 3; haystack.count; haystack.count--, hw = (hw | *haystack.items++) << 8)
if (hw == nw) return (const char*)(haystack.items - 3);
return hw == nw ? (const char*)(haystack.items - 3) : (const char*)0;
} break;
case 4: {
// fourbyte_memmem
uint32_t nw = (uint32_t)needle.items[0] << 24 | needle.items[1] << 16 | needle.items[2] << 8 | needle.items[3];
uint32_t hw = (uint32_t)haystack.items[0] << 24 | haystack.items[1] << 16 | haystack.items[2] << 8 | haystack.items[3];
for (haystack.items += 4, haystack.count -= 4; haystack.count; haystack.count--, hw = hw << 8 | *haystack.items++)
if (hw == nw) return (const char*)(haystack.items - 4);
return hw == nw ? (const char*)(haystack.items - 4) : (const char*)0;
} break;
}
// twoway_memmem
// TODO
for(i = 0; i < haystack.count - needle.count; i++) {
if(mem_compare(haystack.items + i, needle.items, needle.count) == 0)
return (const char*)(haystack.items + i);
}
return (const char*)0;
}
VIEWPROC bool ViewFindChop(view *haystack, view needle, view *chopped)
{
const char *s = ViewFind(*haystack, needle);
if(s) {
size_t count = s - haystack->items;
if(chopped) {
chopped->items = haystack->items;
chopped->count = count;
}
haystack->items = s + needle.count;
haystack->count -= count + needle.count;
return true;
}
return false;
}
VIEWPROC bool ViewFindCharacter(view v, char c, size_t *n)
{
for(size_t i = 0; i < v.count; i++) {
if(v.items[i] == c) {
if(n) *n = i;
return true;
}
}
return false;
}
VIEWPROC bool ViewFindChopCharacter(view *v, char c, view *chopped)
{
size_t count;
bool found = ViewFindCharacter(*v, c, &count);
if(found) {
if(chopped) {
chopped->items = v->items;
chopped->count = count;
}
// skip the character
v->items = v->items + count + 1;
v->count -= count + 1;
}
return found;
}
VIEWPROC bool ViewEndsWith(view v, view end)
{
if(end.count > v.count) return false;
else return ViewEq(ViewFromParts(v.items + v.count - end.count, end.count), end);
}
VIEWPROC view ViewChopByDelim(view *v, char delim)
{
size_t i = 0;
for(;i < v->count && v->items[i] != delim;) i += 1;
view Result = ViewFromParts((const char*)v->items, i);
if(i < v->count) {
v->count -= i + 1;
v->items += i + 1;
}
else {
v->count -= i;
v->items += i;
}
return Result;
}
VIEWPROC view ViewChopByLine(view *v)
{
size_t moveLen = 1;
size_t i = 0;
for(;i < v->count && v->items[i] != '\n';) i += 1;
if(v->items[i-1] == '\r') {
moveLen = 2;
i--;
}
view Result = ViewFromParts((const char*)v->items, i);
if(i < v->count) {
v->count -= i + moveLen;
v->items += i + moveLen;
}
else {
v->count -= i;
v->items += i;
}
return Result;
}
VIEWPROC view ViewChopByAnyDelim(view *v, view delims, char *delimiter)
{
view Result;
if(delimiter) *delimiter = 0;
size_t i = 0;
for(; i < v->count; i++) {
for(size_t j = 0; j < delims.count; j++)
if(delims.items[j] == v->items[i]) {
if(delimiter) *delimiter = v->items[i];
goto done;
}
}
done:
Result = ViewFromParts((const char*)v->items, i);
if(i < v->count) {
v->count -= i + 1;
v->items += i + 1;
}
else {
v->count -= i;
v->items += i;
}
return Result;
}
VIEWPROC view ViewChopByView(view *v, view delim)
{
view Window = ViewFromParts((const char*)v->items, delim.count);
size_t i = 0;
for(; i + delim.count < v->count && !ViewEq(Window, delim);) {
i++;
Window.items++;
}
view Result = ViewFromParts((const char*)v->items, i);
if(i + delim.count == v->count) {
// include last <delim.count> characters if they aren't
// equal to delim
Result.count += delim.count;
}
v->items += i + delim.count;
v->count -= i + delim.count;
return Result;
}
VIEWPROC view ViewChopLeft(view *v, size_t n)
{
if(n > v->count) n = v->count;
view Result = ViewFromParts((const char*)v->items, n);
v->items += n;
v->count -= n;
return Result;
}
VIEWPROC view ViewChopRight(view *v, size_t n)
{
if(n > v->count) n = v->count;
view Result = ViewFromParts((const char*)(v->items + v->count - n), n);
v->count -= n;
return Result;
}
int _digit_val(int c)
{
int v = 16;
if(c >= '0' && c <= '9') {
v = c - '0';
}
else if(c >= 'a' && c <= 'z') {
v = c - 'a' + 10;
}
else if(c >= 'A' && c <= 'Z') {
v = c - 'A' + 10;