sha1_get_pack_name: use a strbuf

We do some manual memory computation here, and there's no check that our 60 is not overflowed by the raw sprintf (it isn't, because the "which" parameter is never longer than "pack"). We can simplify this greatly with a strbuf. Technically the end result is not identical, as the original took care not to rewrite the object directory on each call for performance reasons. We could do that here, too (by saving the baselen and resetting to it), but it's not worth the complexity; this function is not called a lot (generally once per packfile that we open). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Sep 24, 2015 at 17:07 UTC ac5190cc48bd75586566ccc052304d40bbc63147
1 file changed +10 -29
sha1_file.c
+10 -29
@@ -208,44 +208,25 @@ const char *sha1_file_name(const unsigned char *sha1)
208 * provided by the caller. which should be "pack" or "idx".
209 */
210 static char *sha1_get_pack_name(const unsigned char *sha1,
211 - char **name, char **base, const char *which)
211 + struct strbuf *buf,
212 + const char *which)
213 {
213 - static const char hex[] = "0123456789abcdef";
214 - char *buf;
215 - int i;
216 -
217 - if (!*base) {
218 - const char *sha1_file_directory = get_object_directory();
219 - int len = strlen(sha1_file_directory);
220 - *base = xmalloc(len + 60);
221 - sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
222 - sha1_file_directory, which);
223 - *name = *base + len + 11;
224 - }
225 -
226 - buf = *name;
227 -
228 - for (i = 0; i < 20; i++) {
229 - unsigned int val = *sha1++;
230 - *buf++ = hex[val >> 4];
231 - *buf++ = hex[val & 0xf];
232 - }
233 -
234 - return *base;
214 + strbuf_reset(buf);
215 + strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
216 + sha1_to_hex(sha1), which);
217 + return buf->buf;
218 }
219
220 char *sha1_pack_name(const unsigned char *sha1)
221 {
239 - static char *name, *base;
240 -
241 - return sha1_get_pack_name(sha1, &name, &base, "pack");
222 + static struct strbuf buf = STRBUF_INIT;
223 + return sha1_get_pack_name(sha1, &buf, "pack");
224 }
225
226 char *sha1_pack_index_name(const unsigned char *sha1)
227 {
246 - static char *name, *base;
247 -
248 - return sha1_get_pack_name(sha1, &name, &base, "idx");
228 + static struct strbuf buf = STRBUF_INIT;
229 + return sha1_get_pack_name(sha1, &buf, "idx");
230 }
231
232 struct alternate_object_database *alt_odb_list;