date: use strbufs in date-formatting functions

Many of the date functions write into fixed-size buffers.
This is a minor pain, as we have to take special
precautions, and frequently end up copying the result into a
strbuf or heap-allocated buffer anyway (for which we
sometimes use strcpy!).

Let's instead teach parse_date, datestamp, etc to write to a
strbuf. The obvious downside is that we might need to
perform a heap allocation where we otherwise would not need
to. However, it turns out that the only two new allocations
required are:

  1. In test-date.c, where we don't care about efficiency.

  2. In determine_author_info, which is not performance
     critical (and where the use of a strbuf will help later
     refactoring).

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jeff King
2014-08-27 03:57:08 -04:00
committed by Junio C Hamano
parent ea5517f04b
commit c33ddc2e33
6 changed files with 45 additions and 48 deletions

13
date.c
View File

@ -605,7 +605,7 @@ static int match_tz(const char *date, int *offp)
return end - date;
}
static int date_string(unsigned long date, int offset, char *buf, int len)
static void date_string(unsigned long date, int offset, struct strbuf *buf)
{
int sign = '+';
@ -613,7 +613,7 @@ static int date_string(unsigned long date, int offset, char *buf, int len)
offset = -offset;
sign = '-';
}
return snprintf(buf, len, "%lu %c%02d%02d", date, sign, offset / 60, offset % 60);
strbuf_addf(buf, "%lu %c%02d%02d", date, sign, offset / 60, offset % 60);
}
/*
@ -735,13 +735,14 @@ int parse_expiry_date(const char *date, unsigned long *timestamp)
return errors;
}
int parse_date(const char *date, char *result, int maxlen)
int parse_date(const char *date, struct strbuf *result)
{
unsigned long timestamp;
int offset;
if (parse_date_basic(date, &timestamp, &offset))
return -1;
return date_string(timestamp, offset, result, maxlen);
date_string(timestamp, offset, result);
return 0;
}
enum date_mode parse_date_format(const char *format)
@ -766,7 +767,7 @@ enum date_mode parse_date_format(const char *format)
die("unknown date format %s", format);
}
void datestamp(char *buf, int bufsize)
void datestamp(struct strbuf *out)
{
time_t now;
int offset;
@ -776,7 +777,7 @@ void datestamp(char *buf, int bufsize)
offset = tm_to_time_t(localtime(&now)) - now;
offset /= 60;
date_string(now, offset, buf, bufsize);
date_string(now, offset, out);
}
/*