Skip to content

Commit b787d8e

Browse files
committed
Introduce adopt_foreach
A simple mechanism to iterate through arguments without creating a parser.
1 parent 36c7ec1 commit b787d8e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

adopt.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,28 @@ adopt_status_t adopt_parse(
573573
return validate_required(opt, specs, given_specs);
574574
}
575575

576+
int adopt_foreach(
577+
const adopt_spec specs[],
578+
char **args,
579+
size_t args_len,
580+
unsigned int flags,
581+
int (*callback)(adopt_opt *, void *),
582+
void *callback_data)
583+
{
584+
adopt_parser parser;
585+
adopt_opt opt;
586+
int ret;
587+
588+
adopt_parser_init(&parser, specs, args, args_len, flags);
589+
590+
while (adopt_parser_next(&opt, &parser)) {
591+
if ((ret = callback(&opt, callback_data)) != 0)
592+
return ret;
593+
}
594+
595+
return 0;
596+
}
597+
576598
static int spec_name_fprint(FILE *file, const adopt_spec *spec)
577599
{
578600
int error;

adopt.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,24 @@ adopt_status_t adopt_parse(
293293
size_t args_len,
294294
unsigned int flags);
295295

296+
/**
297+
* Quickly executes the given callback for each argument.
298+
*
299+
* @param specs A NULL-terminated array of `adopt_spec`s that can be parsed
300+
* @param args The arguments that will be parsed
301+
* @param args_len The length of arguments to be parsed
302+
* @param flags The `adopt_flag_t flags for parsing
303+
* @param callback The callback to invoke for each specified option
304+
* @param callback_data Data to be provided to the callback
305+
*/
306+
int adopt_foreach(
307+
const adopt_spec specs[],
308+
char **args,
309+
size_t args_len,
310+
unsigned int flags,
311+
int (*callback)(adopt_opt *, void *),
312+
void *callback_data);
313+
296314
/**
297315
* Initializes a parser that parses the given arguments according to the
298316
* given specifications.

0 commit comments

Comments
 (0)