Code

Merge branch 'cn/maint-rev-list-doc' into maint-1.7.8
[git.git] / strbuf.c
index 1a7df12e8f233863cd931a960d453d54050f5584..692cf1bd9a5e7d97d68eb44722afbdd1b59d2cda 100644 (file)
--- a/strbuf.c
+++ b/strbuf.c
@@ -30,10 +30,8 @@ void strbuf_init(struct strbuf *sb, size_t hint)
 {
        sb->alloc = sb->len = 0;
        sb->buf = strbuf_slopbuf;
-       if (hint) {
+       if (hint)
                strbuf_grow(sb, hint);
-               sb->buf[0] = '\0';
-       }
 }
 
 void strbuf_release(struct strbuf *sb)
@@ -65,12 +63,15 @@ void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
 
 void strbuf_grow(struct strbuf *sb, size_t extra)
 {
+       int new_buf = !sb->alloc;
        if (unsigned_add_overflows(extra, 1) ||
            unsigned_add_overflows(sb->len, extra + 1))
                die("you want to use way too much memory");
-       if (!sb->alloc)
+       if (new_buf)
                sb->buf = NULL;
        ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
+       if (new_buf)
+               sb->buf[0] = '\0';
 }
 
 void strbuf_trim(struct strbuf *sb)
@@ -356,7 +357,6 @@ int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
 {
        int ch;
 
-       strbuf_grow(sb, 0);
        if (feof(fp))
                return EOF;
 
@@ -383,6 +383,22 @@ int strbuf_getline(struct strbuf *sb, FILE *fp, int term)
        return 0;
 }
 
+int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
+{
+       strbuf_reset(sb);
+
+       while (1) {
+               char ch;
+               ssize_t len = xread(fd, &ch, 1);
+               if (len <= 0)
+                       return EOF;
+               strbuf_addch(sb, ch);
+               if (ch == term)
+                       break;
+       }
+       return 0;
+}
+
 int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
 {
        int fd, len;