23#define alloca __builtin_alloca
47char *GetOpt::nextchar = 0;
48int GetOpt::first_nonopt = 0;
49int GetOpt::last_nonopt = 0;
51GetOpt::GetOpt(
int argc,
char **argv,
const char *optstring)
52 : opterr(1), nargc(argc), nargv(argv), noptstring(optstring) {
58 first_nonopt = last_nonopt = optind = 1;
59 optarg = nextchar = 0;
63 if (optstring[0] ==
'-')
64 ordering = RETURN_IN_ORDER;
65 else if (getenv(
"_POSIX_OPTION_ORDER") != 0)
66 ordering = REQUIRE_ORDER;
71void GetOpt::exchange(
char **argv) {
72 int nonopts_size = (last_nonopt - first_nonopt) *
sizeof(
char *);
75 std::vector<char> temp(nonopts_size);
79 memcpy(temp.data(), &argv[first_nonopt], nonopts_size);
85 memcpy (&argv[first_nonopt], &argv[last_nonopt],
86 (optind - last_nonopt) *
sizeof (
char *));
88 memmove(&argv[first_nonopt], &argv[last_nonopt], (optind - last_nonopt) *
sizeof(
char *));
90 memcpy(&argv[first_nonopt + optind - last_nonopt], temp.data(), nonopts_size);
94 first_nonopt += (optind - last_nonopt);
137int GetOpt::operator()(
void) {
138 if (nextchar == 0 || *nextchar == 0) {
139 if (ordering == PERMUTE) {
143 if (first_nonopt != last_nonopt && last_nonopt != optind)
145 else if (last_nonopt != optind)
146 first_nonopt = optind;
151 while (optind < nargc && (nargv[optind][0] !=
'-' || nargv[optind][1] == 0))
153 last_nonopt = optind;
161 if (optind != nargc && !strcmp(nargv[optind],
"--")) {
164 if (first_nonopt != last_nonopt && last_nonopt != optind)
166 else if (first_nonopt == last_nonopt)
167 first_nonopt = optind;
176 if (optind == nargc) {
179 if (first_nonopt != last_nonopt)
180 optind = first_nonopt;
187 if (nargv[optind][0] !=
'-' || nargv[optind][1] == 0) {
188 if (ordering == REQUIRE_ORDER)
190 optarg = nargv[optind++];
197 nextchar = nargv[optind] + 1;
203 char c = *nextchar++;
204 char *temp = (
char *)strchr(noptstring, c);
210 if (temp == 0 || c ==
':') {
212 if (c < 040 || c >= 0177)
213 fprintf(stderr,
"%s: unrecognized option, character code 0%o\n", nargv[0], c);
215 fprintf(stderr,
"%s: unrecognized option `-%c'\n", nargv[0], c);
219 if (temp[1] ==
':') {
220 if (temp[2] ==
':') {
222 if (*nextchar != 0) {
230 if (*nextchar != 0) {
235 }
else if (optind == nargc) {
237 fprintf(stderr,
"%s: no argument for `-%c' option\n", nargv[0], c);
242 optarg = nargv[optind++];