[RFC PATCH 06/11] lib: getopt: Add getopt_pop() helper

Sean Anderson seanga2 at gmail.com
Fri May 15 23:40:20 CEST 2026


On 5/15/26 16:32, Simon Glass wrote:
> Callers that consume positional arguments after parsing routinely write
> the same shape:
> 
>      algo = gs.args[gs.index];
>      /* advance past algo */
>      return hash_command(algo, ..., gs.nonopts - 1, &gs.args[gs.index + 1]);

I think it's better to be explicit.

> 
> Wrap that in a small inline helper that returns the next positional,
> advances gs.index, decrements gs.nonopts, and returns NULL when no
> positionals remain. The same helper doubles as an iterator:
> 
>      while ((arg = getopt_pop(&gs)))
>          process(arg);
> 
> stddef.h is now included from getopt.h for the NULL macro.
> 
> Signed-off-by: Simon Glass <sjg at chromium.org>
> ---
> 
>   include/getopt.h | 23 +++++++++++++++++++++++
>   1 file changed, 23 insertions(+)
> 
> diff --git a/include/getopt.h b/include/getopt.h
> index 5a9e7802e65..013431807ff 100644
> --- a/include/getopt.h
> +++ b/include/getopt.h
> @@ -10,6 +10,7 @@
>   #define __GETOPT_H
>   
>   #include <stdbool.h>
> +#include <stddef.h>
>   #include <linux/kconfig.h>
>   
>   /**
> @@ -126,4 +127,26 @@ static inline int getopt_silent(struct getopt_state *gs,
>   	return __getopt(gs, optstring, true);
>   }
>   
> +/**
> + * getopt_pop() - Take the next remaining positional argument
> + * @gs: State, after getopt() has returned -1
> + *
> + * Returns the first parked non-option (``gs->args[gs->index]``),
> + * advances the index, and decrements ``gs->nonopts``. Returns NULL
> + * when no positional arguments remain.
> + *
> + * Useful for consuming positionals one at a time after parsing::
> + *
> + *     algo = getopt_pop(&gs);
> + *     return hash_command(algo, ..., gs.nonopts, &gs.args[gs.index]);
> + */
> +static inline char *getopt_pop(struct getopt_state *gs)
> +{
> +	if (gs->index >= gs->argc)
> +		return NULL;
> +	if (gs->nonopts > 0)
> +		gs->nonopts--;
> +	return gs->args[gs->index++];
> +}
> +
>   #endif /* __GETOPT_H */



More information about the U-Boot mailing list