summaryrefslogtreecommitdiff
path: root/src/libstddjb/slurp.c
blob: 553b29e19837446aa1e17d6cfee06c60ee8a9fb1 (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
/* ISC license. */

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

#define N 4096

int slurp (stralloc *sa, int fd)
{
  register unsigned int salen = sa->len ;
  for (;;)
  {
    int r ;
    if (!stralloc_readyplus(sa, N)) break ;
    r = fd_read(fd, sa->s + sa->len, N) ;
    switch (r)
    {
      case -1: goto err ;
      case 0:
        stralloc_shrink(sa) ;
        return 1 ;
      default:
        sa->len += r ;
    }
  }
err:
  sa->len = salen ;
  stralloc_shrink(sa) ;
  return 0 ;
}