forked from mackron/dr_libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdr.h
4688 lines (3687 loc) · 125 KB
/
dr.h
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
// Public Domain. See "unlicense" statement at the end of this file.
// USAGE
//
// This is a single-file library. To use it, do something like the following in one .c file.
// #define DR_IMPLEMENTATION
// #include "dr.h"
//
// You can then #include dr.h in other parts of the program as you would with any other header file.
//
//
//
// OPTIONS
//
// #define DR_UTIL_WIN32_USE_CRITICAL_SECTION_MUTEX
// - Use the Win32 CRITICAL_SECTION API for mutex objects.
#ifndef dr_util_h
#define dr_util_h
#ifdef __cplusplus
extern "C" {
#endif
// Disable MSVC compatibility if we're compiling with it.
#if defined(_MSC_VER)
#define DR_NO_MSVC_COMPAT
#endif
#if defined(_MSC_VER)
#define DR_INLINE static __inline
#else
#define DR_INLINE static inline
#endif
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <stdio.h>
#ifndef DR_NO_MSVC_COMPAT
#include <errno.h>
#endif
#ifndef DR_SIZED_TYPES_DEFINED
#define DR_SIZED_TYPES_DEFINED
#if defined(_MSC_VER) && _MSC_VER < 1600
typedef signed char dr_int8;
typedef unsigned char dr_uint8;
typedef signed short dr_int16;
typedef unsigned short dr_uint16;
typedef signed int dr_int32;
typedef unsigned int dr_uint32;
typedef signed __int64 dr_int64;
typedef unsigned __int64 dr_uint64;
#else
#include <stdint.h>
typedef int8_t dr_int8;
typedef uint8_t dr_uint8;
typedef int16_t dr_int16;
typedef uint16_t dr_uint16;
typedef int32_t dr_int32;
typedef uint32_t dr_uint32;
typedef int64_t dr_int64;
typedef uint64_t dr_uint64;
#endif
typedef dr_int8 dr_bool8;
typedef dr_int32 dr_bool32;
#define DR_TRUE 1
#define DR_FALSE 0
#endif
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
/////////////////////////////////////////////////////////
// Annotations
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
#ifndef UNUSED
#define UNUSED(x) ((void)(x))
#endif
/////////////////////////////////////////////////////////
// min/max/clamp
#ifndef dr_min
#define dr_min(x, y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef dr_max
#define dr_max(x, y) (((x) > (y)) ? (x) : (y))
#endif
#ifndef dr_clamp
#define dr_clamp(x, low, high) (dr_max(low, dr_min(x, high)))
#endif
#ifndef dr_round_up
#define dr_round_up(x, multiple) ((((x) + ((multiple) - 1)) / (multiple)) * (multiple))
#endif
#ifndef dr_round_up_signed
#define dr_round_up_signed(x, multiple) ((((x) + (((x) >= 0)*((multiple) - 1))) / (multiple)) * (multiple))
#endif
/////////////////////////////////////////////////////////
// MSVC Compatibility
// A basic implementation of MSVC's strcpy_s().
int dr_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src);
// A basic implementation of MSVC's strncpy_s().
int dr_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count);
// A basic implementation of MSVC's strcat_s().
int dr_strcat_s(char* dst, size_t dstSizeInBytes, const char* src);
// A basic implementation of MSVC's strncat_s()
int dr_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count);
// A basic implementation of MSVC's _atoi_s()
int dr_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix);
#ifndef DR_NO_MSVC_COMPAT
#ifndef _TRUNCATE
#define _TRUNCATE ((size_t)-1)
#endif
DR_INLINE int strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
{
return dr_strcpy_s(dst, dstSizeInBytes, src);
}
DR_INLINE int strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
return dr_strncpy_s(dst, dstSizeInBytes, src, count);
}
DR_INLINE int strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
{
return dr_strcat_s(dst, dstSizeInBytes, src);
}
DR_INLINE int strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
return dr_strncat_s(dst, dstSizeInBytes, src, count);
}
#ifndef __MINGW32__
DR_INLINE int _stricmp(const char* string1, const char* string2)
{
return strcasecmp(string1, string2);
}
#endif
DR_INLINE int _itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
{
return dr_itoa_s(value, dst, dstSizeInBytes, radix);
}
#endif
/////////////////////////////////////////////////////////
// String Helpers
// Determines if the given character is whitespace.
dr_bool32 dr_is_whitespace(uint32_t utf32);
/// Removes every occurance of the given character from the given string.
void dr_strrmchar(char* str, char c);
/// Finds the first non-whitespace character in the given string.
const char* dr_first_non_whitespace(const char* str);
static inline const char* dr_ltrim(const char* str) { return dr_first_non_whitespace(str); }
static const char* dr_rtrim(const char* str);
/// Trims both the leading and trailing whitespace from the given string.
void dr_trim(char* str);
/// Finds the first occurance of a whitespace character in the given string.
const char* dr_first_whitespace(const char* str);
/// Finds the beginning of the next line.
const char* dr_next_line(const char* str);
/// Makes a copy of the first line of the given string.
size_t dr_copy_line(const char* str, char* lineOut, size_t lineOutSize);
// A slow string replace function. Free the returned string with free().
char* dr_string_replace(const char* src, const char* query, const char* replacement);
/////////////////////////////////////////////////////////
// Unicode Utilities
/// Converts a UTF-32 character to UTF-16.
///
/// @param utf16 [in] A pointer to an array of at least two 16-bit values that will receive the UTF-16 character.
///
/// @return 2 if the returned character is a surrogate pair, 1 if it's a simple UTF-16 code point, or 0 if it's an invalid character.
///
/// @remarks
/// It is assumed the <utf16> is large enough to hold at least 2 unsigned shorts. <utf16> will be padded with 0 for unused
/// components.
DR_INLINE int dr_utf32_to_utf16_ch(unsigned int utf32, unsigned short utf16[2])
{
if (utf16 == NULL) {
return 0;
}
if (utf32 < 0xD800 || (utf32 >= 0xE000 && utf32 <= 0xFFFF))
{
utf16[0] = (unsigned short)utf32;
utf16[1] = 0;
return 1;
}
else
{
if (utf32 >= 0x10000 && utf32 <= 0x10FFFF)
{
utf16[0] = (unsigned short)(0xD7C0 + (unsigned short)(utf32 >> 10));
utf16[1] = (unsigned short)(0xDC00 + (unsigned short)(utf32 & 0x3FF));
return 2;
}
else
{
// Invalid.
utf16[0] = 0;
utf16[1] = 0;
return 0;
}
}
}
/// Converts a UTF-16 character to UTF-32.
DR_INLINE unsigned int dr_utf16_to_utf32_ch(unsigned short utf16[2])
{
if (utf16 == NULL) {
return 0;
}
if (utf16[0] < 0xD800 || utf16[0] > 0xDFFF)
{
return utf16[0];
}
else
{
if ((utf16[0] & 0xFC00) == 0xD800 && (utf16[1] & 0xFC00) == 0xDC00)
{
return ((unsigned int)utf16[0] << 10) + utf16[1] - 0x35FDC00;
}
else
{
// Invalid.
return 0;
}
}
}
/// Converts a UTF-16 surrogate pair to UTF-32.
DR_INLINE unsigned int dr_utf16pair_to_utf32_ch(unsigned short utf160, unsigned short utf161)
{
unsigned short utf16[2];
utf16[0] = utf160;
utf16[1] = utf161;
return dr_utf16_to_utf32_ch(utf16);
}
/////////////////////////////////////////////////////////
// Aligned Allocations
#ifndef DRUTIL_NO_ALIGNED_MALLOC
DR_INLINE void* dr_aligned_malloc(size_t alignment, size_t size)
{
#if defined(_WIN32) || defined(_WIN64)
return _aligned_malloc(size, alignment);
#else
void* pResult;
if (posix_memalign(&pResult, alignment, size) == 0) {
return pResult;
}
return 0;
#endif
}
DR_INLINE void dr_aligned_free(void* ptr)
{
#if defined(_WIN32) || defined(_WIN64)
_aligned_free(ptr);
#else
free(ptr);
#endif
}
#endif // !DRUTIL_NO_ALIGNED_MALLOC
/////////////////////////////////////////////////////////
// Key/Value Pair Parsing
typedef size_t (* dr_key_value_read_proc) (void* pUserData, void* pDataOut, size_t bytesToRead);
typedef void (* dr_key_value_pair_proc) (void* pUserData, const char* key, const char* value);
typedef void (* dr_key_value_error_proc)(void* pUserData, const char* message, unsigned int line);
/// Parses a series of simple Key/Value pairs.
///
/// @remarks
/// This function is suitable for parsing simple key/value config files.
/// @par
/// This function will never allocate memory on the heap. Because of this there is a minor restriction in the length of an individual
/// key/value pair which is 4KB.
/// @par
/// Formatting rules are as follows:
/// - The basic syntax for a key/value pair is [key][whitespace][value]. Example: MyProperty 1234
/// - All key/value pairs must be declared on a single line, and a single line cannot contain more than a single key/value pair.
/// - Comments begin with the '#' character and continue until the end of the line.
/// - A key cannot contain spaces but are permitted in values.
/// - The value will have any leading and trailing whitespace trimmed.
/// @par
/// If an error occurs, that line will be skipped and processing will continue.
void dr_parse_key_value_pairs(dr_key_value_read_proc onRead, dr_key_value_pair_proc onPair, dr_key_value_error_proc onError, void* pUserData);
// This will only return DR_FALSE if the file fails to open. It will still return DR_TRUE even if there are syntax error or whatnot.
dr_bool32 dr_parse_key_value_pairs_from_file(const char* filePath, dr_key_value_pair_proc onPair, dr_key_value_error_proc onError, void* pUserData);
/////////////////////////////////////////////////////////
// Basic Tokenizer
/// Retrieves the first token in the given string.
///
/// @remarks
/// This function is suitable for doing a simple whitespace tokenization of a null-terminated string.
/// @par
/// The return value is a pointer to one character past the last character of the next token. You can use the return value to execute
/// this function in a loop to parse an entire string.
/// @par
/// <tokenOut> can be null. If the buffer is too small to contain the entire token it will be set to an empty string. The original
/// input string combined with the return value can be used to reliably find the token.
/// @par
/// This will handle double-quoted strings, so a string such as "My \"Complex String\"" contains two tokens: "My" and "\"Complex String\"".
/// @par
/// This function has no dependencies.
const char* dr_next_token(const char* tokens, char* tokenOut, size_t tokenOutSize);
/////////////////////////////////////////////////////////
// Known Folders
/// Retrieves the path of the executable.
///
/// @remarks
/// Currently only works on Windows and Linux. Other platforms will be added as they're needed.
dr_bool32 dr_get_executable_path(char* pathOut, size_t pathOutSize);
/// Retrieves the path of the directory containing the executable.
///
/// @remarks
/// Currently only works on Windows and Linux. Other platforms will be added as they're needed.
dr_bool32 dr_get_executable_directory_path(char* pathOut, size_t pathOutSize);
/// Retrieves the path of the user's config directory.
///
/// @remarks
/// On Windows this will typically be %APPDATA% and on Linux it will usually be ~/.config
dr_bool32 dr_get_config_folder_path(char* pathOut, size_t pathOutSize);
/// Retrieves the path of the user's log directory.
///
/// @remarks
/// On Windows this will typically be %APPDATA% and on Linux it will usually be var/log
dr_bool32 dr_get_log_folder_path(char* pathOut, size_t pathOutSize);
/// Retrieves the current directory.
const char* dr_get_current_directory(char* pathOut, size_t pathOutSize);
/// Sets the current directory.
dr_bool32 dr_set_current_directory(const char* path);
/////////////////////////////////////////////////////////
// Basic File Management
// Callback function for file iteration.
typedef dr_bool32 (* dr_iterate_files_proc)(const char* filePath, void* pUserData);
// Helper for opening a stdio FILE.
FILE* dr_fopen(const char* fileName, const char* openMode);
// Helper for creating an empty file.
dr_bool32 dr_create_empty_file(const char* fileName, dr_bool32 failIfExists);
// Retrieves the file data of the given file. Free the returned pointer with dr_free_file_data().
void* dr_open_and_read_file(const char* filePath, size_t* pFileSizeOut);
// Retrieves the file data of the given file as a null terminated string. Free the returned pointer with dr_free_file_data(). The
// returned file size is the length of the string not including the null terminator.
char* dr_open_and_read_text_file(const char* filePath, size_t* pFileSizeOut);
// Creates a new file with the given data.
dr_bool32 dr_open_and_write_file(const char* filePath, const void* pData, size_t dataSize);
// Creates a new file with the given string.
dr_bool32 dr_open_and_write_text_file(const char* filePath, const char* text);
// Frees the file data returned by dr_open_and_read_file().
void dr_free_file_data(void* valueReturnedByOpenAndReadFile);
// Determines whether or not the given file path is to a file.
//
// This will return DR_FALSE if the path points to a directory.
dr_bool32 dr_file_exists(const char* filePath);
// Determines whether or not the given file path points to a directory.
//
// This will return DR_FALSE if the path points to a file.
dr_bool32 dr_directory_exists(const char* directoryPath);
static inline dr_bool32 dr_is_directory(const char* directoryPath) { return dr_directory_exists(directoryPath); }
// Moves a file.
//
// This uses rename() on POSIX platforms and MoveFileEx(oldPath, newPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) on windows platforms.
dr_bool32 dr_move_file(const char* oldPath, const char* newPath);
// Copies a file.
dr_bool32 dr_copy_file(const char* srcPath, const char* dstPath, dr_bool32 failIfExists);
// Determines if the given file is read only.
dr_bool32 dr_is_file_read_only(const char* filePath);
// Retrieves the last modified time of the file at the given path.
uint64_t dr_get_file_modified_time(const char* filePath);
// Deletes the file at the given path.
//
// This uses remove() on POSIX platforms and DeleteFile() on Windows platforms.
dr_bool32 dr_delete_file(const char* filePath);
// Cross-platform wrapper for creating a directory.
dr_bool32 dr_mkdir(const char* directoryPath);
// Recursively creates a directory.
dr_bool32 dr_mkdir_recursive(const char* directoryPath);
// Iterates over every file and folder of the given directory.
dr_bool32 dr_iterate_files(const char* directory, dr_bool32 recursive, dr_iterate_files_proc proc, void* pUserData);
/////////////////////////////////////////////////////////
// DPI Awareness
#if defined(_WIN32)
/// Win32 Only: Makes the application DPI aware.
void dr_win32_make_dpi_aware();
/// Win32 Only: Retrieves the base DPI to use as a reference when calculating DPI scaling.
void dr_win32_get_base_dpi(int* pDPIXOut, int* pDPIYOut);
/// Win32 Only: Retrieves the system-wide DPI.
void dr_win32_get_system_dpi(int* pDPIXOut, int* pDPIYOut);
/// Win32 Only: Retrieves the actual DPI of the monitor at the given index.
///
/// @remarks
/// If per-monitor DPI is not supported, the system wide DPI settings will be used instead.
/// @par
/// This runs in linear time.
void dr_win32_get_monitor_dpi(int monitor, int* pDPIXOut, int* pDPIYOut);
/// Win32 Only: Retrieves the number of monitors active at the time of calling.
///
/// @remarks
/// This runs in linear time.
int dr_win32_get_monitor_count();
#endif
/////////////////////////////////////////////////////////
// Date / Time
/// Retrieves a time_t as of the time the function was called.
time_t dr_now();
/// Formats a data/time string.
void dr_datetime_short(time_t t, char* strOut, unsigned int strOutSize);
// Returns a date string in YYYYMMDD format.
void dr_date_YYYYMMDD(time_t t, char* strOut, unsigned int strOutSize);
/////////////////////////////////////////////////////////
// Command Line
//
// The command line functions below are just simple iteration functions. This command line system is good for
// simple command lines, but probably not the best for programs requiring complex command line work.
//
// For argv style command lines, parse_cmdline() will run without any heap allocations. With a Win32 style
// command line there will be one malloc() per call fo parse_cmdline(). This is the only function that will do
// a malloc().
//
// Below is an example:
//
// dr_cmdline cmdline;
// if (dr_init_cmdline(&cmdline, argc, argv)) {
// dr_parse_cmdline(&cmdline, my_cmdline_handler, pMyUserData);
// }
//
// void my_cmdline_handler(const char* key, const char* value, void* pUserData)
// {
// // Do something...
// }
//
//
// When parsing the command line, the first iteration will be the program path and the key will be "[path]".
//
// For segments such as "-abcd", the callback will be called for "a", "b", "c", "d" individually, with the
// value set to NULL.
//
// For segments such as "--server", the callback will be called for "server", with the value set to NULL.
//
// For segments such as "-f file.txt", the callback will be called with the key set to "f" and the value set
// to "file.txt".
//
// For segments such as "-f file1.txt file2.txt", the callback will be called twice, once for file1.txt and
// again for file2.txt, with with the key set to "f" in both cases.
//
// For segments where there is no leading key, the values will be posted as annonymous (key set to NULL). An example
// is "my_program.exe file1.txt file2.txt", in which case the first iteration will be the program path, the second iteration
// will be "file1.txt", with the key set to NULL. The third iteration will be "file2.txt" with the key set to NULL.
//
// For segments such as "-abcd file.txt", "a", "b", "c", "d" will be sent with NULL values, and "file.txt" will be
// posted with a NULL key.
typedef struct dr_cmdline dr_cmdline;
struct dr_cmdline
{
// argv style.
int argc;
char** argv;
// Win32 style
const char* win32;
};
typedef dr_bool32 dr_cmdline_parse_proc(const char* key, const char* value, void* pUserData);
/// Initializes a command line object.
dr_bool32 dr_init_cmdline(dr_cmdline* pCmdLine, int argc, char** argv);
/// Initializes a command line object using a Win32 style command line.
dr_bool32 dr_init_cmdline_win32(dr_cmdline* pCmdLine, const char* args);
/// Parses the given command line.
void dr_parse_cmdline(dr_cmdline* pCmdLine, dr_cmdline_parse_proc callback, void* pUserData);
/// Helper for determining whether or not the given key exists.
dr_bool32 dr_cmdline_key_exists(dr_cmdline* pCmdLine, const char* key);
// Convers the given command line object to argc/argv style.
//
// Returns the argument count. Returns 0 if an error occurs. Free "argvOut" with dr_free_argv().
int dr_cmdline_to_argv(dr_cmdline* pCmdLine, char*** argvOut);
// Converts a WinMain style command line to argc/argv.
//
// Returns the argument count. Returns 0 if an error occurs. Free "argvOut" with dr_free_argv().
int dr_winmain_to_argv(const char* cmdlineWinMain, char*** argvOut);
// Frees the argc/argv command line that was generated by dr.h
void dr_free_argv(char** argv);
/////////////////////////////////////////////////////////
// Threading
/// Puts the calling thread to sleep for approximately the given number of milliseconds.
///
/// @remarks
/// This is not 100% accurate and should be considered an approximation.
void dr_sleep(unsigned int milliseconds);
/// Retrieves the number of logical cores on system.
unsigned int dr_get_logical_processor_count();
/// Thread.
typedef void* dr_thread;
typedef int (* dr_thread_entry_proc)(void* pData);
/// Creates and begins executing a new thread.
///
/// @remarks
/// This will not return until the thread has entered into it's entry point.
/// @par
/// Creating a thread should be considered an expensive operation. For high performance, you should create threads
/// at load time and cache them.
dr_thread dr_create_thread(dr_thread_entry_proc entryProc, void* pData);
/// Deletes the given thread.
///
/// @remarks
/// This does not actually exit the thread, but rather deletes the memory that was allocated for the thread
/// object returned by dr_create_thread().
/// @par
/// It is usually best to wait for the thread to terminate naturally with dr_wait_thread() before calling
/// this function, however it is still safe to do something like the following.
/// @code
/// dr_delete_thread(dr_create_thread(my_thread_proc, pData))
/// @endcode
void dr_delete_thread(dr_thread thread);
/// Waits for the given thread to terminate.
void dr_wait_thread(dr_thread thread);
/// Helper function for waiting for a thread and then deleting the handle after it has terminated.
void dr_wait_and_delete_thread(dr_thread thread);
/// Mutex
typedef void* dr_mutex;
/// Creates a mutex object.
///
/// @remarks
/// If an error occurs, 0 is returned. Otherwise a handle the size of a pointer is returned.
dr_mutex dr_create_mutex();
/// Deletes a mutex object.
void dr_delete_mutex(dr_mutex mutex);
/// Locks the given mutex.
void dr_lock_mutex(dr_mutex mutex);
/// Unlocks the given mutex.
void dr_unlock_mutex(dr_mutex mutex);
/// Semaphore
typedef void* dr_semaphore;
/// Creates a semaphore object.
///
/// @remarks
/// If an error occurs, 0 is returned. Otherwise a handle the size of a pointer is returned.
dr_semaphore dr_create_semaphore(int initialValue);
/// Deletes the given semaphore.
void dr_delete_semaphore(dr_semaphore semaphore);
/// Waits on the given semaphore object and decrements it's counter by one upon returning.
dr_bool32 dr_wait_semaphore(dr_semaphore semaphore);
/// Releases the given semaphore and increments it's counter by one upon returning.
dr_bool32 dr_release_semaphore(dr_semaphore semaphore);
/////////////////////////////////////////////////////////
// Timing
typedef struct
{
int64_t counter;
} dr_timer;
// Initializes a high-resolution timer.
void dr_timer_init(dr_timer* pTimer);
// Ticks the timer and returns the number of seconds since the previous tick.
//
// The maximum return value is about 140 years or so.
double dr_timer_tick(dr_timer* pTimer);
/////////////////////////////////////////////////////////
// Random
// Generates a random double between 0 and 1. This is bassed of C standard rand().
double dr_randd();
// Generates a random float between 0 and 1. This is based off C standard rand().
float dr_randf();
/////////////////////////////////////////////////////////
// User Accounts and Process Management
// Retrieves the user name of the user running the application.
size_t dr_get_username(char* usernameOut, size_t usernameOutSize);
// Retrieves the ID of the current process.
unsigned int dr_get_process_id();
/////////////////////////////////////////////////////////
// Miscellaneous Stuff.
// Helper for clearing the given object to 0.
#define dr_zero_object(pObject) memset(pObject, 0, sizeof(*pObject));
// Converts an ASCII hex character to it's integral equivalent. Returns DR_FALSE if it's not a valid hex character.
dr_bool32 dr_hex_char_to_uint(char ascii, unsigned int* out);
/////////////////////////////////////////////////////////
// C++ Specific
#ifdef __cplusplus
// Use this to prevent objects of the given class or struct from being copied. This is also useful for eliminating some
// compiler warnings.
//
// Note for structs - this sets the access mode to private, so place this at the end of the declaration.
#define NO_COPY(classname) \
private: \
classname(const classname &); \
classname & operator=(const classname &);
#ifndef DR_NO_MSVC_COMPAT
extern "C++"
{
template <size_t dstSizeInBytes>
int strcpy_s(char (&dst)[dstSizeInBytes], const char* src)
{
return strcpy_s(dst, dstSizeInBytes, src);
}
template <size_t dstSizeInBytes>
int strncpy_s(char (&dst)[dstSizeInBytes], const char* src, size_t count)
{
return strncpy_s(dst, dstSizeInBytes, src, count);
}
template <size_t dstSizeInBytes>
int strcat_s(char (&dst)[dstSizeInBytes], const char* src)
{
return strcat_s(dst, dstSizeInBytes, src);
}
template <size_t dstSizeInBytes>
int strncat_s(char (&dst)[dstSizeInBytes], const char* src, size_t count)
{
return strncat_s(dst, dstSizeInBytes, src, count);
}
}
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif //dr_util_h
///////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION
//
///////////////////////////////////////////////////////////////////////////////
#ifdef DR_IMPLEMENTATION
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h> // For memmove()
#include <errno.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <pthread.h>
#include <fcntl.h>
#include <semaphore.h>
#include <dirent.h>
#endif
int dr_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
{
if (dst == 0) {
return EINVAL;
}
if (dstSizeInBytes == 0) {
return ERANGE;
}
if (src == 0) {
dst[0] = '\0';
return EINVAL;
}
size_t i;
for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
dst[i] = src[i];
}
if (i < dstSizeInBytes) {
dst[i] = '\0';
return 0;
}
dst[0] = '\0';
return ERANGE;
}
int dr_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
if (dst == 0) {
return EINVAL;
}
if (dstSizeInBytes == 0) {
return EINVAL;
}
if (src == 0) {
dst[0] = '\0';
return EINVAL;
}
size_t maxcount = count;
if (count == ((size_t)-1) || count >= dstSizeInBytes) { // -1 = _TRUNCATE
maxcount = dstSizeInBytes - 1;
}
size_t i;
for (i = 0; i < maxcount && src[i] != '\0'; ++i) {
dst[i] = src[i];
}
if (src[i] == '\0' || i == count || count == ((size_t)-1)) {
dst[i] = '\0';
return 0;
}
dst[0] = '\0';
return ERANGE;
}
int dr_strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
{
if (dst == 0) {
return EINVAL;
}
if (dstSizeInBytes == 0) {
return ERANGE;
}
if (src == 0) {
dst[0] = '\0';
return EINVAL;
}
char* dstorig = dst;
while (dstSizeInBytes > 0 && dst[0] != '\0') {
dst += 1;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes == 0) {
return EINVAL; // Unterminated.
}
while (dstSizeInBytes > 0 && src[0] != '\0') {
*dst++ = *src++;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes > 0) {
dst[0] = '\0';
} else {
dstorig[0] = '\0';
return ERANGE;
}
return 0;
}
int dr_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
if (dst == 0) {
return EINVAL;
}
if (dstSizeInBytes == 0) {
return ERANGE;
}
if (src == 0) {
return EINVAL;
}
char* dstorig = dst;
while (dstSizeInBytes > 0 && dst[0] != '\0') {
dst += 1;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes == 0) {
return EINVAL; // Unterminated.
}
if (count == ((size_t)-1)) { // _TRUNCATE
count = dstSizeInBytes - 1;
}
while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0)
{
*dst++ = *src++;
dstSizeInBytes -= 1;
count -= 1;
}
if (dstSizeInBytes > 0) {
dst[0] = '\0';
} else {
dstorig[0] = '\0';
return ERANGE;
}
return 0;
}
int dr_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
{
if (dst == NULL || dstSizeInBytes == 0) {
return EINVAL;
}
if (radix < 2 || radix > 36) {
dst[0] = '\0';
return EINVAL;
}
int sign = (value < 0 && radix == 10) ? -1 : 1; // The negative sign is only used when the base is 10.
unsigned int valueU;
if (value < 0) {
valueU = -value;
} else {
valueU = value;
}
char* dstEnd = dst;
do
{
int remainder = valueU % radix;
if (remainder > 9) {
*dstEnd = (char)((remainder - 10) + 'a');
} else {
*dstEnd = (char)(remainder + '0');
}
dstEnd += 1;
dstSizeInBytes -= 1;
valueU /= radix;
} while (dstSizeInBytes > 0 && valueU > 0);
if (dstSizeInBytes == 0) {