forked from defuse/crackstation-hashdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
optionparser.h
1432 lines (1229 loc) · 39.2 KB
/
optionparser.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
/*
* The Lean Mean C++ Option Parser
*
* Copyright (C) 2012 Matthias S. Benkmann
*
* The "Software" in the following 2 paragraphs refers to this file containing
* the code to The Lean Mean C++ Option Parser.
* The "Software" does NOT refer to any other files which you
* may have received alongside this file (e.g. as part of a larger project that
* incorporates The Lean Mean C++ Option Parser).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this 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.
*/
/*
* You can find the documentation at
*
* http://optionparser.sourceforge.net/
*
* Note: All documentation comments haven been reduced in order to minimize this
* file!
*/
#ifndef OPTIONPARSER_H_
#define OPTIONPARSER_H_
namespace option
{
#ifdef _MSC_VER
#include <intrin.h>
#pragma intrinsic(_BitScanReverse)
struct MSC_Builtin_CLZ
{
static int builtin_clz(unsigned x)
{
unsigned long index;
_BitScanReverse(&index, x);
return 32-index; // int is always 32bit on Windows, even for target x64
}
};
#define __builtin_clz(x) MSC_Builtin_CLZ::builtin_clz(x)
#endif
class Option;
enum ArgStatus
{
ARG_NONE,
ARG_OK,
ARG_IGNORE,
ARG_ILLEGAL
};
typedef ArgStatus (*CheckArg)(const Option& option, bool msg);
struct Descriptor
{
const unsigned index;
const int type;
const char* const shortopt;
const char* const longopt;
const CheckArg check_arg;
const char* help;
};
class Option
{
Option* next_;
Option* prev_;
public:
const Descriptor* desc;
const char* name;
const char* arg;
int namelen;
int type() const
{
return desc == 0 ? 0 : desc->type;
}
int index() const
{
return desc == 0 ? -1 : (int)desc->index;
}
int count()
{
int c = (desc == 0 ? 0 : 1);
Option* p = first();
while (!p->isLast())
{
++c;
p = p->next_;
};
return c;
}
bool isFirst() const
{
return isTagged(prev_);
}
bool isLast() const
{
return isTagged(next_);
}
Option* first()
{
Option* p = this;
while (!p->isFirst())
p = p->prev_;
return p;
}
Option* last()
{
return first()->prevwrap();
}
Option* prev()
{
return isFirst() ? 0 : prev_;
}
Option* prevwrap()
{
return untag(prev_);
}
Option* next()
{
return isLast() ? 0 : next_;
}
Option* nextwrap()
{
return untag(next_);
}
void append(Option* new_last)
{
Option* p = last();
Option* f = first();
p->next_ = new_last;
new_last->prev_ = p;
new_last->next_ = tag(f);
f->prev_ = tag(new_last);
}
operator const Option*() const
{
return desc ? this : 0;
}
operator Option*()
{
return desc ? this : 0;
}
Option() :
desc(0), name(0), arg(0), namelen(0)
{
prev_ = tag(this);
next_ = tag(this);
}
Option(const Descriptor* desc_, const char* name_, const char* arg_)
{
init(desc_, name_, arg_);
}
void operator=(const Option& orig)
{
init(orig.desc, orig.name, orig.arg);
}
Option(const Option& orig)
{
init(orig.desc, orig.name, orig.arg);
}
private:
void init(const Descriptor* desc_, const char* name_, const char* arg_)
{
desc = desc_;
name = name_;
arg = arg_;
prev_ = tag(this);
next_ = tag(this);
namelen = 0;
if (name == 0)
return;
namelen = 1;
if (name[0] != '-')
return;
while (name[namelen] != 0 && name[namelen] != '=')
++namelen;
}
static Option* tag(Option* ptr)
{
return (Option*) ((unsigned long long) ptr | 1);
}
static Option* untag(Option* ptr)
{
return (Option*) ((unsigned long long) ptr & ~1ull);
}
static bool isTagged(Option* ptr)
{
return ((unsigned long long) ptr & 1);
}
};
struct Arg
{
static ArgStatus None(const Option&, bool)
{
return ARG_NONE;
}
static ArgStatus Optional(const Option& option, bool)
{
if (option.arg && option.name[option.namelen] != 0)
return ARG_OK;
else
return ARG_IGNORE;
}
};
struct Stats
{
unsigned buffer_max;
unsigned options_max;
Stats() :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
}
Stats(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false) :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
add(gnu, usage, argc, argv, min_abbr_len, single_minus_longopt);
}
Stats(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false) :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt);
}
Stats(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false) :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
add(false, usage, argc, argv, min_abbr_len, single_minus_longopt);
}
Stats(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false) :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt);
}
void add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false);
void add(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false)
{
add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt);
}
void add(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false)
{
add(false, usage, argc, argv, min_abbr_len, single_minus_longopt);
}
void add(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false)
{
add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt);
}
private:
class CountOptionsAction;
};
class Parser
{
int op_count;
int nonop_count;
const char** nonop_args;
bool err;
public:
Parser() :
op_count(0), nonop_count(0), nonop_args(0), err(false)
{
}
Parser(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[],
int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) :
op_count(0), nonop_count(0), nonop_args(0), err(false)
{
parse(gnu, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
Parser(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[],
int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) :
op_count(0), nonop_count(0), nonop_args(0), err(false)
{
parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
Parser(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], int min_abbr_len = 0,
bool single_minus_longopt = false, int bufmax = -1) :
op_count(0), nonop_count(0), nonop_args(0), err(false)
{
parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
Parser(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0,
bool single_minus_longopt = false, int bufmax = -1) :
op_count(0), nonop_count(0), nonop_args(0), err(false)
{
parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
void parse(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[],
int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1);
void parse(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[],
int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1)
{
parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
void parse(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[],
int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1)
{
parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
void parse(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0,
bool single_minus_longopt = false, int bufmax = -1)
{
parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax);
}
int optionsCount()
{
return op_count;
}
int nonOptionsCount()
{
return nonop_count;
}
const char** nonOptions()
{
return nonop_args;
}
const char* nonOption(int i)
{
return nonOptions()[i];
}
bool error()
{
return err;
}
private:
friend struct Stats;
class StoreOptionAction;
struct Action;
static bool workhorse(bool gnu, const Descriptor usage[], int numargs, const char** args, Action& action,
bool single_minus_longopt, bool print_errors, int min_abbr_len);
static bool streq(const char* st1, const char* st2)
{
while (*st1 != 0)
if (*st1++ != *st2++)
return false;
return (*st2 == 0 || *st2 == '=');
}
static bool streqabbr(const char* st1, const char* st2, long long min)
{
const char* st1start = st1;
while (*st1 != 0 && (*st1 == *st2))
{
++st1;
++st2;
}
return (*st1 == 0 || (min > 0 && (st1 - st1start) >= min)) && (*st2 == 0 || *st2 == '=');
}
static bool instr(char ch, const char* st)
{
while (*st != 0 && *st != ch)
++st;
return *st == ch;
}
static void shift(const char** args, int count)
{
for (int i = 0; i > -count; --i)
{
const char* temp = args[i];
args[i] = args[i - 1];
args[i - 1] = temp;
}
}
};
struct Parser::Action
{
virtual bool perform(Option&)
{
return true;
}
virtual bool finished(int numargs, const char** args)
{
(void) numargs;
(void) args;
return true;
}
};
class Stats::CountOptionsAction: public Parser::Action
{
unsigned* buffer_max;
public:
CountOptionsAction(unsigned* buffer_max_) :
buffer_max(buffer_max_)
{
}
bool perform(Option&)
{
if (*buffer_max == 0x7fffffff)
return false; // overflow protection: don't accept number of options that doesn't fit signed int
++*buffer_max;
return true;
}
};
class Parser::StoreOptionAction: public Parser::Action
{
Parser& parser;
Option* options;
Option* buffer;
int bufmax;
public:
StoreOptionAction(Parser& parser_, Option options_[], Option buffer_[], int bufmax_) :
parser(parser_), options(options_), buffer(buffer_), bufmax(bufmax_)
{
// find first empty slot in buffer (if any)
int bufidx = 0;
while ((bufmax < 0 || bufidx < bufmax) && buffer[bufidx])
++bufidx;
// set parser's optionCount
parser.op_count = bufidx;
}
bool perform(Option& option)
{
if (bufmax < 0 || parser.op_count < bufmax)
{
if (parser.op_count == 0x7fffffff)
return false; // overflow protection: don't accept number of options that doesn't fit signed int
buffer[parser.op_count] = option;
int idx = buffer[parser.op_count].desc->index;
if (options[idx])
options[idx].append(buffer[parser.op_count]);
else
options[idx] = buffer[parser.op_count];
++parser.op_count;
}
return true; // NOTE: an option that is discarded because of a full buffer is not fatal
}
bool finished(int numargs, const char** args)
{
// only overwrite non-option argument list if there's at least 1
// new non-option argument. Otherwise we keep the old list. This
// makes it easy to use default non-option arguments.
if (numargs > 0)
{
parser.nonop_count = numargs;
parser.nonop_args = args;
}
return true;
}
};
inline void Parser::parse(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[],
Option buffer[], int min_abbr_len, bool single_minus_longopt, int bufmax)
{
StoreOptionAction action(*this, options, buffer, bufmax);
err = !workhorse(gnu, usage, argc, argv, action, single_minus_longopt, true, min_abbr_len);
}
inline void Stats::add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len,
bool single_minus_longopt)
{
// determine size of options array. This is the greatest index used in the usage + 1
int i = 0;
while (usage[i].shortopt != 0)
{
if (usage[i].index + 1 >= options_max)
options_max = (usage[i].index + 1) + 1; // 1 more than necessary as sentinel
++i;
}
CountOptionsAction action(&buffer_max);
Parser::workhorse(gnu, usage, argc, argv, action, single_minus_longopt, false, min_abbr_len);
}
inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, const char** args, Action& action,
bool single_minus_longopt, bool print_errors, int min_abbr_len)
{
// protect against NULL pointer
if (args == 0)
numargs = 0;
int nonops = 0;
while (numargs != 0 && *args != 0)
{
const char* param = *args; // param can be --long-option, -srto or non-option argument
// in POSIX mode the first non-option argument terminates the option list
// a lone minus character is a non-option argument
if (param[0] != '-' || param[1] == 0)
{
if (gnu)
{
++nonops;
++args;
if (numargs > 0)
--numargs;
continue;
}
else
break;
}
// -- terminates the option list. The -- itself is skipped.
if (param[1] == '-' && param[2] == 0)
{
shift(args, nonops);
++args;
if (numargs > 0)
--numargs;
break;
}
bool handle_short_options;
const char* longopt_name;
if (param[1] == '-') // if --long-option
{
handle_short_options = false;
longopt_name = param + 2;
}
else
{
handle_short_options = true;
longopt_name = param + 1; //for testing a potential -long-option
}
bool try_single_minus_longopt = single_minus_longopt;
bool have_more_args = (numargs > 1 || numargs < 0); // is referencing argv[1] valid?
do // loop over short options in group, for long options the body is executed only once
{
int idx;
const char* optarg;
/******************** long option **********************/
if (handle_short_options == false || try_single_minus_longopt)
{
idx = 0;
while (usage[idx].longopt != 0 && !streq(usage[idx].longopt, longopt_name))
++idx;
if (usage[idx].longopt == 0 && min_abbr_len > 0) // if we should try to match abbreviated long options
{
int i1 = 0;
while (usage[i1].longopt != 0 && !streqabbr(usage[i1].longopt, longopt_name, min_abbr_len))
++i1;
if (usage[i1].longopt != 0)
{ // now test if the match is unambiguous by checking for another match
int i2 = i1 + 1;
while (usage[i2].longopt != 0 && !streqabbr(usage[i2].longopt, longopt_name, min_abbr_len))
++i2;
if (usage[i2].longopt == 0) // if there was no second match it's unambiguous, so accept i1 as idx
idx = i1;
}
}
// if we found something, disable handle_short_options (only relevant if single_minus_longopt)
if (usage[idx].longopt != 0)
handle_short_options = false;
try_single_minus_longopt = false; // prevent looking for longopt in the middle of shortopt group
optarg = longopt_name;
while (*optarg != 0 && *optarg != '=')
++optarg;
if (*optarg == '=') // attached argument
++optarg;
else
// possibly detached argument
optarg = (have_more_args ? args[1] : 0);
}
/************************ short option ***********************************/
if (handle_short_options)
{
if (*++param == 0) // point at the 1st/next option character
break; // end of short option group
idx = 0;
while (usage[idx].shortopt != 0 && !instr(*param, usage[idx].shortopt))
++idx;
if (param[1] == 0) // if the potential argument is separate
optarg = (have_more_args ? args[1] : 0);
else
// if the potential argument is attached
optarg = param + 1;
}
const Descriptor* descriptor = &usage[idx];
if (descriptor->shortopt == 0) /************** unknown option ********************/
{
// look for dummy entry (shortopt == "" and longopt == "") to use as Descriptor for unknown options
idx = 0;
while (usage[idx].shortopt != 0 && (usage[idx].shortopt[0] != 0 || usage[idx].longopt[0] != 0))
++idx;
descriptor = (usage[idx].shortopt == 0 ? 0 : &usage[idx]);
}
if (descriptor != 0)
{
Option option(descriptor, param, optarg);
switch (descriptor->check_arg(option, print_errors))
{
case ARG_ILLEGAL:
return false; // fatal
case ARG_OK:
// skip one element of the argument vector, if it's a separated argument
if (optarg != 0 && have_more_args && optarg == args[1])
{
shift(args, nonops);
if (numargs > 0)
--numargs;
++args;
}
// No further short options are possible after an argument
handle_short_options = false;
break;
case ARG_IGNORE:
case ARG_NONE:
option.arg = 0;
break;
}
if (!action.perform(option))
return false;
}
} while (handle_short_options);
shift(args, nonops);
++args;
if (numargs > 0)
--numargs;
} // while
if (numargs > 0 && *args == 0) // It's a bug in the caller if numargs is greater than the actual number
numargs = 0; // of arguments, but as a service to the user we fix this if we spot it.
if (numargs < 0) // if we don't know the number of remaining non-option arguments
{ // we need to count them
numargs = 0;
while (args[numargs] != 0)
++numargs;
}
return action.finished(numargs + nonops, args - nonops);
}
struct PrintUsageImplementation
{
struct IStringWriter
{
virtual void operator()(const char*, int)
{
}
};
template<typename Function>
struct FunctionWriter: public IStringWriter
{
Function* write;
virtual void operator()(const char* str, int size)
{
(*write)(str, size);
}
FunctionWriter(Function* w) :
write(w)
{
}
};
template<typename OStream>
struct OStreamWriter: public IStringWriter
{
OStream& ostream;
virtual void operator()(const char* str, int size)
{
ostream.write(str, size);
}
OStreamWriter(OStream& o) :
ostream(o)
{
}
};
template<typename Temporary>
struct TemporaryWriter: public IStringWriter
{
const Temporary& userstream;
virtual void operator()(const char* str, int size)
{
userstream.write(str, size);
}
TemporaryWriter(const Temporary& u) :
userstream(u)
{
}
};
template<typename Syscall>
struct SyscallWriter: public IStringWriter
{
Syscall* write;
int fd;
virtual void operator()(const char* str, int size)
{
(*write)(fd, str, size);
}
SyscallWriter(Syscall* w, int f) :
write(w), fd(f)
{
}
};
template<typename Function, typename Stream>
struct StreamWriter: public IStringWriter
{
Function* fwrite;
Stream* stream;
virtual void operator()(const char* str, int size)
{
(*fwrite)(str, size, 1, stream);
}
StreamWriter(Function* w, Stream* s) :
fwrite(w), stream(s)
{
}
};
static void upmax(int& i1, int i2)
{
i1 = (i1 >= i2 ? i1 : i2);
}
static void indent(IStringWriter& write, int& x, int want_x)
{
int indent = want_x - x;
if (indent < 0)
{
write("\n", 1);
indent = want_x;
}
if (indent > 0)
{
char space = ' ';
for (int i = 0; i < indent; ++i)
write(&space, 1);
x = want_x;
}
}
static bool isWideChar(unsigned ch)
{
if (ch == 0x303F)
return false;
return ((0x1100 <= ch && ch <= 0x115F) || (0x2329 <= ch && ch <= 0x232A) || (0x2E80 <= ch && ch <= 0xA4C6)
|| (0xA960 <= ch && ch <= 0xA97C) || (0xAC00 <= ch && ch <= 0xD7FB) || (0xF900 <= ch && ch <= 0xFAFF)
|| (0xFE10 <= ch && ch <= 0xFE6B) || (0xFF01 <= ch && ch <= 0xFF60) || (0xFFE0 <= ch && ch <= 0xFFE6)
|| (0x1B000 <= ch));
}
class LinePartIterator
{
const Descriptor* tablestart;
const Descriptor* rowdesc;
const char* rowstart;
const char* ptr;
int col;
int len;
int screenlen;
int max_line_in_block;
int line_in_block;
int target_line_in_block;
bool hit_target_line;
void update_length()
{
screenlen = 0;
for (len = 0; ptr[len] != 0 && ptr[len] != '\v' && ptr[len] != '\t' && ptr[len] != '\n'; ++len)
{
++screenlen;
unsigned ch = (unsigned char) ptr[len];
if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte
{
// int __builtin_clz (unsigned int x)
// Returns the number of leading 0-bits in x, starting at the most significant bit
unsigned mask = (unsigned) -1 >> __builtin_clz(ch ^ 0xff);
ch = ch & mask; // mask out length bits, we don't verify their correctness
while (((unsigned char) ptr[len + 1] ^ 0x80) <= 0x3F) // while next byte is continuation byte
{
ch = (ch << 6) ^ (unsigned char) ptr[len + 1] ^ 0x80; // add continuation to char code
++len;
}
// ch is the decoded unicode code point
if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case
++screenlen;
}
}
}
public:
LinePartIterator(const Descriptor usage[]) :
tablestart(usage), rowdesc(0), rowstart(0), ptr(0), col(-1), len(0), max_line_in_block(0), line_in_block(0),
target_line_in_block(0), hit_target_line(true)
{
}
bool nextTable()
{
// If this is NOT the first time nextTable() is called after the constructor,
// then skip to the next table break (i.e. a Descriptor with help == 0)
if (rowdesc != 0)
{
while (tablestart->help != 0 && tablestart->shortopt != 0)
++tablestart;
}
// Find the next table after the break (if any)
while (tablestart->help == 0 && tablestart->shortopt != 0)
++tablestart;
restartTable();
return rowstart != 0;
}
void restartTable()
{
rowdesc = tablestart;
rowstart = tablestart->help;
ptr = 0;
}
bool nextRow()
{
if (ptr == 0)
{
restartRow();
return rowstart != 0;
}
while (*ptr != 0 && *ptr != '\n')
++ptr;
if (*ptr == 0)
{
if ((rowdesc + 1)->help == 0) // table break
return false;
++rowdesc;
rowstart = rowdesc->help;
}
else // if (*ptr == '\n')
{
rowstart = ptr + 1;
}
restartRow();
return true;
}
void restartRow()
{
ptr = rowstart;
col = -1;
len = 0;
screenlen = 0;
max_line_in_block = 0;
line_in_block = 0;
target_line_in_block = 0;
hit_target_line = true;
}
bool next()
{
if (ptr == 0)
return false;
if (col == -1)
{
col = 0;
update_length();
return true;
}
ptr += len;
while (true)
{
switch (*ptr)
{
case '\v':
upmax(max_line_in_block, ++line_in_block);
++ptr;
break;
case '\t':
if (!hit_target_line) // if previous column did not have the targetline
{ // then "insert" a 0-length part
update_length();
hit_target_line = true;
return true;
}
hit_target_line = false;
line_in_block = 0;
++col;