parse-options: add precision handling for OPTION_COUNTUP
Similar to 09705696f7 (parse-options: introduce precision handling for `OPTION_INTEGER`, 2025-04-17) support value variables of different sizes for OPTION_COUNTUP. Do that by requiring their "precision" to be set, casting their "value" pointer accordingly and checking whether the value fits. Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
René Scharfe committed
Jul 9, 2025 at 11:46 UTC
c1e616c39b31e78acc595790bf3a9553a022a19d
3 files changed
+21
-5
parse-options.c
+17
-5
@@ -177,10 +177,22 @@ static enum parse_opt_result do_get_value(struct parse_opt_ctx_t *p,
177
}
178
179
case OPTION_COUNTUP:
180
- if (*(int *)opt->value < 0)
181
- *(int *)opt->value = 0;
182
- *(int *)opt->value = unset ? 0 : *(int *)opt->value + 1;
183
- return 0;
180
+ {
181
+ size_t bits = CHAR_BIT * opt->precision;
182
+ intmax_t upper_bound = INTMAX_MAX >> (bitsizeof(intmax_t) - bits);
183
+ intmax_t value = get_int_value(opt, flags);
184
+
185
+ if (value < 0)
186
+ value = 0;
187
+ if (unset)
188
+ value = 0;
189
+ else if (value < upper_bound)
190
+ value++;
191
+ else
192
+ return error(_("value for %s exceeds %"PRIdMAX),
193
+ optname(opt, flags), upper_bound);
194
+ return set_int_value(opt, flags, value);
195
+ }
196
197
case OPTION_SET_INT:
198
return set_int_value(opt, flags, unset ? 0 : opt->defval);
@@ -651,10 +663,10 @@ static void parse_options_check(const struct option *opts)
663
case OPTION_BIT:
664
case OPTION_NEGBIT:
665
case OPTION_BITOP:
666
+ case OPTION_COUNTUP:
667
if (!signed_int_fits(opts->defval, opts->precision))
668
optbug(opts, "has invalid defval");
669
/* fallthru */
657
- case OPTION_COUNTUP:
670
case OPTION_NUMBER:
671
if ((opts->flags & PARSE_OPT_OPTARG) ||
672
!(opts->flags & PARSE_OPT_NOARG))
parse-options.h
+1
@@ -183,6 +183,7 @@ struct option {
183
.short_name = (s), \
184
.long_name = (l), \
185
.value = (v), \
186
+ .precision = sizeof(*v), \
187
.help = (h), \
188
.flags = PARSE_OPT_NOARG|(f), \
189
}
t/helper/test-parse-options.c
+3
@@ -178,6 +178,7 @@ int cmd__parse_options(int argc, const char **argv)
178
.type = OPTION_COUNTUP,
179
.short_name = '+',
180
.value = &boolean,
181
+ .precision = sizeof(boolean),
182
.help = "same as -b",
183
.flags = PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
184
},
@@ -185,6 +186,7 @@ int cmd__parse_options(int argc, const char **argv)
186
.type = OPTION_COUNTUP,
187
.long_name = "ambiguous",
188
.value = &ambiguous,
189
+ .precision = sizeof(ambiguous),
190
.help = "positive ambiguity",
191
.flags = PARSE_OPT_NOARG | PARSE_OPT_NONEG,
192
},
@@ -192,6 +194,7 @@ int cmd__parse_options(int argc, const char **argv)
194
.type = OPTION_COUNTUP,
195
.long_name = "no-ambiguous",
196
.value = &ambiguous,
197
+ .precision = sizeof(ambiguous),
198
.help = "negative ambiguity",
199
.flags = PARSE_OPT_NOARG | PARSE_OPT_NONEG,
200
},