index_fd(): split into two helper functions

Split out the case where we do not know the size of the input (hence we read everything into a strbuf before doing anything) to index_pipe(), and the other case where we mmap or read the whole data to index_bulk(). Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed May 8, 2011 at 01:47 UTC 7b41e1e15b2cce13deaafc0aab10580036346a5a
1 file changed +31 -11
sha1_file.c
+31 -11
@@ -2619,22 +2619,29 @@ static int index_mem(unsigned char *sha1, void *buf, size_t size,
2619 return ret;
2620 }
2621
2622 +static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
2623 + const char *path, unsigned flags)
2624 +{
2625 + struct strbuf sbuf = STRBUF_INIT;
2626 + int ret;
2627 +
2628 + if (strbuf_read(&sbuf, fd, 4096) >= 0)
2629 + ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
2630 + else
2631 + ret = -1;
2632 + strbuf_release(&sbuf);
2633 + return ret;
2634 +}
2635 +
2636 #define SMALL_FILE_SIZE (32*1024)
2637
2624 -int index_fd(unsigned char *sha1, int fd, struct stat *st,
2625 - enum object_type type, const char *path, unsigned flags)
2638 +static int index_core(unsigned char *sha1, int fd, size_t size,
2639 + enum object_type type, const char *path,
2640 + unsigned flags)
2641 {
2642 int ret;
2628 - size_t size = xsize_t(st->st_size);
2643
2630 - if (!S_ISREG(st->st_mode)) {
2631 - struct strbuf sbuf = STRBUF_INIT;
2632 - if (strbuf_read(&sbuf, fd, 4096) >= 0)
2633 - ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
2634 - else
2635 - ret = -1;
2636 - strbuf_release(&sbuf);
2637 - } else if (!size) {
2644 + if (!size) {
2645 ret = index_mem(sha1, NULL, size, type, path, flags);
2646 } else if (size <= SMALL_FILE_SIZE) {
2647 char *buf = xmalloc(size);
@@ -2648,6 +2655,19 @@ int index_fd(unsigned char *sha1, int fd, struct stat *st,
2655 ret = index_mem(sha1, buf, size, type, path, flags);
2656 munmap(buf, size);
2657 }
2658 + return ret;
2659 +}
2660 +
2661 +int index_fd(unsigned char *sha1, int fd, struct stat *st,
2662 + enum object_type type, const char *path, unsigned flags)
2663 +{
2664 + int ret;
2665 + size_t size = xsize_t(st->st_size);
2666 +
2667 + if (!S_ISREG(st->st_mode))
2668 + ret = index_pipe(sha1, fd, type, path, flags);
2669 + else
2670 + ret = index_core(sha1, fd, size, type, path, flags);
2671 close(fd);
2672 return ret;
2673 }