strbuf_read(): skip unnecessary strbuf_grow() at eof

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>

Jim Hill committed May 31, 2015 at 11:16 UTC 3ebbd00cf3c5a7c6f90e2fed8adaf0c5145fb4ac
1 file changed +5 -5
strbuf.c
+5 -5
@@ -348,19 +348,19 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
348
349 strbuf_grow(sb, hint ? hint : 8192);
350 for (;;) {
351 - ssize_t cnt;
351 + ssize_t want = sb->alloc - sb->len - 1;
352 + ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
353
353 - cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
354 - if (cnt < 0) {
354 + if (got < 0) {
355 if (oldalloc == 0)
356 strbuf_release(sb);
357 else
358 strbuf_setlen(sb, oldlen);
359 return -1;
360 }
361 - if (!cnt)
361 + sb->len += got;
362 + if (got < want)
363 break;
363 - sb->len += cnt;
364 strbuf_grow(sb, 8192);
365 }
366