Skip to content

Commit 540cc75

Browse files
committed
Merge branch 'mh/shorten-unambigous-ref'
* mh/shorten-unambigous-ref: shorten_unambiguous_ref(): tighten up pointer arithmetic gen_scanf_fmt(): delete function and use snprintf() instead shorten_unambiguous_ref(): introduce a new local variable
2 parents 272220f + 7902fe0 commit 540cc75

File tree

1 file changed

+14
-31
lines changed

1 file changed

+14
-31
lines changed

refs.c

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3334,53 +3334,36 @@ int update_refs(const char *action, const struct ref_update **updates_orig,
33343334
return ret;
33353335
}
33363336

3337-
/*
3338-
* generate a format suitable for scanf from a ref_rev_parse_rules
3339-
* rule, that is replace the "%.*s" spec with a "%s" spec
3340-
*/
3341-
static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
3342-
{
3343-
char *spec;
3344-
3345-
spec = strstr(rule, "%.*s");
3346-
if (!spec || strstr(spec + 4, "%.*s"))
3347-
die("invalid rule in ref_rev_parse_rules: %s", rule);
3348-
3349-
/* copy all until spec */
3350-
strncpy(scanf_fmt, rule, spec - rule);
3351-
scanf_fmt[spec - rule] = '\0';
3352-
/* copy new spec */
3353-
strcat(scanf_fmt, "%s");
3354-
/* copy remaining rule */
3355-
strcat(scanf_fmt, spec + 4);
3356-
3357-
return;
3358-
}
3359-
33603337
char *shorten_unambiguous_ref(const char *refname, int strict)
33613338
{
33623339
int i;
33633340
static char **scanf_fmts;
33643341
static int nr_rules;
33653342
char *short_name;
33663343

3367-
/* pre generate scanf formats from ref_rev_parse_rules[] */
33683344
if (!nr_rules) {
3345+
/*
3346+
* Pre-generate scanf formats from ref_rev_parse_rules[].
3347+
* Generate a format suitable for scanf from a
3348+
* ref_rev_parse_rules rule by interpolating "%s" at the
3349+
* location of the "%.*s".
3350+
*/
33693351
size_t total_len = 0;
3352+
size_t offset = 0;
33703353

33713354
/* the rule list is NULL terminated, count them first */
33723355
for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3373-
/* no +1 because strlen("%s") < strlen("%.*s") */
3374-
total_len += strlen(ref_rev_parse_rules[nr_rules]);
3356+
/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3357+
total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
33753358

33763359
scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
33773360

3378-
total_len = 0;
3361+
offset = 0;
33793362
for (i = 0; i < nr_rules; i++) {
3380-
scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
3381-
+ total_len;
3382-
gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
3383-
total_len += strlen(ref_rev_parse_rules[i]);
3363+
assert(offset < total_len);
3364+
scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3365+
offset += snprintf(scanf_fmts[i], total_len - offset,
3366+
ref_rev_parse_rules[i], 2, "%s") + 1;
33843367
}
33853368
}
33863369

0 commit comments

Comments
 (0)