This repository has been archived by the owner on Mar 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autil.h
3504 lines (3060 loc) · 105 KB
/
autil.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
/*
AUTIL - ASHN'S UTILITY LIBRARY - v2.0.0
Single header file containing functions and data structures for rapid
application development in C99 (or later) with a focus on simplicity.
This library has no dependencies outside of libc.
USAGE
To create function and object definitions:
#define AUTIL_IMPLEMENTATION
in exactly *ONE* translation unit before including this file:
#define AUTIL_IMPLEMENTATION
#include "autil.h"
To restrict function and object definitions to a single translation unit:
#define AUTIL_API static
before including this file:
#define AUTIL_IMPLEMENTATION
#define AUTIL_API static
#include "autil.h"
This library uses the libc functions realloc and free for dynamic memory
management. If you would like to replace these functions with your own
custom allocation functions:
#define AUTIL_REALLOC custom_realloc
#define AUTIL_FREE custom_free
before including this file in the translation unit where
AUTIL_IMPLEMENTATION is defined:
void* custom_realloc(void* ptr, size_t size);
void custom_free(void* ptr);
#define AUTIL_IMPLEMENTATION
#define AUTIL_REALLOC custom_realloc
#define AUTIL_FREE custom_free
#include "autil.h"
LICENSE
Copyright (c) 2020 ashn <me@ashn.dev>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// HEADER SECTION ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#ifndef AUTIL_H_INCLUDED
#define AUTIL_H_INCLUDED
#ifndef AUTIL_API
# define AUTIL_API extern
#endif
#include <stdarg.h> /* va_list */
#include <stddef.h> /* size_t, NULL */
#include <stdio.h> /* FILE*, printf-family */
struct autil_vstr;
struct autil_bitarr;
struct autil_bigint;
struct autil_string;
struct autil_vec;
struct autil_map;
struct autil_freezer;
// C99 compatible max_align_t.
// clang-format off
typedef union {
_Bool bool_;
char char_;
short short_;
int int_;
long long_;
long long long_long_;
float float_;
double double_;
long double long_double_;
void* void_ptr_;
} autil_max_align_type;
// clang-format on
// Produce a pointer of type TYPE* whose contents is the scalar rvalue val.
// This pointer has automatic storage duration associated with the enclosing
// block.
//
// Example:
// int* pint = AUTIL_LOCAL_PTR(int, 42);
// char const** pstr = AUTIL_LOCAL_PTR(char const*, "FOO");
// printf("%d %s\n", *pint, *pstr); // 42 FOO
#define AUTIL_LOCAL_PTR(TYPE, /*val*/...) (&((TYPE){__VA_ARGS__}))
// Dereference ptr as if it were of type TYPE*.
//
// Example:
// void* ptr = some_func();
// int val = AUTIL_DEREF_PTR(int, ptr);
#define AUTIL_DEREF_PTR(TYPE, /*ptr*/...) (*((TYPE*)(__VA_ARGS__)))
// Number of elements in an array.
#define AUTIL_ARRAY_COUNT(array) (sizeof(array) / sizeof((array)[0]))
// Number of characters in a string literal, excluding the NUL-terminator.
#define AUTIL_STR_LITERAL_COUNT(str_literal) \
(AUTIL_ARRAY_COUNT(str_literal) - 1)
// Number of characters in a formatted string.
#define AUTIL_FMT_COUNT(fmt, ...) ((size_t)snprintf(NULL, 0, fmt, __VA_ARGS__))
// C99 compatible(ish) _Static_assert.
// Macro parameter what should be a valid identifier describing the assertion.
// Flips the order of arguments from C11's _Static_assert so that assertions
// read as if they were a sentence.
// Example:
// // Assert that we are compiling on a 64-bit machine.
// AUTIL_STATIC_ASSERT(pointers_are_eight_bytes, sizeof(void*) == 8);
// clang-format off
#define AUTIL_STATIC_ASSERT(what, expr) \
enum {STATIC_ASSERT__ ## what = 1/!!(expr)}//;
// clang-format on
// Should return an int less than, equal to, or greater than zero if lhs is
// semantically less than, equal to, or greater than rhs, respectively.
typedef int (*autil_vpcmp_fn)(void const* lhs, void const* rhs);
// Implementations of autil_vpcmp_fn for builtin types.
AUTIL_API int
autil_void_vpcmp(void const* lhs, void const* rhs); // void (zero-sized object)
AUTIL_API int
autil_cstr_vpcmp(void const* lhs, void const* rhs); // char const*
AUTIL_API int
autil_int_vpcmp(void const* lhs, void const* rhs); // int
// Alternatives to the C99 standard library functions in ctype.h.
// These functions always use the "C" locale and will not result in undefined
// behavior if passed a value not representable by an unsigned char.
// clang-format off
AUTIL_API int autil_isalnum(int c);
AUTIL_API int autil_isalpha(int c);
AUTIL_API int autil_isblank(int c);
AUTIL_API int autil_iscntrl(int c);
AUTIL_API int autil_isdigit(int c);
AUTIL_API int autil_isgraph(int c);
AUTIL_API int autil_islower(int c);
AUTIL_API int autil_isprint(int c);
AUTIL_API int autil_ispunct(int c);
AUTIL_API int autil_isspace(int c);
AUTIL_API int autil_isupper(int c);
AUTIL_API int autil_isbdigit(int c); // Not in C99. Binary digit.
AUTIL_API int autil_isodigit(int c); // Not in C99. Octal digit.
AUTIL_API int autil_isxdigit(int c);
AUTIL_API int autil_tolower(int c);
AUTIL_API int autil_toupper(int c);
// clang-format on
// Alternatives to the C99 standard library functions in string.h.
// These functions do not result in undefined behavior when passed an invalid
// pointer argument paired with a memory-size argument of zero.
// clang-format off
AUTIL_API int autil_memcmp(void const* s1, void const* s2, size_t n);
AUTIL_API void* autil_memmove(void* dest, void const* src, size_t n);
AUTIL_API void* autil_memset(void* s, int c, size_t n);
// clang-format on
// Zero out the memory under the provided pointer parameter. The number of
// bytes to be zeroed is automatically determined by the sizeof(*ptr).
#define AUTIL_MEMZERO(ptr) autil_memset(ptr, 0x00, sizeof(*ptr))
// General purpose allocator functions with out-of-memory error checking. The
// behavior of autil_xalloc and autil_xallocn is similar to libc realloc and
// *BSD reallocarray with the following exceptions:
// (1) On allocation failure an error message will be printed followed by
// program termination with EXIT_FAILURE status.
// (2) The call autil_xalloc(ptr, 0) is guaranteed to free the memory backing
// ptr. A pointer returned by autil_xalloc may be freed with
// autil_xalloc(ptr, 0) or the equivalent
// autil_xalloc(ptr, AUTIL_XALLOC_FREE). The calls autil_xallocn(ptr, x, 0)
// and autil_xallocn(ptr, 0, y) are equivalent to autil_xalloc(ptr, 0).
// The macro AUTIL_XALLOC_FREE may be used in place of the constant zero to
// indicate that a call autil_xalloc(ptr, AUTIL_XALLOC_FREE) is intended as a
// free operation.
AUTIL_API void*
autil_xalloc(void* ptr, size_t size);
AUTIL_API void*
autil_xallocn(void* ptr, size_t nmemb, size_t size);
#define AUTIL_XALLOC_FREE ((size_t)0)
// Write a formatted info message to stderr.
// A newline is automatically appended to the end of the formatted message.
AUTIL_API void
autil_infof(char const* fmt, ...);
// Write a formatted error message to stderr.
// A newline is automatically appended to the end of the formatted message.
AUTIL_API void
autil_errorf(char const* fmt, ...);
// Write a formatted error message to stderr and exit with EXIT_FAILURE status.
// A newline is automatically appended to the end of the formatted message.
AUTIL_API void
autil_fatalf(char const* fmt, ...);
// Read the full contents of the file specified by path.
// Memory for the read content is allocated with autil_xalloc.
// Returns zero on success.
AUTIL_API int
autil_file_read(char const* path, void** buf, size_t* buf_size);
// Write the contents of a buffer into the file specified by path.
// The file specified by path is created if it does not exist.
// Returns zero on success.
// On failure, the contents of the file specified by path is undefined.
AUTIL_API int
autil_file_write(char const* path, void const* buf, size_t buf_size);
// Read the full contents of the input stream specified by stream.
// Memory for the read content is allocated with autil_xalloc.
// Returns zero on success.
AUTIL_API int
autil_stream_read(FILE* stream, void** buf, size_t* buf_size);
// Read the contents of the input stream specified by stream until a newline or
// end-of-file is encountered.
// The line buffer will *not* have NUL termination.
// The line buffer will contain the end-of-line newline (if present).
// Memory for the read content is allocated with autil_xalloc.
// Returns zero on success.
AUTIL_API int
autil_stream_read_line(FILE* stream, void** buf, size_t* buf_size);
////////////////////////////////////////////////////////////////////////////////
//////// CSTR //////////////////////////////////////////////////////////////////
// Returns an autil_xalloc-allocated cstring of the first count bytes of start.
// This function behaves similarly to the POSIX strdupn function.
AUTIL_API char*
autil_cstr_new(char const* start, size_t count);
// Returns an autil_xalloc-allocated copy of the provided cstring.
// This function behaves similarly to the POSIX strdup function.
AUTIL_API char*
autil_cstr_new_cstr(char const* cstr);
// Returns an autil_xalloc-allocated cstring from the provided formatted text.
AUTIL_API char*
autil_cstr_new_fmt(char const* fmt, ...);
// Returns a non-zero value if cstr starts with target.
AUTIL_API int
autil_cstr_starts_with(char const* cstr, char const* target);
// Returns a non-zero value if cstr ends with target.
AUTIL_API int
autil_cstr_ends_with(char const* cstr, char const* target);
////////////////////////////////////////////////////////////////////////////////
//////// VSTR //////////////////////////////////////////////////////////////////
// Byte string view.
struct autil_vstr {
char const* start;
size_t count;
};
// Produce a pointer of type struct autil_vstr* constructed from the provided
// parameters. This pointer has automatic storage duration associated with the
// enclosing block.
#define AUTIL_VSTR_LOCAL_PTR(start, count) (&(struct autil_vstr){start, count})
// Produce a pointer of type struct autil_vstr* from the provided cstring
// literal. This pointer has automatic storage duration associated with the
// enclosing block.
#define AUTIL_VSTR_LOCAL_PTR_STR_LITERAL(str_literal) \
AUTIL_VSTR_LOCAL_PTR(str_literal, AUTIL_STR_LITERAL_COUNT(str_literal))
// Initializer for a vstring literal from a cstring literal.
// Example:
// static struct autil_vstr const foo =
// AUTIL_VSTR_INIT_STR_LITERAL("foo");
// Example:
// struct autil_vstr bar = {0};
// // some time later...
// bar = (struct autil_vstr)AUTIL_VSTR_INIT_STR_LITERAL("bar");
// clang-format off
#define AUTIL_VSTR_INIT_STR_LITERAL(str_literal) \
{str_literal, AUTIL_STR_LITERAL_COUNT(str_literal)}
// clang-format on
// Return an int less than, equal to, or greater than zero if lhs is
// lexicographically less than, equal to, or greater than rhs, respectively.
AUTIL_API int
autil_vstr_cmp(struct autil_vstr const* lhs, struct autil_vstr const* rhs);
// Comparison function satisfying autil_vpcmp_fn.
// Parameters lhs and rhs must be of type struct autil_vstr const*.
AUTIL_API int
autil_vstr_vpcmp(void const* lhs, void const* rhs);
// Returns a non-zero value if vstr starts with target.
AUTIL_API int
autil_vstr_starts_with(
struct autil_vstr const* vstr, struct autil_vstr const* target);
// Returns a non-zero value if vstr ends with target.
AUTIL_API int
autil_vstr_ends_with(
struct autil_vstr const* vstr, struct autil_vstr const* target);
////////////////////////////////////////////////////////////////////////////////
//////// STRETCHY BUFFER ///////////////////////////////////////////////////////
// General purpose type-safe dynamic array (a.k.a stretchy buffer).
//
// A stretchy buffer works by storing metadata about the number of allocated
// and in-use elements in a header just before the address of the buffer's
// first element. The ith element of a stretchy buffer may be accessed using
// the array index operator, sbuf[i], and a stretchy buffer containing elements
// of type T may be passed to subroutines as if it were regular array-like
// pointer of type T* or T const*. The address of a stretchy buffer may change
// when a resizing operation is performed, similar to resizing operations done
// with realloc, so the address of a stretchy buffer should not be considered
// stable.
//
// +--------+---------+---------+---------+--
// | HEADER | SBUF[0] | SBUF[1] | SBUF[2] | ...
// +--------+---------+---------+---------+--
// ^
// Pointer manipulated by the user / autil_sbuf_* macros.
//
// Example:
// // The declaration:
// // TYPE* identifier = NULL;
// // creates an empty stretchy buffer holding TYPE values.
// // An equivalent declaration:
// // autil_sbuf(TYPE) identifier = NULL;
// // may also be used in most cases.
// int* vals = NULL;
// printf("count == %zu\n", autil_sbuf_count(vals)); /* count == 0 */
//
// for (int i = 0; i < 3; ++i) {
// autil_sbuf_push(vals, (i + 1) * 2);
// }
// printf("count == %zu\n", autil_sbuf_count(vals)); /* count == 3 */
// printf("vals[0] == %d\n", vals[0]); /* vals[0] == 2 */
// printf("vals[1] == %d\n", vals[1]); /* vals[1] == 4 */
// printf("vals[2] == %d\n", vals[2]); /* vals[2] == 6 */
//
// printf("popped == %d\n", autil_sbuf_pop(vals)); /* popped == 6 */
// printf("count == %zu\n", autil_sbuf_count(vals)); /* count == 2 */
//
// // Free memory allocated to the sbuf.
// // This is safe to call even if vals == NULL.
// autil_sbuf_fini(vals);
// Convenience macros used to explicitly annotate a pointer as a stretchy
// buffer. Type annotations for types such as stack-allocated arrays and
// function pointers are not supported by this macro due to the complicated
// nature of C variable/type declarations.
//
// Example:
// autil_sbuf(int) sbuf = NULL;
// autil_sbuf_push(sbuf, 1);
#define autil_sbuf(TYPE) TYPE*
#define autil_sbuf_const(TYPE) TYPE const*
// void autil_sbuf_fini(TYPE* sbuf)
// ------------------------------------------------------------
// Free resources associated with the stretchy buffer.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_fini(sbuf) \
((void)((sbuf) != NULL ? AUTIL__SBUF_FREE_NON_NULL_HEAD_(sbuf) : NULL))
// void autil_sbuf_freeze(TYPE* sbuf, struct autil_freezer* freezer)
// ------------------------------------------------------------
// Register resources within sbuf with the provided freezer.
#define autil_sbuf_freeze(sbuf, freezer) \
((void)((sbuf) != NULL ? AUTIL__SBUF_FREEZE_NON_NULL_HEAD_(sbuf, freezer), NULL : NULL))
// size_t autil_sbuf_count(TYPE* sbuf)
// ------------------------------------------------------------
// The number of elements in the stretchy buffer.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_count(sbuf) \
((size_t)((sbuf) != NULL ? AUTIL__SBUF_PHEAD_CONST_(sbuf)->cnt_ : 0u))
// size_t autil_sbuf_capacity(TYPE* sbuf)
// ------------------------------------------------------------
// The number of elements the allocated in the sbuf.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_capacity(sbuf) \
((size_t)((sbuf) != NULL ? AUTIL__SBUF_PHEAD_CONST_(sbuf)->cap_ : 0u))
// void autil_sbuf_reserve(TYPE* sbuf, size_t n)
// ------------------------------------------------------------
// Update the minimum capacity of the stretchy buffer to n elements.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_reserve(sbuf, /*n*/...) \
((void)((sbuf) = autil__sbuf_rsv_(sizeof(*(sbuf)), sbuf, __VA_ARGS__)))
// void autil_sbuf_resize(TYPE* sbuf, size_t n)
// ------------------------------------------------------------
// Update the count of the stretchy buffer to n elements.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_resize(sbuf, /*n*/...) \
((void)((sbuf) = autil__sbuf_rsz_(sizeof(*(sbuf)), sbuf, __VA_ARGS__)))
// void autil_sbuf_push(TYPE* sbuf, TYPE val)
// ------------------------------------------------------------
// Append val as the last element of the stretchy buffer.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_push(sbuf, /*val*/...) \
((void)(AUTIL__SBUF_MAYBE_GROW_(sbuf), AUTIL__SBUF_APPEND_(sbuf, __VA_ARGS__)))
// TYPE autil_sbuf_pop(TYPE* sbuf)
// ------------------------------------------------------------
// Remove and return the last element of the stretchy buffer.
// This macro does *not* perform bounds checking.
// Macro parameter sbuf is evaluated multiple times.
#define autil_sbuf_pop(sbuf) ((sbuf)[--AUTIL__SBUF_PHEAD_MUTBL_(sbuf)->cnt_])
// Internal utilities that must be visible to other header/source files that
// wish to use the autil_sbuf_* API. Do not use these directly!
// clang-format off
struct autil__sbuf_header_{size_t cnt_; size_t cap_; autil_max_align_type _[];};
enum{AUTIL__SBUF_HEADER_OFFSET_ = sizeof(struct autil__sbuf_header_)};
#define AUTIL__SBUF_PHEAD_MUTBL_(sbuf_) \
((struct autil__sbuf_header_ *) \
((char *)(sbuf_)-AUTIL__SBUF_HEADER_OFFSET_))
#define AUTIL__SBUF_PHEAD_CONST_(sbuf_) \
((struct autil__sbuf_header_ const*) \
((char const*)(sbuf_)-AUTIL__SBUF_HEADER_OFFSET_))
#define AUTIL__SBUF_FREE_NON_NULL_HEAD_(sbuf_) \
(autil_xalloc(AUTIL__SBUF_PHEAD_MUTBL_(sbuf_), AUTIL_XALLOC_FREE))
#define AUTIL__SBUF_FREEZE_NON_NULL_HEAD_(sbuf_, freezer) \
(autil_freezer_register(freezer, AUTIL__SBUF_PHEAD_MUTBL_(sbuf_)))
#define AUTIL__SBUF_MAYBE_GROW_(sbuf_) \
((autil_sbuf_count(sbuf_) == autil_sbuf_capacity(sbuf_)) \
? (sbuf_) = autil__sbuf_grw_(sizeof(*(sbuf_)), sbuf_) \
: (sbuf_))
#define AUTIL__SBUF_APPEND_(sbuf_, ...) \
((sbuf_)[AUTIL__SBUF_PHEAD_MUTBL_(sbuf_)->cnt_++] = (__VA_ARGS__))
AUTIL_API void* autil__sbuf_rsv_(size_t elemsize, void* sbuf, size_t cap);
AUTIL_API void* autil__sbuf_rsz_(size_t elemsize, void* sbuf, size_t cnt);
AUTIL_API void* autil__sbuf_grw_(size_t elemsize, void* sbuf);
// clang-format on
////////////////////////////////////////////////////////////////////////////////
//////// BIT ARRAY /////////////////////////////////////////////////////////////
// Allocate and initialize a bit array with count bits.
// The bit array is initially zeroed.
AUTIL_API struct autil_bitarr*
autil_bitarr_new(size_t count);
// Deinitialize and free the bit array.
// Does nothing if self == NULL.
AUTIL_API void
autil_bitarr_del(struct autil_bitarr* self);
// Register resources within the bit array with the provided freezer.
AUTIL_API void
autil_bitarr_freeze(struct autil_bitarr* self, struct autil_freezer* freezer);
// Returns the number of bits in this bit array.
AUTIL_API size_t
autil_bitarr_count(struct autil_bitarr const* self);
// Set the nth bit (zero indexed) of self to value.
// Fatally exits after printing an error message if n is out of bounds.
AUTIL_API void
autil_bitarr_set(struct autil_bitarr* self, size_t n, int value);
// Returns the value (one or zero) of the nth bit (zero indexed) of self.
// Fatally exits after printing an error message if n is out of bounds.
AUTIL_API int
autil_bitarr_get(struct autil_bitarr const* self, size_t n);
// self = othr
// Fatally exits after printing an error message if the count of self is not
// equal to the count of othr.
AUTIL_API void
autil_bitarr_assign(struct autil_bitarr* self, struct autil_bitarr const* othr);
// res = ~rhs
// Fatally exits after printing an error message if the count of res and rhs
// are not equal.
AUTIL_API void
autil_bitarr_compl(struct autil_bitarr* res, struct autil_bitarr const* rhs);
// res = lhs << nbits (logical shift left)
// Fatally exits after printing an error message if the count of res and lhs
// are not equal.
AUTIL_API void
autil_bitarr_shiftl(
struct autil_bitarr* res, struct autil_bitarr const* lhs, size_t nbits);
// res = lhs >> nbits (logical shift right)
// Fatally exits after printing an error message if the count of res and lhs
// are not equal.
AUTIL_API void
autil_bitarr_shiftr(
struct autil_bitarr* res, struct autil_bitarr const* lhs, size_t nbits);
// res = lhs & rhs
// Fatally exits after printing an error message if the count of res, lhs, and
// rhs are not equal.
AUTIL_API void
autil_bitarr_and(
struct autil_bitarr* res,
struct autil_bitarr const* lhs,
struct autil_bitarr const* rhs);
// res = lhs ^ rhs
// Fatally exits after printing an error message if the count of res, lhs, and
// rhs are not equal.
AUTIL_API void
autil_bitarr_xor(
struct autil_bitarr* res,
struct autil_bitarr const* lhs,
struct autil_bitarr const* rhs);
// res = lhs | rhs
// Fatally exits after printing an error message if the count of res, lhs, and
// rhs are not equal.
AUTIL_API void
autil_bitarr_or(
struct autil_bitarr* res,
struct autil_bitarr const* lhs,
struct autil_bitarr const* rhs);
////////////////////////////////////////////////////////////////////////////////
//////// BIG INTEGER ///////////////////////////////////////////////////////////
// Arbitrary precision integer.
// A bigint conceptually consists of the following components:
// (1) sign: The arithmetic sign of the integer (+, -, or 0).
// (2) magnitude: The absolute value of the bigint, presented through this API
// as an infinitely long sequence of bits with little endian ordering.
extern struct autil_bigint const* const AUTIL_BIGINT_ZERO; // 0
extern struct autil_bigint const* const AUTIL_BIGINT_POS_ONE; // +1
extern struct autil_bigint const* const AUTIL_BIGINT_NEG_ONE; // -1
// Allocate and initialize a bigint to the specified value.
// The call autil_bigint_new(AUTIL_BIGINT_ZERO) will zero-initialize a bigint.
AUTIL_API struct autil_bigint*
autil_bigint_new(struct autil_bigint const* othr);
// Allocate and initialize a bigint from the provided NUL-terminated cstring.
// Returns NULL if the cstring could not be parsed.
//
// The cstring may begin with a plus (+) or minus (-) sign.
// In the absence of a plus or minus sign the cstring will interpreted as a
// non-negative number.
//
// The digits of the cstring may be prefixed with a radix identifier:
// 0b (binary), 0o (octal), or 0x (hexadecimal).
// In the absence of a radix identifier, the digits of the cstring will decoded
// with radix 10 (decimal).
//
// The cstring *must* not have any leading or trailing whitespace.
AUTIL_API struct autil_bigint*
autil_bigint_new_cstr(char const* cstr);
// Allocate and initialize a bigint from the provided string slice.
// Returns NULL if the string could not be parsed.
// This function uses the same string-grammar as autil_bigint_new_cstr().
AUTIL_API struct autil_bigint*
autil_bigint_new_text(char const* start, size_t count);
// Deinitialize and free the bigint.
// Does nothing if self == NULL.
AUTIL_API void
autil_bigint_del(struct autil_bigint* self);
// Register resources within the bigint with the provided freezer.
AUTIL_API void
autil_bigint_freeze(struct autil_bigint* self, struct autil_freezer* freezer);
// Return an int less than, equal to, or greater than zero if lhs is
// semantically less than, equal to, or greater than rhs, respectively.
AUTIL_API int
autil_bigint_cmp(
struct autil_bigint const* lhs, struct autil_bigint const* rhs);
// self = othr
AUTIL_API void
autil_bigint_assign(struct autil_bigint* self, struct autil_bigint const* othr);
// res = -rhs
AUTIL_API void
autil_bigint_neg(struct autil_bigint* res, struct autil_bigint const* rhs);
// res = abs(rhs)
AUTIL_API void
autil_bigint_abs(struct autil_bigint* res, struct autil_bigint const* rhs);
// res = lhs + rhs
AUTIL_API void
autil_bigint_add(
struct autil_bigint* res,
struct autil_bigint const* lhs,
struct autil_bigint const* rhs);
// res = lhs - rhs
AUTIL_API void
autil_bigint_sub(
struct autil_bigint* res,
struct autil_bigint const* lhs,
struct autil_bigint const* rhs);
// res = lhs * rhs
AUTIL_API void
autil_bigint_mul(
struct autil_bigint* res,
struct autil_bigint const* lhs,
struct autil_bigint const* rhs);
// res = lhs / rhs
// rem = lhs % rhs
// If res is NULL then the result will not be written to res.
// If rem is NULL then the remainder will not be written to rem.
//
// This function matches the behavior of the / and % operators as defined by
// the C99 standard, satisfying the expression:
// (lhs/rhs)*rhs + lhs%rhs == lhs
// where:
// lhs/rhs == res
// lhs%rhs == rem
AUTIL_API void
autil_bigint_divrem(
struct autil_bigint* res,
struct autil_bigint* rem,
struct autil_bigint const* lhs,
struct autil_bigint const* rhs);
// self.magnitude = self.magnitude << nbits (logical shift left)
// This function is sign-oblivious (the sign of self is not altered).
AUTIL_API void
autil_bigint_magnitude_shiftl(struct autil_bigint* self, size_t nbits);
// self.magnitude = self.magnitude >> nbits (logical shift right)
// This function is sign-oblivious (the sign of self is not altered).
AUTIL_API void
autil_bigint_magnitude_shiftr(struct autil_bigint* self, size_t nbits);
// Returns the number of bits required to store the magnitude of self.
// This function is sign-oblivious (the sign of self is not considered).
AUTIL_API size_t
autil_bigint_magnitude_bit_count(struct autil_bigint const* self);
// Returns the value (one or zero) of the nth bit (zero indexed) of the
// magnitude of self.
// This function is sign-oblivious (the sign of self is not considered).
AUTIL_API int
autil_bigint_magnitude_bit_get(struct autil_bigint const* self, size_t n);
// Set the nth bit (zero indexed) of the magnitude of self to value.
// This function is sign-oblivious (the sign of self is not altered).
AUTIL_API void
autil_bigint_magnitude_bit_set(struct autil_bigint* self, size_t n, int value);
// Returns an autil_xalloc-allocated cstring representation of the provided
// bigint as specified by the provided format string.
// If fmt is NULL then default formatting is used.
//
// Returns a NUL-terminated string on success.
// Returns NULL if an invalid format string was provided.
//
// Format string grammar: "[flags][width][specifier]"
// Note that the format directive character, %, is *NOT* used in the format
// string grammar.
//
// Flags (optional):
// # Prefix the digits of the output string with "0b", "0o", "0x", or
// "0x" when used in conjunction with the "b", "o", "x", or "X"
// specifiers, respectively. Note that "0x" is used for both the "x"
// and "X" specifiers.
// 0 Left pad the output string up to the field width using zeros.
// Default behavior is to pad with spaces.
// + Prefix the numeric representation of the output string with a plus
// or minus sign (+ or -), even for positive numbers.
// Default behavior will only emit a minus sign for negative numbers.
// - Left justify the output string within the provided field width.
// space Prefix the numeric representation of the output string with a space
// if no sign would be written otherwise.
//
// Width (optional):
// Decimal digit string with nonzero first digit specifying the minimum
// length of the output string.
//
// Specifier (required):
// d The provided bigint will be represented using decimal notation.
// b The provided bigint will be represented using binary notation.
// o The provided bigint will be represented using octal notation.
// x The provided bigint will be represented using hexadecimal notation
// with *lower case* alphanumeric digits.
// X The provided bigint will be represented using hexadecimal notation
// with *UPPER CASE* alphanumeric digits.
AUTIL_API char*
autil_bigint_to_new_cstr(struct autil_bigint const* self, char const* fmt);
////////////////////////////////////////////////////////////////////////////////
//////// STRING ////////////////////////////////////////////////////////////////
// Byte string with guaranteed NUL termination.
// Allocate and initialize a string from the first count bytes of start.
AUTIL_API struct autil_string*
autil_string_new(char const* start, size_t count);
// Allocate and initialize a string from the provided NUL-terminated cstring.
// If cstr is NULL then string will be initialized to the empty string.
AUTIL_API struct autil_string*
autil_string_new_cstr(char const* cstr);
// Allocate and initialize a string from the provided formatted text.
AUTIL_API struct autil_string*
autil_string_new_fmt(char const* fmt, ...);
// Deinitialize and free the string.
// Does nothing if self == NULL.
AUTIL_API void
autil_string_del(struct autil_string* self);
// Register resources within the string with the provided freezer.
AUTIL_API void
autil_string_freeze(struct autil_string* self, struct autil_freezer* freezer);
// Pointer to the start of the underlying char array of the string.
// Returns a pointer to a NUL terminator when the count of the string is zero.
AUTIL_API char const*
autil_string_start(struct autil_string const* self);
// The number of bytes in the string *NOT* including the NUL terminator.
AUTIL_API size_t
autil_string_count(struct autil_string const* self);
// Return an int less than, equal to, or greater than zero if lhs is
// lexicographically less than, equal to, or greater than rhs, respectively.
AUTIL_API int
autil_string_cmp(
struct autil_string const* lhs, struct autil_string const* rhs);
// Update the count of the string.
// If count is greater than the current count of the string then additional
// elements are initialized with garbage data.
AUTIL_API void
autil_string_resize(struct autil_string* self, size_t count);
// Return a pointer to the byte of the string at position idx.
// Fatally exits after printing an error message if idx is out of bounds.
AUTIL_API char*
autil_string_ref(struct autil_string* self, size_t idx);
AUTIL_API char const*
autil_string_ref_const(struct autil_string const* self, size_t idx);
// Insert count bytes of start into the string at position idx.
// Bytes with position greater than idx are moved back count bytes.
// Fatally exits after printing an error message if idx is out of bounds.
AUTIL_API void
autil_string_insert(
struct autil_string* self, size_t idx, char const* start, size_t count);
// Remove count bytes at position idx from the string.
// Bytes with position greater than idx are moved forward count bytes.
// Fatally exits after printing an error message if the slice to be removed
// indexes out of bounds.
AUTIL_API void
autil_string_remove(struct autil_string* self, size_t idx, size_t count);
// Append count bytes of start onto the end of the string.
AUTIL_API void
autil_string_append(struct autil_string* self, char const* start, size_t count);
// Append the provided NUL-terminated cstring onto the end of the string.
AUTIL_API void
autil_string_append_cstr(struct autil_string* self, char const* cstr);
// Append the formatted text to the end of the string.
AUTIL_API void
autil_string_append_fmt(struct autil_string* self, char const* fmt, ...);
AUTIL_API void
autil_string_append_vfmt(
struct autil_string* self, char const* fmt, va_list args);
// Trim leading and trailing whitespace from the string.
// Bytes of the string are decoded using the "C" locale.
AUTIL_API void
autil_string_trim(struct autil_string* self);
// Split the string on all occurrences of the provided separator. Empty strings
// are *NOT* removed from the result. This function returns a stretchy buffer
// of newly allocated string pointers containing the results of the split.
//
// Example:
// "ABCBB" ===split on "B"===> "A" "C" "" ""
AUTIL_API struct autil_string** /* sbuf */
autil_string_split(
struct autil_string const* self,
char const* separator,
size_t separator_size);
////////////////////////////////////////////////////////////////////////////////
//////// VEC ///////////////////////////////////////////////////////////////////
// General purpose generic resizeable array.
// A vec conceptually consists of the following components:
// (1) data: An array containing the elements of the vec.
// (2) count: The number of elements in the vec.
// (3) capacity: The total number of elements allocated in the data array.
// This value is always greater than or equal to the count of the vec.
// Allocate and initialize a vec holding elements of size elemsize.
AUTIL_API struct autil_vec*
autil_vec_new(size_t elemsize);
// Deinitialize and free the vec.
// Does nothing if self == NULL.
AUTIL_API void
autil_vec_del(struct autil_vec* self);
// Register resources within the vec with the provided freezer.
AUTIL_API void
autil_vec_freeze(struct autil_vec* self, struct autil_freezer* freezer);
// Pointer to the start of the underlying array of the vec.
// May return NULL when the count of the vec is zero.
AUTIL_API void const*
autil_vec_start(struct autil_vec const* self);
// The number of elements in the vec.
AUTIL_API size_t
autil_vec_count(struct autil_vec const* self);
// The number of elements allocated in the vec.
AUTIL_API size_t
autil_vec_capacity(struct autil_vec const* self);
// The sizeof of elements in the vec.
AUTIL_API size_t
autil_vec_elemsize(struct autil_vec const* self);
// Update the minimum capacity of the vec.
// The count of the vec remains unchanged.
AUTIL_API void
autil_vec_reserve(struct autil_vec* self, size_t capacity);
// Update the count of the vec.
// If count is greater than the current count of the vec then additional
// elements are initialized with garbage data.
AUTIL_API void
autil_vec_resize(struct autil_vec* self, size_t count);
// Set the value of the vec *at* position idx to the value *at* data.
// Fatally exits after printing an error message if idx is out of bounds.
//
// Example:
// struct autil_vec* const v = autil_vec_new(sizeof(int));
// // some time later...
// int const foo = 0xdeadbeef;
// autil_vec_set(v, 42u, &val);
AUTIL_API void
autil_vec_set(struct autil_vec* self, size_t idx, void const* data);
// Get a pointer to the value of the vec *at* position idx.
// Fatally exits after printing an error message if idx is out of bounds.
//
// Example:
// struct autil_vec* const v = autil_vec_new(sizeof(int));
// // some time later...
// int val = AUTIL_DEREF_PTR(int, autil_vec_ref(v, 42u)
AUTIL_API void*
autil_vec_ref(struct autil_vec* self, size_t idx);
AUTIL_API void const*
autil_vec_ref_const(struct autil_vec const* self, size_t idx);
// Insert a copy of the value at data into the vec at position idx.
// Elements with position greater than or equal to idx are moved back one
// place.
// Fatally exits after printing an error message if idx is greater than the
// count of the vec.
AUTIL_API void
autil_vec_insert(struct autil_vec* self, size_t idx, void const* data);
// Remove the element at position idx from the vec.
// Elements with position greater than idx are moved forward one place.
// If oldelem is not NULL then the removed element will be copied into oldelem.
// Fatally exits after printing an error message if idx is out of bounds.
AUTIL_API void
autil_vec_remove(struct autil_vec* self, size_t idx, void* oldelem);
// Create or advance an iterator over elements of a vec.
// If parameter iter is NULL then a new iterator pointing to the first element
// of the vec is returned. A NULL value signaling end-of-iteration will be
// returned for a vec with no elements or a vec containing zero-sized elements.
// If parameter iter is non-NULL then the element following iter is returned.
// End-of-iteration is signaled by a NULL return value.
//
// Example (using a const-iterator):
// struct autil_vec* const v = autil_vec_new(sizeof(TYPE));
// // some time later...
// TYPE const* iter = autil_vec_next_const(v, NULL);
// for (; iter != NULL; iter = autil_vec_next_const(v, iter)) {
// do_thing(*iter);
// }
AUTIL_API void*
autil_vec_next(struct autil_vec* self, void const* iter);
AUTIL_API void const*
autil_vec_next_const(struct autil_vec const* self, void const* iter);
////////////////////////////////////////////////////////////////////////////////
//////// MAP ///////////////////////////////////////////////////////////////////
// General purpose generic ordered split flatmap.
// Maps keys of some key-type to values of some value-type.
// Allocate and initialize a map.
// The map will hold keys of size keysize.
// The map will hold values of size valsize.
// Keys-value pairs in the map are sorted by key using keycmp.
AUTIL_API struct autil_map*
autil_map_new(size_t keysize, size_t valsize, autil_vpcmp_fn keycmp);
// Deinitialize and free the map.
// Does nothing if self == NULL.
AUTIL_API void
autil_map_del(struct autil_map* self);
// Register resources within the map with the provided freezer.
AUTIL_API void
autil_map_freeze(struct autil_map* self, struct autil_freezer* freezer);
// The number of key-value pairs in the map.
AUTIL_API size_t
autil_map_count(struct autil_map const* self);
// Reference to the ordered vec of keys in the map.
AUTIL_API struct autil_vec const*
autil_map_keys(struct autil_map const* self);
// Reference to the ordered vec of values in the map.
AUTIL_API struct autil_vec const*
autil_map_vals(struct autil_map const* self);
// Retrieve a pointer to the value associated with key.
// Returns NULL if the map has no key-value pair associated with key.
AUTIL_API void*
autil_map_lookup(struct autil_map* self, void const* key);
AUTIL_API void const*
autil_map_lookup_const(struct autil_map const* self, void const* key);
// Insert a copy of the key-value pair at key/val into the map.
// If a key-value pair with key already exists in the map then the existing key
// and value are replaced with the provided key and value.
//
// If oldkey is not NULL then the removed key will be copied into oldkey.
// If oldval is not NULL then the removed value will be copied into oldval.
// Returns a non-zero value if a key-value pair associated with key was
// replaced by the provided key and value.
AUTIL_API int
autil_map_insert(
struct autil_map* self,
void const* key,
void const* val,
void* oldkey,
void* oldval);
// Remove the key-value pair associated with key.
// If no such key-value pair exists in the map then the operation is a noop.
//
// If oldkey is not NULL then the removed key will be copied into oldkey.
// If oldval is not NULL then the removed value will be copied into oldval.
// Returns a non-zero value if a key-value pair associated with key was
// removed.
AUTIL_API int
autil_map_remove(
struct autil_map* self, void const* key, void* oldkey, void* oldval);
////////////////////////////////////////////////////////////////////////////////
//////// FREEZER ///////////////////////////////////////////////////////////////
// Allocate and initialize a freezer.
AUTIL_API struct autil_freezer*
autil_freezer_new(void);
// Deinitialize and free the freezer.
// Does nothing if self == NULL.
AUTIL_API void
autil_freezer_del(struct autil_freezer* self);
// Register a pointer to autil_xalloc-allocated memory to be freed when the
// freezer is deinitialized.
AUTIL_API void
autil_freezer_register(struct autil_freezer* self, void* ptr);
#endif // AUTIL_H_INCLUDED
////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IMPLEMENTATION SECTION ////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#ifdef AUTIL_IMPLEMENTATION
#undef AUTIL_IMPLEMENTATION
// USE: AUTIL_REALLOC(ptr, size)
#ifndef AUTIL_REALLOC
# define AUTIL_REALLOC realloc
#endif
// USE: AUTIL_FREE(ptr)
#ifndef AUTIL_FREE
# define AUTIL_FREE free
#endif
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
AUTIL_STATIC_ASSERT(CHAR_BIT_IS_8, CHAR_BIT == 8);
AUTIL_API int
autil_void_vpcmp(void const* lhs, void const* rhs)
{
(void)lhs;
(void)rhs;
return 0; // The void (i.e. zero-sized object) type acts as a unit type.
}
AUTIL_API int
autil_cstr_vpcmp(void const* lhs, void const* rhs)
{
assert(lhs != NULL);
assert(rhs != NULL);
return strcmp(*(char const**)lhs, *(char const**)rhs);
}
AUTIL_API int
autil_int_vpcmp(void const* lhs, void const* rhs)
{
assert(lhs != NULL);
assert(rhs != NULL);
int const l = *(int*)lhs;
int const r = *(int*)rhs;
if (l < r) {
return -1;
}
if (l > r) {
return +1;
}
return 0;
}