Skip to content

Commit b4e04fb

Browse files
stefanbellergitster
authored andcommitted
strbuf: add strbuf_read_once to read without blocking
The new call will read from a file descriptor into a strbuf once. The underlying call xread is just run once. xread only reattempts reading in case of EINTR, which makes it suitable to use for a nonblocking read. Signed-off-by: Stefan Beller <sbeller@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent 1079c4b commit b4e04fb

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

strbuf.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,17 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
384384
return sb->len - oldlen;
385385
}
386386

387+
ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
388+
{
389+
ssize_t cnt;
390+
391+
strbuf_grow(sb, hint ? hint : 8192);
392+
cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
393+
if (cnt > 0)
394+
strbuf_setlen(sb, sb->len + cnt);
395+
return cnt;
396+
}
397+
387398
#define STRBUF_MAXLINK (2*PATH_MAX)
388399

389400
int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)

strbuf.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,14 @@ extern size_t strbuf_fread(struct strbuf *, size_t, FILE *);
366366
*/
367367
extern ssize_t strbuf_read(struct strbuf *, int fd, size_t hint);
368368

369+
/**
370+
* Read the contents of a given file descriptor partially by using only one
371+
* attempt of xread. The third argument can be used to give a hint about the
372+
* file size, to avoid reallocs. Returns the number of new bytes appended to
373+
* the sb.
374+
*/
375+
extern ssize_t strbuf_read_once(struct strbuf *, int fd, size_t hint);
376+
369377
/**
370378
* Read the contents of a file, specified by its path. The third argument
371379
* can be used to give a hint about the file size, to avoid reallocs.

0 commit comments

Comments
 (0)