-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathds.h
2811 lines (2409 loc) · 81.4 KB
/
ds.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
// DOCUMENTATION
//
// DS.H
//
// This is a single-header library that provides a set of data structures and
// utilities for C programs. The library is designed to be simple and easy to
// use, and it is intended to be used in small to medium-sized projects.
//
// Options:
// - DS_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of all the data structures and utilities
// - DS_PQ_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the priority queue data structure
// - DS_SB_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the string builder utility
// - DS_SS_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the string slice utility
// - DS_DA_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the dynamic array data structure
// - DS_LL_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the linked list data structure
// - DS_HT_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the hash table data structure
// - DS_AL_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the allocator utility and set the allocator to use
// - DS_AP_IMPLEMENTATION: Define this macro in one source file to include the
// implementation of the ds_argument parser utility
// - DS_IO_IMPLEMENTATION: Define this macro for some io utils
//
// MEMORY MANAGEMENT
//
// The memory management macros are used to allocate, reallocate and free
// memory, and to exit the program. The DS_MALLOC macro is used to allocate
// memory, the DS_REALLOC macro is used to reallocate memory, the DS_FREE macro
// is used to free memory, and the DS_EXIT macro is used to exit the program.
//
// Options:
// - DS_NO_STDLIB: Disables the use of the standard library
//
// LOGGING
//
// The logging macros are used to print messages to the standard output and
// standard error streams. The DS_LOG_ERROR macro is used to print error
// messages, and the DS_LOG_INFO macro is used to print informational messages.
// The DS_PANIC macro is used to print an error message and exit the program.
//
// Options:
// - DS_NO_STDIO: Disables the use of the standard input/output streams
// - DS_LOG_LEVEL: Sets the logging level to one of the following values:
// - DS_LOG_LEVEL_DEBUG: Print debug, info, warn and error messages
// - DS_LOG_LEVEL_INFO: Print info, warn and error messages
// - DS_LOG_LEVEL_WARN: Print warn and error messages
// - DS_LOG_LEVEL_ERROR: Print error messages
// - DS_LOG_LEVEL_NONE: Print no messages
// The default logging level is DS_LOG_LEVEL_DEBUG
// - DS_NO_TERMINAL_COLORS: Disables the use of terminal colors in the log
// messages
#ifndef DS_H
#define DS_H
#include <stdarg.h>
#include <stdint.h>
// TODO: rework the hash table to actually work
#ifndef DSHDEF
#ifdef DSH_STATIC
#define DSHDEF static
#else
#define DSHDEF extern
#endif
#endif
// ALLOCATOR
//
// The allocator is a simple utility to allocate and free memory. You can define
// the allocator to use when allocating and freeing memory. This can be used in
// all the other data structures and utilities to use a custom allocator.
typedef struct ds_allocator
{
uint8_t *start;
uint8_t *prev;
uint8_t *top;
uint64_t size;
} ds_allocator;
DSHDEF void ds_allocator_init(ds_allocator *allocator, uint8_t *start,
uint64_t size);
DSHDEF void ds_allocator_dump(ds_allocator *allocator);
DSHDEF void *ds_allocator_alloc(ds_allocator *allocator, uint64_t size);
DSHDEF void ds_allocator_free(ds_allocator *allocator, void *ptr);
// DYNAMIC ARRAY
//
// The dynamic array is a simple array that grows as needed. This is the real
// implementation of dynamic arrays. The macros from the header file are just
// quick inline versions of these functions. This implementation is generic and
// can be used with any type of item, unlike the macros which require you to
// define the array structure with the items, count and capacity fields.
typedef struct ds_dynamic_array
{
struct ds_allocator *allocator;
void *items;
unsigned int item_size;
unsigned int count;
unsigned int capacity;
} ds_dynamic_array;
DSHDEF void ds_dynamic_array_init_allocator(ds_dynamic_array *da,
unsigned int item_size,
struct ds_allocator *allocator);
DSHDEF void ds_dynamic_array_init(ds_dynamic_array *da, unsigned int item_size);
DSHDEF int ds_dynamic_array_append(ds_dynamic_array *da, const void *item);
DSHDEF int ds_dynamic_array_pop(ds_dynamic_array *da, const void **item);
DSHDEF int ds_dynamic_array_append_many(ds_dynamic_array *da, void **new_items,
unsigned int new_items_count);
DSHDEF int ds_dynamic_array_get(ds_dynamic_array *da, unsigned int index,
void *item);
DSHDEF void ds_dynamic_array_get_ref(ds_dynamic_array *da, unsigned int index,
void **item);
DSHDEF int ds_dynamic_array_copy(ds_dynamic_array *da, ds_dynamic_array *copy);
DSHDEF void ds_dynamic_array_sort(ds_dynamic_array *da,
int (*compare)(const void *, const void *));
DSHDEF int ds_dynamic_array_reverse(ds_dynamic_array *da);
DSHDEF int ds_dynamic_array_swap(ds_dynamic_array *da, unsigned int index1,
unsigned int index2);
DSHDEF void ds_dynamic_array_free(ds_dynamic_array *da);
// PRIORITY QUEUE
//
// The priority queue is implemented as a heap, where you can define the
// comparison function to use when inserting items. The comparison function
// should return a positive value if the first item has higher priority than
// the second item, a negative value if the second item has higher priority than
// the first item, and 0 if the items have the same priority.
typedef struct ds_priority_queue
{
ds_dynamic_array items;
int (*compare)(const void *, const void *);
} ds_priority_queue;
DSHDEF void ds_priority_queue_init_allocator(
ds_priority_queue *pq, int (*compare)(const void *, const void *),
unsigned int item_size, struct ds_allocator *allocator);
DSHDEF void ds_priority_queue_init(ds_priority_queue *pq,
int (*compare)(const void *, const void *),
unsigned int item_size);
DSHDEF int ds_priority_queue_insert(ds_priority_queue *pq, void *item);
DSHDEF int ds_priority_queue_pull(ds_priority_queue *pq, void *item);
DSHDEF int ds_priority_queue_peek(ds_priority_queue *pq, void *item);
DSHDEF int ds_priority_queue_empty(ds_priority_queue *pq);
DSHDEF void ds_priority_queue_free(ds_priority_queue *pq);
// STRING BUILDER
//
// The string builder is a simple utility to build strings. You can append
// formatted strings to the string builder, and then build the final string.
// The string builder will automatically grow as needed.
typedef struct ds_string_builder
{
ds_dynamic_array items;
} ds_string_builder;
DSHDEF void ds_string_builder_init_allocator(ds_string_builder *sb,
struct ds_allocator *allocator);
DSHDEF void ds_string_builder_init(ds_string_builder *sb);
DSHDEF int ds_string_builder_append(ds_string_builder *sb, const char *format,
...);
DSHDEF int ds_string_builder_appendn(ds_string_builder *sb, const char *str,
unsigned int len);
DSHDEF int ds_string_builder_appendc(ds_string_builder *sb, char chr);
DSHDEF int ds_string_builder_build(ds_string_builder *sb, char **str);
DSHDEF void ds_string_builder_free(ds_string_builder *sb);
// STRING SLICE
//
// The string slice is a simple utility to work with substrings. You can use the
// string slice to tokenize a string, and to convert a string slice to an owned
// string.
typedef struct ds_string_slice
{
struct ds_allocator *allocator;
char *str;
unsigned int len;
} ds_string_slice;
DSHDEF void ds_string_slice_init_allocator(ds_string_slice *ss, char *str,
unsigned int len,
struct ds_allocator *allocator);
DSHDEF void ds_string_slice_init(ds_string_slice *ss, char *str,
unsigned int len);
DSHDEF int ds_string_slice_tokenize(ds_string_slice *ss, char delimiter,
ds_string_slice *token);
DSHDEF int ds_string_slice_trim_left(ds_string_slice *ss, char chr);
DSHDEF int ds_string_slice_trim_right(ds_string_slice *ss, char chr);
DSHDEF int ds_string_slice_trim(ds_string_slice *ss, char chr);
DSHDEF int ds_string_slice_to_owned(ds_string_slice *ss, char **str);
DSHDEF void ds_string_slice_free(ds_string_slice *ss);
// (DOUBLY) LINKED LIST
//
// The linked list is a simple list that can be used to push and pop items from
// the front and back of the list.
typedef struct ds_linked_list_node
{
void *item;
struct ds_linked_list_node *prev;
struct ds_linked_list_node *next;
} ds_linked_list_node;
typedef struct ds_linked_list
{
struct ds_allocator *allocator;
unsigned int item_size;
ds_linked_list_node *head;
ds_linked_list_node *tail;
} ds_linked_list;
DSHDEF void ds_linked_list_init_allocator(ds_linked_list *ll,
unsigned int item_size,
struct ds_allocator *allocator);
DSHDEF void ds_linked_list_init(ds_linked_list *ll, unsigned int item_size);
DSHDEF int ds_linked_list_push_back(ds_linked_list *ll, void *item);
DSHDEF int ds_linked_list_push_front(ds_linked_list *ll, void *item);
DSHDEF int ds_linked_list_pop_back(ds_linked_list *ll, void *item);
DSHDEF int ds_linked_list_pop_front(ds_linked_list *ll, void *item);
DSHDEF int ds_linked_list_empty(ds_linked_list *ll);
DSHDEF void ds_linked_list_free(ds_linked_list *ll);
// HASH TABLE
//
// The hash table is a simple table that uses a hash function to store and
// retrieve items. The hash table uses separate chaining to handle collisions.
// You can define the hash and compare functions to use when inserting and
// retrieving items.
typedef struct ds_hash_table
{
struct ds_allocator *allocator;
ds_dynamic_array *keys;
ds_dynamic_array *values;
unsigned int key_size;
unsigned int value_size;
unsigned int capacity;
unsigned int (*hash)(const void *);
int (*compare)(const void *, const void *);
} ds_hash_table;
DSHDEF int ds_hash_table_init_allocator(
ds_hash_table *ht, unsigned int key_size, unsigned int value_size,
unsigned int capacity, unsigned int (*hash)(const void *),
int (*compare)(const void *, const void *), struct ds_allocator *allocator);
DSHDEF int ds_hash_table_init(ds_hash_table *ht, unsigned int key_size,
unsigned int value_size, unsigned int capacity,
unsigned int (*hash)(const void *),
int (*compare)(const void *, const void *));
DSHDEF int ds_hash_table_insert(ds_hash_table *ht, const void *key,
void *value);
DSHDEF int ds_hash_table_has(ds_hash_table *ht, const void *key);
DSHDEF int ds_hash_table_get(ds_hash_table *ht, const void *key, void *value);
DSHDEF int ds_hash_table_get_ref(ds_hash_table *ht, const void *key,
void **value);
DSHDEF unsigned int ds_hash_table_count(ds_hash_table *ht);
DSHDEF int ds_hash_table_remove(ds_hash_table *ht, const void *key);
DSHDEF void ds_hash_table_free(ds_hash_table *ht);
// ARGUMENT PARSER
//
// The ds_argument parser is a simple utility to parse command line arguments.
// You can define the options and arguments to parse, and then parse the command
// line arguments.
// Argument types
enum ds_argument_type
{
ARGUMENT_TYPE_VALUE, // Argument with a value
ARGUMENT_TYPE_FLAG, // Flag ds_argument
ARGUMENT_TYPE_POSITIONAL, // Positional ds_argument
ARGUMENT_TYPE_POSITIONAL_REST, // Positional ds_argument that consumes the
// rest
ARGUMENT_TYPE_VALUE_ARRAY, // Argument with an array of values
};
// Argument options
typedef struct ds_argparse_options
{
char short_name; // Short name of the ds_argument
char *long_name; // Long name of the ds_argument
char *description; // Description of the ds_argument
enum ds_argument_type type; // Type of the ds_argument
unsigned int required; // Whether the ds_argument is required
} ds_argparse_options;
// Argument
typedef struct ds_argument
{
struct ds_argparse_options options;
union
{
char *value;
unsigned int flag;
ds_dynamic_array values;
};
} ds_argument;
typedef struct ds_argparse_parser
{
struct ds_allocator *allocator;
char *name;
char *description;
char *version;
ds_dynamic_array arguments; // ds_argument
} ds_argparse_parser;
DSHDEF void ds_argparse_parser_init_allocator(struct ds_argparse_parser *parser,
char *name, char *description,
char *version,
struct ds_allocator *allocator);
DSHDEF void ds_argparse_parser_init(struct ds_argparse_parser *parser,
char *name, char *description,
char *version);
DSHDEF int ds_argparse_add_argument(struct ds_argparse_parser *parser,
struct ds_argparse_options options);
DSHDEF int ds_argparse_parse(struct ds_argparse_parser *parser, int argc,
char **argv);
DSHDEF char *ds_argparse_get_value(struct ds_argparse_parser *parser,
char *name);
DSHDEF unsigned int ds_argparse_get_flag(struct ds_argparse_parser *parser,
char *name);
DSHDEF int ds_argparse_get_values(struct ds_argparse_parser *parser, char *name,
ds_dynamic_array *values);
DSHDEF void ds_argparse_print_help(struct ds_argparse_parser *parser);
DSHDEF void ds_argparse_print_version(struct ds_argparse_parser *parser);
DSHDEF void ds_argparse_parser_free(struct ds_argparse_parser *parser);
// IO
//
// The io utils are a simple set of utilities to read and write files.
#ifndef LINE_MAX
#define LINE_MAX 4096
#endif
DSHDEF int ds_io_read_file(const char *path, char **buffer);
DSHDEF int ds_io_write_file(const char *path, const char *buffer, const char *mode);
// RETURN DEFER
//
// The return_defer macro is a simple way to return a value and jump to a label
// to execute cleanup code. It is similar to the defer statement in Go.
#ifndef return_defer
#define return_defer(code) \
do \
{ \
result = code; \
goto defer; \
} while (0)
#endif // return_defer
#ifndef DS_NO_STDLIB
#include <stdlib.h>
#include <string.h>
#endif
#ifndef NULL
#define NULL 0
#endif
#if defined(DS_MEMCPY)
// ok
#elif !defined(DS_MEMCPY) && !defined(DS_NO_STDLIB)
#define DS_MEMCPY(dst, src, sz) memcpy(dst, src, sz)
#elif defined(DS_NO_STDLIB)
#define DS_MEMCPY(dst, src, sz) \
do \
{ \
for (unsigned int i = 0; i < sz; i++) \
{ \
((char *)dst)[i] = ((char *)src)[i]; \
} \
} while (0)
#endif
#if defined(DS_MEMCMP)
// ok
#elif !defined(DS_MEMCMP) && !defined(DS_NO_STDLIB)
#define DS_MEMCMP(ptr1, ptr2, sz) memcmp(ptr1, ptr2, sz)
#elif defined(DS_NO_STDLIB)
#define DS_MEMCMP(ptr1, ptr2, sz) \
({ \
int result = 0; \
for (unsigned int i = 0; i < sz; i++) \
{ \
if (((char *)ptr1)[i] != ((char *)ptr2)[i]) \
{ \
result = ((char *)ptr1)[i] - ((char *)ptr2)[i]; \
break; \
} \
} \
result; \
})
#endif
#if defined(DS_MALLOC) && defined(DS_FREE)
// ok
#elif !defined(DS_MALLOC) && !defined(DS_FREE) && !defined(DS_REALLOC) && \
!defined(DS_NO_STDLIB) && !defined(DS_AL_IMPLEMENTATION)
#define DS_MALLOC(a, sz) malloc(sz)
#define DS_REALLOC(a, ptr, old_sz, new_sz) realloc(ptr, new_sz)
#define DS_FREE(a, ptr) free(ptr)
#elif !defined(DS_MALLOC) && !defined(DS_FREE) && !defined(DS_REALLOC) && \
defined(DS_AL_IMPLEMENTATION)
#define DS_MALLOC(a, sz) ds_allocator_alloc(a, sz)
#define DS_FREE(a, ptr) ds_allocator_free(a, ptr)
#elif defined(DS_NO_STDLIB)
#error "Must define DS_MALLOC and DS_FREE when DS_NO_STDLIB is defined"
#elif defined(DS_REALLOC) && !defined(DS_MALLOC) && !defined(DS_FREE)
#error "Must define DS_MALLOC and DS_FREE when DS_REALLOC is defined"
#else
#error "Must define both DS_MALLOC and DS_FREE, or neither"
#endif
#ifndef DS_REALLOC
static inline void *ds_realloc(void *a, void *ptr, unsigned int old_sz,
unsigned int new_sz)
{
void *new_ptr = DS_MALLOC(a, new_sz);
if (new_ptr == NULL)
{
DS_FREE(a, ptr);
return NULL;
}
DS_MEMCPY(new_ptr, ptr, old_sz < new_sz ? old_sz : new_sz);
DS_FREE(a, ptr);
return new_ptr;
}
#define DS_REALLOC(a, ptr, old_sz, new_sz) ds_realloc(a, ptr, old_sz, new_sz)
#endif
#if defined(DS_EXIT)
// ok
#elif !defined(DS_EXIT) && !defined(DS_NO_STDLIB)
#define DS_EXIT(code) exit(code)
#elif defined(DS_NO_STDLIB)
#error "Must define DS_EXIT when DS_NO_STDLIB is defined"
#endif
#ifndef DS_NO_STDIO
#include <stdio.h>
#endif
// TODO: actually do something for fprintf
#if defined(DS_NO_STDIO) && !defined(fprintf)
#define fprintf(stream, format, ...) 0
#endif
// TODO: actually do something for vsnprintf
#if defined(DS_NO_STDIO) && !defined(vsnprintf)
#define vsnprintf(buffer, size, format, args) 0
#endif
#if defined(DS_NO_STDIO) && !defined(stderr)
#define stderr NULL
#endif
#if defined(DS_NO_STDIO) && !defined(stdout)
#define stdout NULL
#endif
#define DS_LOG_LEVEL_DEBUG 1
#define DS_LOG_LEVEL_INFO 10
#define DS_LOG_LEVEL_WARN 100
#define DS_LOG_LEVEL_ERROR 1000
#define DS_LOG_LEVEL_NONE 10000
#ifndef DS_LOG_LEVEL
#define DS_LOG_LEVEL DS_LOG_LEVEL_DEBUG
#endif
#ifdef DS_NO_TERMINAL_COLORS
#define DS_TERMINAL_RED ""
#define DS_TERMINAL_YELLOW ""
#define DS_TERMINAL_BLUE ""
#define DS_TERMINAL_RESET ""
#else
#define DS_TERMINAL_RED "\033[1;31m"
#define DS_TERMINAL_YELLOW "\033[1;33m"
#define DS_TERMINAL_BLUE "\033[1;34m"
#define DS_TERMINAL_RESET "\033[0m"
#endif
#if DS_LOG_LEVEL > DS_LOG_LEVEL_ERROR
#define DS_LOG_ERROR(format, ...)
#else
#define DS_LOG_ERROR(format, ...) \
fprintf(stderr, \
DS_TERMINAL_RED "ERROR" DS_TERMINAL_RESET ": %s:%d: " format "\n", \
__FILE__, __LINE__, ##__VA_ARGS__)
#endif
#if DS_LOG_LEVEL > DS_LOG_LEVEL_WARN
#define DS_LOG_WARN(format, ...)
#else
#define DS_LOG_WARN(format, ...) \
fprintf(stdout, \
DS_TERMINAL_YELLOW "WARN" DS_TERMINAL_RESET ": %s:%d: " format \
"\n", \
__FILE__, __LINE__, ##__VA_ARGS__)
#endif
#if DS_LOG_LEVEL > DS_LOG_LEVEL_INFO
#define DS_LOG_INFO(format, ...)
#else
#define DS_LOG_INFO(format, ...) \
fprintf(stderr, \
DS_TERMINAL_BLUE "INFO" DS_TERMINAL_RESET ": %s:%d: " format "\n", \
__FILE__, __LINE__, ##__VA_ARGS__)
#endif
#if DS_LOG_LEVEL > DS_LOG_LEVEL_DEBUG
#define DS_LOG_DEBUG(format, ...)
#else
#define DS_LOG_DEBUG(format, ...) \
fprintf(stdout, "DEBUG: %s:%d: " format "\n", __FILE__, __LINE__, \
##__VA_ARGS__)
#endif
#ifndef DS_PANIC
#define DS_PANIC(format, ...) \
do \
{ \
DS_LOG_ERROR(format, ##__VA_ARGS__); \
DS_EXIT(1); \
} while (0)
#endif
// DYNAMIC ARRAY
//
// The dynamic array is a simple array that grows as needed. To use the dynamic
// array append macro, you need to define a struct with the following fields:
// - items: a pointer to the array of items
// - count: the number of items in the array
// - capacity: the number of items that can be stored in the array
#define DS_DA_INIT_CAPACITY 8192
#define ds_da_append(da, item) \
do \
{ \
if ((da)->count >= (da)->capacity) \
{ \
unsigned int new_capacity = (da)->capacity * 2; \
if (new_capacity == 0) \
{ \
new_capacity = DS_DA_INIT_CAPACITY; \
} \
\
(da)->items = DS_REALLOC(NULL, (da)->items, \
(da)->capacity * sizeof(*(da)->items), \
new_capacity * sizeof(*(da)->items)); \
if ((da)->items == NULL) \
{ \
DS_PANIC("Failed to reallocate dynamic array"); \
} \
\
(da)->capacity = new_capacity; \
} \
\
(da)->items[(da)->count++] = (item); \
} while (0)
#define ds_da_append_many(da, new_items, new_items_count) \
do \
{ \
if ((da)->count + new_items_count > (da)->capacity) \
{ \
if ((da)->capacity == 0) \
{ \
(da)->capacity = DS_DA_INIT_CAPACITY; \
} \
while ((da)->count + new_items_count > (da)->capacity) \
{ \
(da)->capacity *= 2; \
} \
\
(da)->items = DS_REALLOC(NULL, (da)->items, \
(da)->capacity * sizeof(*(da)->items), \
(da)->capacity * sizeof(*(da)->items)); \
if ((da)->items == NULL) \
{ \
DS_PANIC("Failed to reallocate dynamic array"); \
} \
} \
\
DS_MEMCPY((da)->items + (da)->count, new_items, \
new_items_count * sizeof(*(da)->items)); \
(da)->count += new_items_count; \
} while (0)
#endif // DS_H
#ifdef DS_IMPLEMENTATION
#define DS_PQ_IMPLEMENTATION
#define DS_SB_IMPLEMENTATION
#define DS_SS_IMPLEMENTATION
#define DS_DA_IMPLEMENTATION
#define DS_LL_IMPLEMENTATION
#define DS_HT_IMPLEMENTATION
#define DS_AL_IMPLEMENTATION
#define DS_AP_IMPLEMENTATION
#define DS_IO_IMPLEMENTATION
#endif // DS_IMPLEMENTATION
#ifdef DS_IO_IMPLEMENTATION
#define DS_SB_IMPLEMENTATION
#endif // DS_IO_IMPLEMENTATION
#ifdef DS_PQ_IMPLEMENTATION
#define DS_DA_IMPLEMENTATION
#endif // DS_PQ_IMPLEMENTATION
#ifdef DS_SB_IMPLEMENTATION
#define DS_DA_IMPLEMENTATION
#endif // DS_SB_IMPLEMENTATION
#ifdef DS_HT_IMPLEMENTATION
#define DS_DA_IMPLEMENTATION
#endif // DS_HT_IMPLEMENTATION
#ifdef DS_AP_IMPLEMENTATION
#define DS_DA_IMPLEMENTATION
#endif // DS_AP_IMPLEMENTATION
#ifdef DS_PQ_IMPLEMENTATION
// Initialize the priority queue with a custom allocator
DSHDEF void ds_priority_queue_init_allocator(
ds_priority_queue *pq, int (*compare)(const void *, const void *),
unsigned int item_size, struct ds_allocator *allocator)
{
ds_dynamic_array_init_allocator(&pq->items, item_size, allocator);
pq->compare = compare;
}
// Initialize the priority queue
DSHDEF void ds_priority_queue_init(ds_priority_queue *pq,
int (*compare)(const void *, const void *),
unsigned int item_size)
{
ds_priority_queue_init_allocator(pq, compare, item_size, NULL);
}
// Insert an item into the priority queue
//
// Returns 0 if the item was inserted successfully.
DSHDEF int ds_priority_queue_insert(ds_priority_queue *pq, void *item)
{
ds_dynamic_array_append(&pq->items, item);
int index = pq->items.count - 1;
int parent = (index - 1) / 2;
void *index_item = NULL;
ds_dynamic_array_get_ref(&pq->items, index, &index_item);
void *parent_item = NULL;
ds_dynamic_array_get_ref(&pq->items, parent, &parent_item);
while (index != 0 && pq->compare(index_item, parent_item) > 0)
{
ds_dynamic_array_swap(&pq->items, index, parent);
index = parent;
parent = (index - 1) / 2;
ds_dynamic_array_get_ref(&pq->items, index, &index_item);
ds_dynamic_array_get_ref(&pq->items, parent, &parent_item);
}
return 0;
}
// Pull the item with the highest priority from the priority queue
//
// Returns 0 if an item was pulled successfully, 1 if the priority queue is
// empty.
DSHDEF int ds_priority_queue_pull(ds_priority_queue *pq, void *item)
{
int result = 0;
if (pq->items.count == 0)
{
DS_LOG_ERROR("Priority queue is empty");
return_defer(1);
}
ds_dynamic_array_get(&pq->items, 0, item);
ds_dynamic_array_swap(&pq->items, 0, pq->items.count - 1);
unsigned int index = 0;
unsigned int swap = index;
void *swap_item = NULL;
do
{
index = swap;
unsigned int left = 2 * index + 1;
void *left_item = NULL;
ds_dynamic_array_get_ref(&pq->items, swap, &swap_item);
ds_dynamic_array_get_ref(&pq->items, left, &left_item);
if (left < pq->items.count - 1 &&
pq->compare(left_item, swap_item) > 0)
{
swap = left;
}
unsigned int right = 2 * index + 2;
void *right_item = NULL;
ds_dynamic_array_get_ref(&pq->items, swap, &swap_item);
ds_dynamic_array_get_ref(&pq->items, right, &right_item);
if (right < pq->items.count - 1 &&
pq->compare(right_item, swap_item) > 0)
{
swap = right;
}
ds_dynamic_array_swap(&pq->items, index, swap);
} while (swap != index);
pq->items.count--;
defer:
return result;
}
// Peek at the item with the highest priority in the priority queue
//
// Returns 0 if an item was peeked successfully, 1 if the priority queue is
// empty.
DSHDEF int ds_priority_queue_peek(ds_priority_queue *pq, void *item)
{
int result = 0;
if (pq->items.count == 0)
{
DS_LOG_ERROR("Priority queue is empty");
return_defer(1);
}
ds_dynamic_array_get(&pq->items, 0, item);
defer:
return result;
}
// Check if the priority queue is empty
DSHDEF int ds_priority_queue_empty(ds_priority_queue *pq)
{
return pq->items.count == 0;
}
// Free the priority queue
DSHDEF void ds_priority_queue_free(ds_priority_queue *pq)
{
ds_dynamic_array_free(&pq->items);
pq->compare = NULL;
}
#endif // DS_PQ_IMPLEMENTATION
#ifdef DS_SB_IMPLEMENTATION
DSHDEF void ds_string_builder_init_allocator(ds_string_builder *sb,
struct ds_allocator *allocator)
{
ds_dynamic_array_init_allocator(&sb->items, sizeof(char), allocator);
}
// Initialize the string builder
DSHDEF void ds_string_builder_init(ds_string_builder *sb)
{
ds_string_builder_init_allocator(sb, NULL);
}
// Append a formatted string to the string builder
//
// Returns 0 if the string was appended successfully.
DSHDEF int ds_string_builder_appendn(ds_string_builder *sb, const char *str,
unsigned int len)
{
return ds_dynamic_array_append_many(&sb->items, (void **)str, len);
}
// Append a formatted string to the string builder
//
// Returns 0 if the string was appended successfully.
DSHDEF int ds_string_builder_append(ds_string_builder *sb, const char *format,
...)
{
int result = 0;
va_list args;
va_start(args, format);
int needed = vsnprintf(NULL, 0, format, args);
va_end(args);
char *buffer = DS_MALLOC(sb->items.allocator, needed + 1);
if (buffer == NULL)
{
DS_LOG_ERROR("Failed to allocate string");
return_defer(1);
}
va_start(args, format);
vsnprintf(buffer, needed + 1, format, args);
va_end(args);
if (ds_dynamic_array_append_many(&sb->items, (void **)buffer, needed) !=
0)
{
return_defer(1);
}
defer:
if (buffer != NULL)
{
DS_FREE(sb->items.allocator, buffer);
}
return result;
}
// Append a character to the string builder
//
// Returns 0 if the character was appended successfully.
DSHDEF int ds_string_builder_appendc(ds_string_builder *sb, char chr)
{
return ds_dynamic_array_append(&sb->items, &chr);
}
// Build the final string from the string builder
//
// Returns 0 if the string was built successfully, 1 if the string could not be
// allocated.
DSHDEF int ds_string_builder_build(ds_string_builder *sb, char **str)
{
int result = 0;
*str = DS_MALLOC(NULL, sb->items.count + 1);
if (*str == NULL)
{
DS_LOG_ERROR("Failed to allocate string");
return_defer(1);
}
DS_MEMCPY(*str, (char *)sb->items.items, sb->items.count);
(*str)[sb->items.count] = '\0';
defer:
return result;
}
// Free the string builder
DSHDEF void ds_string_builder_free(ds_string_builder *sb)
{
ds_dynamic_array_free(&sb->items);
}
#endif // DS_SB_IMPLEMENTATION
#ifdef DS_SS_IMPLEMENTATION
DSHDEF void ds_string_slice_init_allocator(ds_string_slice *ss, char *str,
unsigned int len,
struct ds_allocator *allocator)
{
ss->allocator = allocator;
ss->str = str;
ss->len = len;
}
// Initialize the string slice
DSHDEF void ds_string_slice_init(ds_string_slice *ss, char *str,
unsigned int len)
{
ds_string_slice_init_allocator(ss, str, len, NULL);
}
// Tokenize the string slice by a delimiter
//
// Returns 0 if a token was found, 1 if the string slice is empty.
DSHDEF int ds_string_slice_tokenize(ds_string_slice *ss, char delimiter,
ds_string_slice *token)
{
int result = 0;
if (ss->len == 0 || ss->str == NULL)
{
return_defer(1);
}
token->str = ss->str;
token->len = 0;
for (unsigned int i = 0; i < ss->len; i++)
{
if (ss->str[i] == delimiter)
{
token->len = i;
ss->str += i + 1;
ss->len -= i + 1;
return_defer(0);
}
}
token->len = ss->len;
ss->str += ss->len;
ss->len = 0;
defer:
return result;
}
// Trim the left side of the string slice by a character
//
// Returns 0 if the string was trimmed successfully, 1 if the string slice is
DSHDEF int ds_string_slice_trim_left(ds_string_slice *ss, char chr)
{
int result = 0;
while (ss->len > 0 && ss->str[0] == chr)
{
ss->str++;
ss->len--;
}
return result;
}
// Trim the right side of the string slice by a character
//
// Returns 0 if the string was trimmed successfully, 1 if the string slice is
DSHDEF int ds_string_slice_trim_right(ds_string_slice *ss, char chr)
{
int result = 0;
while (ss->len > 0 && ss->str[ss->len - 1] == chr)
{
ss->len--;
}
return result;
}
// Trim the string slice by a character
//
// Returns 0 if the string was trimmed successfully, 1 if the string slice is
DSHDEF int ds_string_slice_trim(ds_string_slice *ss, char chr)
{
int result = 0;
if (ds_string_slice_trim_left(ss, chr) != 0)
{
return_defer(1);
}
if (ds_string_slice_trim_right(ss, chr) != 0)
{
return_defer(1);
}
defer:
return result;
}
// Convert the string slice to an owned string
//
// Returns 0 if the string was converted successfully, 1 if the string could not
// be allocated.
DSHDEF int ds_string_slice_to_owned(ds_string_slice *ss, char **str)
{
int result = 0;
*str = DS_MALLOC(ss->allocator, ss->len + 1);
if (*str == NULL)
{
DS_LOG_ERROR("Failed to allocate string");
return_defer(1);
}
DS_MEMCPY(*str, ss->str, ss->len);
(*str)[ss->len] = '\0';
defer:
return result;
}
// Free the string slice
DSHDEF void ds_string_slice_free(ds_string_slice *ss)
{
ss->str = NULL;