author | Olivier Brunel
<jjk@jjacky.com> 2023-07-23 11:19:13 UTC |
committer | Olivier Brunel
<jjk@jjacky.com> 2023-07-24 10:16:43 UTC |
parent | 9e782cf20e769b8dce7969f3f685ec84d2462455 |
src/liblimb/djbunix.h/sa_readmax.c | +32 | -0 |
src/liblimb/include/limb/djbunix.h | +2 | -2 |
diff --git a/src/liblimb/djbunix.h/sa_readmax.c b/src/liblimb/djbunix.h/sa_readmax.c new file mode 100644 index 0000000..4c8e804 --- /dev/null +++ b/src/liblimb/djbunix.h/sa_readmax.c @@ -0,0 +1,32 @@ +/* This file is part of limb https://lila.oss/limb + * Copyright (C) 2023 Olivier Brunel jjk@jjacky.com */ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include <errno.h> +#include <limb/allreadwrite.h> +#include <limb/djbunix.h> + +int +sa_readmax(stralloc *sa, int fd, size_t max) +{ + size_t salen = sa->len; + for (;;) + { + size_t n = max && sa->len - salen + 4096 > max ? max - (sa->len - salen) : 4096; + if (!n) { + errno = ENOBUFS; + break; + } + if (!stralloc_readyplus(sa, n)) break; + + ssize_t r = fd_read(fd, sa->s + sa->len, n) ; + switch (r) + { + case -1: break; + case 0: return 1; + default: sa->len += r; + } + } + + sa->len = salen; + return 0; +} diff --git a/src/liblimb/include/limb/djbunix.h b/src/liblimb/include/limb/djbunix.h index 7fcf1a4..21bc86d 100644 --- a/src/liblimb/include/limb/djbunix.h +++ b/src/liblimb/include/limb/djbunix.h @@ -38,8 +38,8 @@ extern int openc_exclat(int fd, const char *file); extern int open_parsed_name(const char *name, open_fn open); #define read_close(dst,dlen,fd) readnclose(fd, dst, dlen) -#define sa_read(sa,fd) slurpn(fd, sa, 0) -#define sa_readmax(sa,fd,max) slurpn(fd, sa, max) +extern int sa_readmax(stralloc *sa, int fd, size_t max); +#define sa_read(sa,fd) sa_readmax(sa, fd, 0) extern ssize_t open_read_closeat(char *dst, size_t dlen, int bfd, const char *file); extern int open_saread_closeat(stralloc *sa, int bfd, const char *file);