fast-import: Use strbuf API, and simplify cmd_data()
This patch features the use of strbuf_detach, and prevent the programmer to mess with allocation directly. The code is as efficent as before, just more concise and more straightforward. Signed-off-by: Junio C Hamano <gitster@pobox.com>
Pierre Habouzit committed
Sep 6, 2007 at 13:20 UTC
4a241d79c9020dcafb1f254774bcab200171ab46
1 file changed
+13
-17
fast-import.c
+13
-17
@@ -340,7 +340,7 @@ static struct tag *last_tag;
340
341
/* Input stream parsing */
342
static whenspec_type whenspec = WHENSPEC_RAW;
343
-static struct strbuf command_buf;
343
+static struct strbuf command_buf = STRBUF_INIT;
344
static int unread_command_buf;
345
static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
346
static struct recent_command *cmd_tail = &cmd_hist;
@@ -1638,17 +1638,16 @@ static void cmd_mark(void)
1638
1639
static void *cmd_data (size_t *size)
1640
{
1641
- size_t length;
1642
- char *buffer;
1641
+ struct strbuf buffer;
1642
1643
+ strbuf_init(&buffer);
1644
if (prefixcmp(command_buf.buf, "data "))
1645
die("Expected 'data n' command, found: %s", command_buf.buf);
1646
1647
if (!prefixcmp(command_buf.buf + 5, "<<")) {
1648
char *term = xstrdup(command_buf.buf + 5 + 2);
1649
- size_t sz = 8192, term_len = command_buf.len - 5 - 2;
1650
- length = 0;
1651
- buffer = xmalloc(sz);
1649
+ size_t term_len = command_buf.len - 5 - 2;
1650
+
1651
for (;;) {
1652
read_line(&command_buf, stdin, '\n');
1653
if (command_buf.eof)
@@ -1656,21 +1655,18 @@ static void *cmd_data (size_t *size)
1655
if (term_len == command_buf.len
1656
&& !strcmp(term, command_buf.buf))
1657
break;
1659
- ALLOC_GROW(buffer, length + command_buf.len + 1, sz);
1660
- memcpy(buffer + length,
1661
- command_buf.buf,
1662
- command_buf.len);
1663
- length += command_buf.len;
1664
- buffer[length++] = '\n';
1658
+ strbuf_addbuf(&buffer, &command_buf);
1659
+ strbuf_addch(&buffer, '\n');
1660
}
1661
free(term);
1662
}
1663
else {
1669
- size_t n = 0;
1664
+ size_t n = 0, length;
1665
+
1666
length = strtoul(command_buf.buf + 5, NULL, 10);
1671
- buffer = xmalloc(length);
1667
+
1668
while (n < length) {
1673
- size_t s = fread(buffer + n, 1, length - n, stdin);
1669
+ size_t s = strbuf_fread(&buffer, length - n, stdin);
1670
if (!s && feof(stdin))
1671
die("EOF in data (%lu bytes remaining)",
1672
(unsigned long)(length - n));
@@ -1679,8 +1675,8 @@ static void *cmd_data (size_t *size)
1675
}
1676
1677
skip_optional_lf();
1682
- *size = length;
1683
- return buffer;
1678
+ *size = buffer.len;
1679
+ return strbuf_detach(&buffer);
1680
}
1681
1682
static int validate_raw_date(const char *src, char *result, int maxlen)