summaryrefslogtreecommitdiff
path: root/src/libstddjb/getlnmax.c
blob: 6f6783a53ab753303eeedaaac28c949c16538839 (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
/* ISC license. */

#include <sys/types.h>
#include <sys/uio.h>
#include <errno.h>
#include <skalibs/bytestr.h>
#include <skalibs/buffer.h>
#include <skalibs/skamisc.h>

int getlnmax (buffer *b, char *d, size_t max, size_t *w, char sep)
{
  if (max < *w) return (errno = EINVAL, -1) ;
  for (;;)
  {
    struct iovec v[2] ;
    size_t len = buffer_len(b) ;
    size_t pos ;
    ssize_t r ;
    buffer_rpeek(b, v) ;
    if (len > max - *w) len = max - *w ;
    pos = siovec_bytechr(v, 2, sep) ;
    if (pos > len) pos = len ;
    r = pos < len ;
    buffer_getnofill(b, d + *w, pos + r) ; *w += pos ;
    if (*w >= max) return (errno = ERANGE, -1) ;
    if (r) return 1 ;
    r = buffer_fill(b) ;
    if (r <= 0) return r ;
  }
}