Skip to content

Commit

Permalink
strbuf_read(): skip unnecessary strbuf_grow() at eof
Browse files Browse the repository at this point in the history
The loop in strbuf_read() uses xread() repeatedly while extending
the strbuf until the call returns zero.  If the buffer is
sufficiently large to begin with, this results in xread()
returning the remainder of the file to the end (returning
non-zero), the loop extending the strbuf, and then making another
call to xread() to have it return zero.

By using read_in_full(), we can tell when the read reached the end
of file: when it returns less than was requested, it's eof.  This
way we can avoid an extra iteration that allocates an extra 8kB
that is never used.

Signed-off-by: Jim Hill <gjthill@gmail.com>
Reviewed-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Loading branch information
jthill authored and gitster committed Aug 10, 2015
1 parent 282616c commit 3ebbd00
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions strbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -348,19 +348,19 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)

strbuf_grow(sb, hint ? hint : 8192);
for (;;) {
ssize_t cnt;
ssize_t want = sb->alloc - sb->len - 1;
ssize_t got = read_in_full(fd, sb->buf + sb->len, want);

cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
if (cnt < 0) {
if (got < 0) {
if (oldalloc == 0)
strbuf_release(sb);
else
strbuf_setlen(sb, oldlen);
return -1;
}
if (!cnt)
sb->len += got;
if (got < want)
break;
sb->len += cnt;
strbuf_grow(sb, 8192);
}

Expand Down

0 comments on commit 3ebbd00

Please sign in to comment.