[PATCHv3 04/13] strbuf: add strbuf_read_once to read without blocking
- From
Stefan Beller <sbeller@google.com>
- Date
- Sep 21, 2015, 22:39 UTC
- Message-ID
- <1442875159-13027-5-git-send-email-sbeller@google.com>
- In-Reply-To
- <1442875159-13027-1-git-send-email-sbeller@google.com>
The new call will read a fd into a strbuf once. The underlying call xread_nonblock is meant to execute non blockingly if the fd is set to O_NONBLOCK.
Signed-off-by: Stefan Beller <sbeller@google.com> --- strbuf.c | 11 +++++++++++ strbuf.h | 6 ++++++ 2 files changed, 17 insertions(+)
diff --git a/strbuf.c b/strbuf.c index cce5eed..35e71b8 100644 --- a/strbuf.c +++ b/strbuf.c @@ -384,6 +384,17 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint) return sb->len - oldlen; } +ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint) +{ + ssize_t cnt; + + strbuf_grow(sb, hint ? hint : 8192); + cnt = xread_nonblock(fd, sb->buf + sb->len, sb->alloc - sb->len - 1); + if (cnt > 0) + strbuf_setlen(sb, sb->len + cnt); + return cnt; +} + #define STRBUF_MAXLINK (2*PATH_MAX) int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint) diff --git a/strbuf.h b/strbuf.h index aef2794..4d4e5b1 100644 --- a/strbuf.h +++ b/strbuf.h @@ -367,6 +367,12 @@ extern size_t strbuf_fread(struct strbuf *, size_t, FILE *); extern ssize_t strbuf_read(struct strbuf *, int fd, size_t hint); /** + * Same as strbuf_read, just returns non-blockingly by ignoring EAGAIN. + * The fd must have set O_NONBLOCK. + */ +extern ssize_t strbuf_read_once(struct strbuf *, int fd, size_t hint); + +/** * Read the contents of a file, specified by its path. The third argument * can be used to give a hint about the file size, to avoid reallocs. */
-- 2.5.0.275.ge015d2a