summaryrefslogtreecommitdiff
path: root/src/libstddjb/slurpn.c
blob: ee5157fdca7ac810f57c179828fe8c4c84436d75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* ISC license. */

#include <sys/types.h>
#include <errno.h>

#include <skalibs/allreadwrite.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

#define N 4096

int slurpn (int fd, stralloc *sa, size_t max)
{
  size_t sabase = sa->len ;
  int wasnull = !sa->s ;
  for (;;)
  {
    ssize_t r ;
    size_t n = max && sa->len - sabase + N > max ? max - (sa->len - sabase) : N ;
    if (!n) { errno = ENOBUFS ; goto err ; }
    if (!stralloc_readyplus(sa, n)) break ;
    r = fd_read(fd, sa->s + sa->len, n) ;
    switch (r)
    {
      case -1 : goto err ;
      case 0 : return 1 ;
      default : sa->len += r ;
    }
  }

err:
  if (wasnull) stralloc_free(sa) ;
  else sa->len = sabase ;
  return 0 ;
}