-
Notifications
You must be signed in to change notification settings - Fork 3
/
cargo.c
executable file
·12684 lines (10586 loc) · 365 KB
/
cargo.c
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
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Soderberg <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <ctype.h>
#include "cargo.h"
#include <stdarg.h>
#include <limits.h>
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#define strcasecmp _stricmp
#else // _WIN32 (Unix below)
#include <sys/ioctl.h>
#include <unistd.h>
#include <wordexp.h>
#endif // _WIN32
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif // __APPLE__
#if defined(__STDC__)
# define C89
# if defined(__STDC_VERSION__)
# define C90
# if (__STDC_VERSION__ >= 199409L)
# define C94
# endif
# if (__STDC_VERSION__ >= 199901L)
# define C99
# endif
# endif
#endif
#ifdef _WIN32
#define CARGO_LONGLONG_FMT "I64d"
#define CARGO_ULONGLONG_FMT "I64u"
#else
#define CARGO_LONGLONG_FMT "lld"
#define CARGO_ULONGLONG_FMT "llu"
#endif
#ifdef C90
#include <math.h>
#define cargo_fabs fabs
#else
double cargo_fabs(double x)
{
return (x < 0) ? -x : x;
}
#endif // C90
static cargo_malloc_f replaced_cargo_malloc = NULL;
static cargo_free_f replaced_cargo_free = NULL;
static cargo_realloc_f replaced_cargo_realloc = NULL;
void cargo_set_memfunctions(cargo_malloc_f malloc_replacement,
cargo_realloc_f realloc_replacement,
cargo_free_f free_replacement)
{
replaced_cargo_malloc = malloc_replacement;
replaced_cargo_realloc = realloc_replacement;
replaced_cargo_free = free_replacement;
}
static void *_cargo_malloc(size_t size)
{
if (size == 0)
return NULL;
if (replaced_cargo_malloc)
return replaced_cargo_malloc(size);
return malloc(size);
}
static void *_cargo_realloc(void *ptr, size_t size)
{
return replaced_cargo_realloc ? replaced_cargo_realloc(ptr, size) : realloc(ptr, size);
}
static void _cargo_free(void *ptr)
{
if (replaced_cargo_free)
replaced_cargo_free(ptr);
else
free(ptr);
}
static void *_cargo_calloc(size_t count, size_t size)
{
void *p = NULL;
if (!count || !size)
return NULL;
if (replaced_cargo_malloc)
{
size_t sz = count * size;
// TODO: If count > (size_t max / size), goto fail.
p = replaced_cargo_malloc(sz);
if (p)
return memset(p, 0, sz);
}
p = calloc(count, size);
#ifdef _WIN32
// Windows doesn't set ENOMEM properly.
if (!p)
{
errno = ENOMEM;
return NULL;
}
#endif // _WIN32
return p;
}
static char *_cargo_strdup(const char *str)
{
if (!str)
{
errno = EINVAL;
return NULL;
}
if (replaced_cargo_malloc)
{
size_t len = strlen(str);
void *p = NULL;
if (len == ((size_t)-1))
goto fail;
if ((p = replaced_cargo_malloc(len + 1)))
{
return memcpy(p, str, len + 1);
}
}
else
{
#ifdef _WIN32
return _strdup(str);
#else
return strdup(str);
#endif
}
fail:
errno = ENOMEM;
return NULL;
}
int cargo_suppress_debug;
#ifdef CARGO_DEBUG
#define CARGODBG(level, fmt, ...) \
do \
{ \
if (!cargo_suppress_debug && (level == 1)) \
{ \
fprintf(stderr, "%d [cargo.c:%4d]: [ERROR] " fmt, level, __LINE__, ##__VA_ARGS__); \
} \
else if (!cargo_suppress_debug && (level <= CARGO_DEBUG)) \
{ \
fprintf(stderr, "%d [cargo.c:%4d]: " fmt, level, __LINE__, ##__VA_ARGS__); \
} \
} while (0)
#define CARGODBGI(level, fmt, ...) \
do \
{ \
if (!cargo_suppress_debug && (level <= CARGO_DEBUG)) \
{ \
fprintf(stderr, fmt, ##__VA_ARGS__); \
} \
} while (0)
#else
#define CARGODBG(level, fmt, ...)
#define CARGODBGI(level, fmt, ...)
#endif
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(a, b) memcpy(&(a), &(b), sizeof(va_list))
#endif
#endif
#define CARGO_MIN(a, b) ((a) < (b) ? a : b)
#define CARGO_MAX(a, b) ((a) > (b) ? a : b)
#ifndef CARGO_NOLIB
static int _cargo_get_console_width()
{
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
return -1;
}
CARGODBG(3, "Console width: %d\n",
(int)(csbi.srWindow.Right - csbi.srWindow.Left));
return (int)(csbi.srWindow.Right - csbi.srWindow.Left);
#else // Unix
struct winsize w;
ioctl(0, TIOCGWINSZ , &w);
if (!ioctl(0, TIOCGWINSZ , &w))
{
return w.ws_col;
}
return -1;
#endif // _WIN32
}
int cargo_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
{
int r;
if (!buflen)
return 0;
// Visual Studio 2015+ has support for vsnprintf
#if defined(_MSC_VER) && (_MSC_VER < 1900)
r = _vsnprintf(buf, buflen, format, ap);
if (r < 0)
r = _vscprintf(format, ap);
#else
r = vsnprintf(buf, buflen, format, ap);
#endif
buf[buflen - 1] = '\0';
return r;
}
int cargo_snprintf(char *buf, size_t buflen, const char *format, ...)
{
int r;
va_list ap;
va_start(ap, format);
r = cargo_vsnprintf(buf, buflen, format, ap);
va_end(ap);
return r;
}
char *cargo_strndup(const char *s, size_t n)
{
char *res;
size_t len = strlen(s);
if (n < len)
{
len = n;
}
if (!(res = (char *)_cargo_malloc(len + 1)))
{
return NULL;
}
res[len] = '\0';
return (char *)memcpy(res, s, len);
}
typedef struct cargo_str_s
{
char *s;
size_t l;
size_t offset;
size_t diff;
} cargo_str_t;
int cargo_vappendf(cargo_str_t *str, const char *format, va_list ap)
{
int ret;
assert(str);
str->diff = (str->l - str->offset);
if ((ret = cargo_vsnprintf(&str->s[str->offset],
str->diff, format, ap)) < 0)
{
return -1;
}
str->offset += ret;
return ret;
}
#define CARGO_ASTR_DEFAULT_SIZE 256
typedef struct cargo_astr_s
{
char **s;
size_t l;
size_t offset;
size_t diff;
} cargo_astr_t;
int cargo_avappendf(cargo_astr_t *str, const char *format, va_list ap)
{
int ret = 0;
va_list apc;
assert(str);
assert(str->s);
if (!(*str->s))
{
if (str->l == 0)
{
str->l = CARGO_ASTR_DEFAULT_SIZE;
}
str->offset = 0;
if (!(*str->s = _cargo_calloc(1, str->l)))
{
CARGODBG(1, "Out of memory!\n");
return -1;
}
}
while (1)
{
// We must copy the va_list otherwise it will be
// out of sync on a realloc.
va_copy(apc, ap);
str->diff = (str->l - str->offset);
if ((ret = cargo_vsnprintf(&(*str->s)[str->offset],
str->diff, format, apc)) < 0)
{
CARGODBG(1, "Formatting error\n");
return -1;
}
va_end(apc);
if ((size_t)ret >= str->diff)
{
if (str->l == 0) str->l = CARGO_ASTR_DEFAULT_SIZE;
str->l *= 2;
CARGODBG(4, "Realloc %lu\n", str->l);
if (!(*str->s = _cargo_realloc(*str->s, str->l)))
{
CARGODBG(1, "Out of memory!\n");
return -1;
}
continue;
}
break;
}
str->offset += ret;
return ret;
}
int cargo_appendf(cargo_str_t *str, const char *fmt, ...)
{
int ret;
va_list ap;
assert(str);
va_start(ap, fmt);
ret = cargo_vappendf(str, fmt, ap);
va_end(ap);
return ret;
}
int cargo_aappendf(cargo_astr_t *str, const char *fmt, ...)
{
int ret;
va_list ap;
assert(str);
va_start(ap, fmt);
ret = cargo_avappendf(str, fmt, ap);
va_end(ap);
return ret;
}
#ifndef _WIN32
int _vscprintf(const char *format, va_list argptr)
{
return(vsnprintf(NULL, 0, format, argptr));
}
#endif
//
// Below is code for translating ANSI color escape codes to
// windows equivalent API calls.
//
int cargo_vasprintf(char **strp, const char *format, va_list ap)
{
int count;
va_list apc;
assert(strp);
// Find out how long the resulting string is
va_copy(apc, ap);
count = _vscprintf(format, apc);
va_end(apc);
if (count == 0)
{
*strp = _cargo_strdup("");
return 0;
}
else if (count < 0)
{
// Something went wrong, so return the error code (probably still requires checking of "errno" though)
return count;
}
// Allocate memory for our string
if (!(*strp = _cargo_malloc(count + 1)))
{
return -1;
}
// Do the actual printing into our newly created string
return vsprintf(*strp, format, ap);
}
int cargo_asprintf(char** strp, const char* format, ...)
{
va_list ap;
int count;
va_start(ap, format);
count = cargo_vasprintf(strp, format, ap);
va_end(ap);
return count;
}
#ifdef _WIN32
//
// Conversion tables and structs below are from
// https://github.com/adoxa/ansicon
//
#define CARGO_ANSI_MAX_ARG 16
#define CARGO_ANSI_ESC '\x1b'
#define FOREGROUND_BLACK 0
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#define BACKGROUND_BLACK 0
#define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
const BYTE foregroundcolor[8] =
{
FOREGROUND_BLACK, // black foreground
FOREGROUND_RED, // red foreground
FOREGROUND_GREEN, // green foreground
FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground
FOREGROUND_BLUE, // blue foreground
FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground
FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground
FOREGROUND_WHITE // white foreground
};
const BYTE backgroundcolor[8] =
{
BACKGROUND_BLACK, // black background
BACKGROUND_RED, // red background
BACKGROUND_GREEN, // green background
BACKGROUND_RED | BACKGROUND_GREEN, // yellow background
BACKGROUND_BLUE, // blue background
BACKGROUND_BLUE | BACKGROUND_RED, // magenta background
BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background
BACKGROUND_WHITE, // white background
};
// Map windows console attribute to ANSI number.
const BYTE attr2ansi[8] =
{
0, // black
4, // blue
2, // green
6, // cyan
1, // red
5, // magenta
3, // yellow
7 // white
};
// Used to save the state while parsing the render attributes.
typedef struct cargo_ansi_state_s
{
WORD def; // The default attribute.
BYTE foreground; // ANSI base color (0 to 7; add 30)
BYTE background; // ANSI base color (0 to 7; add 40)
BYTE bold; // console FOREGROUND_INTENSITY bit
BYTE underline; // console BACKGROUND_INTENSITY bit
BYTE rvideo; // swap foreground/bold & background/underline
BYTE concealed; // set foreground/bold to background/underline
BYTE reverse; // swap console foreground & background attributes
} cargo_ansi_state_t;
// ANSI render modifiers used by \x1b[#;#;...;#m
//
// 00 for normal display (or just 0)
// 01 for bold on (or just 1)
// 02 faint (or just 2)
// 03 standout (or just 3)
// 04 underline (or just 4)
// 05 blink on (or just 5)
// 07 reverse video on (or just 7)
// 08 nondisplayed (invisible) (or just 8)
// 22 normal
// 23 no-standout
// 24 no-underline
// 25 no-blink
// 27 no-reverse
// 30 black foreground
// 31 red foreground
// 32 green foreground
// 33 yellow foreground
// 34 blue foreground
// 35 magenta foreground
// 36 cyan foreground
// 37 white foreground
// 39 default foreground
// 40 black background
// 41 red background
// 42 green background
// 43 yellow background
// 44 blue background
// 45 magenta background
// 46 cyan background
// 47 white background
// 49 default background
void cargo_ansi_to_win32(cargo_ansi_state_t *state, int ansi)
{
assert(state);
if ((ansi >= 30) && (ansi <= 37))
{
// Foreground colors.
// We remove 30 so we can use our translation table later.
state->foreground = (ansi - 30);
}
else if ((ansi >= 40) && (ansi <= 47))
{
// Background colors.
state->background = (ansi - 40);
}
else switch (ansi)
{
// Reset to defaults.
case 0: // 00 for normal display (or just 0)
case 39: // 39 default foreground
case 49: // 49 default background
{
WORD a = 7;
if (a < 0)
{
state->reverse = 1;
a = -a;
}
if (ansi != 49)
state->foreground = attr2ansi[a & 7];
if (ansi != 39)
state->background = attr2ansi[(a >> 4) & 7];
// Reset all to default
// (or rather what the console was set to before we started parsing)
if (ansi == 0)
{
state->bold = 0;
state->underline = 0;
state->rvideo = 0;
state->concealed = 0;
}
break;
}
case 1: state->bold = FOREGROUND_INTENSITY; break;
case 5: // blink.
case 4: state->underline = BACKGROUND_INTENSITY; break;
case 7: state->rvideo = 1; break;
case 8: state->concealed = 1; break;
case 21: // Double underline says ansicon
case 22: state->bold = 0; break;
case 25: // no blink.
case 24: state->underline = 0; break;
case 27: state->rvideo = 0; break;
case 28: state->concealed = 0; break;
}
}
WORD cargo_ansi_state_to_attr(cargo_ansi_state_t *state)
{
WORD attr = 0;
assert(state);
if (state->concealed)
{
// Reversed video.
if (state->rvideo)
{
attr = foregroundcolor[state->foreground]
| backgroundcolor[state->foreground];
if (state->bold)
{
attr |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
}
else // Normal.
{
attr = foregroundcolor[state->background]
| backgroundcolor[state->background];
if (state->underline)
{
attr |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
}
}
else if (state->rvideo)
{
attr = foregroundcolor[state->background]
| backgroundcolor[state->foreground];
if (state->bold) attr |= BACKGROUND_INTENSITY;
if (state->underline) attr |= FOREGROUND_INTENSITY;
}
else
{
attr = foregroundcolor[state->foreground] | state->bold
| backgroundcolor[state->background] | state->underline;
}
if (state->reverse)
{
attr = ((attr >> 4) & 15) | ((attr & 15) << 4);
}
return attr;
}
void cargo_print_ansicolor(FILE *fd, const char *buf)
{
const char *end = NULL;
char *numend = NULL;
const char *s = buf;
int i = 0;
cargo_ansi_state_t state;
HANDLE handle = INVALID_HANDLE_VALUE;
CONSOLE_SCREEN_BUFFER_INFO csbi;
memset(&state, 0, sizeof(cargo_ansi_state_t));
handle = (HANDLE)_get_osfhandle(fileno(fd));
GetConsoleScreenBufferInfo(handle, &csbi);
// We reset to these attributes if we get a reset code.
state.def = csbi.wAttributes;
while (*s)
{
if (*s == CARGO_ANSI_ESC)
{
s++;
// ANSI colors are in the following format:
// \x1b[#;#;...;#m
//
// Where # is a set of colors and modifiers, see above for table.
if (*s == '[')
{
// TODO: Add support for other Escape codes than render ones.
s++;
end = strchr(s, 'm');
if (!end || ((end - s) > CARGO_ANSI_MAX_ARG))
{
// Output other escaped sequences
// like normal, we just support colors!
continue;
}
// Parses #;#;#;# until there is no more ';'
// at the end.
do
{
i = strtol(s, &numend, 0);
cargo_ansi_to_win32(&state, i);
s = numend + 1;
} while (*numend == ';');
SetConsoleTextAttribute(handle,
cargo_ansi_state_to_attr(&state));
}
}
else
{
putchar(*s);
s++;
}
}
}
void cargo_fprintf(FILE *fd, const char *fmt, ...)
{
int ret;
va_list ap;
char *s = NULL;
va_start(ap, fmt);
ret = cargo_vasprintf(&s, fmt, ap);
va_end(ap);
if (ret != -1)
{
cargo_print_ansicolor(fd, s);
}
if (s) _cargo_free(s);
}
// Overload the normal printf!
#define fprintf cargo_fprintf
#define printf cargo_printf
#else // Unix below (already has ANSI support).
void cargo_print_ansicolor(FILE *fd, const char *buf)
{
fprintf(fd, "%s", buf);
}
#define cargo_fprintf fprintf
#endif // End Unix
#define cargo_printf(fmt, ...) cargo_fprintf(stdout, fmt, ##__VA_ARGS__)
#define CARGO_NARGS_ONE_OR_MORE -1
#define CARGO_NARGS_ZERO_OR_MORE -2
#define CARGO_NARGS_ZERO_OR_ONE -3
const char *_cargo_type_to_str(cargo_type_t type)
{
switch (type)
{
case CARGO_BOOL: return "bool";
case CARGO_INT: return "int";
case CARGO_UINT: return "unsigned int";
case CARGO_FLOAT: return "float";
case CARGO_DOUBLE: return "double";
case CARGO_STRING: return "string";
case CARGO_LONGLONG: return "long long";
case CARGO_ULONGLONG: return "unsigned long long";
}
return NULL;
}
typedef enum cargo_bool_acc_op_e
{
CARGO_BOOL_OP_PLUS,
CARGO_BOOL_OP_OR,
CARGO_BOOL_OP_AND,
CARGO_BOOL_OP_STORE
} cargo_bool_acc_op_t;
struct cargo_validation_s
{
const char *name;
cargo_validation_f validator;
cargo_validation_destroy_f destroy;
cargo_type_t types;
size_t ref_count;
void *user;
};
typedef struct cargo_group_s cargo_group_t;
typedef struct cargo_opt_s
{
char *name[CARGO_NAME_COUNT];
size_t name_count;
char *description;
char *metavar;
int positional;
cargo_type_t type;
int nargs;
int alloc;
int str_alloc_items; // If we should allocate string items
// (but not the array).
int group_index;
size_t mutex_group_idxs[CARGO_MAX_OPT_MUTEX_GROUP];
size_t mutex_group_count;
char **mutex_group_names;
cargo_custom_f custom; // Custom callback function.
void *custom_user; // Custom user data passed to user callback.
size_t *custom_user_count; // Used to return array count when parsing
// custom callbacks.
char **custom_target; // Internal storage for args passed to callback.
size_t custom_target_count; // Internal count for args passed to callbac.
void **target; // Pointer to target values.
size_t target_idx; // Current index into target values.
size_t *target_count; // Return value or number of parsed target values.
size_t lenstr; // String length.
size_t max_target_count; // Max values to store in an array.
int array; // Is this option being parsed as an array?
int parsed; // The argv index when we last parsed the option
cargo_option_flags_t flags;
int num_eaten; // How many arguments consumed by this option.
int first_parse; // First time we parse this? (cargo_parse can be called more than once)
int bool_store; // Value to store when a bool flag is set.
int bool_count; // If we should count occurances for bool flag.
// Bool accumulator related.
int *bool_acc; // Values to accumulate.
cargo_bool_acc_op_t bool_acc_op; // Operation used to accumulate.
size_t bool_acc_count; // Current index into the accumulate vals.
size_t bool_acc_max_count; // Number of accumulation values.
char *zero_or_one_default; // Default value used for target value when
// CARGO_NARGS_ZERO_OR_ONE is used
// ('?' format character). This value is passed
// by the caller.
cargo_validation_t *validation; // Validation for target values.
cargo_validation_flags_t validation_flags;
} cargo_opt_t;
#define CARGO_DEFAULT_MAX_GROUPS 4
#define CARGO_DEFAULT_MAX_GROUP_OPTS 8
struct cargo_group_s
{
char *name;
char *title;
char *description;
char *metavar;
size_t flags; // This is either cargo_group_flags_t
// or cargo_mutex_group_flags_t depending on type.
size_t *option_indices;
size_t opt_count;
size_t max_opt_count;
void *user;
};
typedef struct cargo_s
{
char *progname;
char *description;
char *epilog;
size_t max_width;
cargo_usage_t usage_flags;
cargo_flags_t flags;
int i; // argv index.
int j; // sub-argv index (when getting arguments for options)
int argc;
char **argv;
int start;
int stopped;
int stopped_hard;
int help;
cargo_group_t *groups;
size_t group_count;
size_t max_groups;
cargo_group_t *mutex_groups;
size_t mutex_group_count;
size_t mutex_max_groups;
cargo_opt_t *options;
size_t opt_count;
size_t max_opts;
const char *prefix;
char **unknown_opts;
int *unknown_opts_idxs;
size_t unknown_opts_count;
char **args;
size_t arg_count;
char *error;
char *short_usage;
char *usage;
void *user;
} cargo_s;
static void _cargo_xfree(void *p)
{
void **pp;
assert(p);
pp = (void **)p;
if (*pp)
{
_cargo_free(*pp);
*pp = NULL;
}
}
static void _cargo_set_error(cargo_t ctx, char *error)
{
assert(ctx);
_cargo_xfree(&ctx->error);
ctx->error = error;
}
static cargo_fprint_flags_t _cargo_get_cflag(cargo_t ctx)
{
assert(ctx);
return (ctx->flags & CARGO_NOCOLOR) ? CARGO_FPRINT_NOCOLOR : 0;
}
static size_t _cargo_get_type_size(cargo_type_t t)
{
assert((t >= CARGO_BOOL) && (t <= CARGO_ULONGLONG));
switch (t)
{
case CARGO_BOOL:
case CARGO_INT: return sizeof(int);
case CARGO_UINT: return sizeof(unsigned int);
case CARGO_FLOAT: return sizeof(float);
case CARGO_DOUBLE: return sizeof(double);
case CARGO_STRING: return sizeof(char *);
case CARGO_LONGLONG: return sizeof(long long int);
case CARGO_ULONGLONG: return sizeof(unsigned long long int);
}
return 0;
}
static int _cargo_nargs_is_valid(int nargs)
{
return (nargs >= 0)
|| (nargs == CARGO_NARGS_ZERO_OR_MORE)
|| (nargs == CARGO_NARGS_ONE_OR_MORE)
|| (nargs == CARGO_NARGS_ZERO_OR_ONE);
}
static int _cargo_starts_with_prefix(cargo_t ctx, const char *arg)
{
if (!arg)
return 0;
return (strpbrk(arg, ctx->prefix) == arg);
}