support linux kernel apis (new archs) with old syscalls removed
[oweals/musl.git] / src / stdio / getdelim.c
1 #include "stdio_impl.h"
2 #include <string.h>
3 #include <inttypes.h>
4 #include <errno.h>
5
6 #define MIN(a,b) ((a)<(b) ? (a) : (b))
7
8 ssize_t getdelim(char **restrict s, size_t *restrict n, int delim, FILE *restrict f)
9 {
10         char *tmp;
11         unsigned char *z;
12         size_t k;
13         size_t i=0;
14         int c;
15
16         if (!n || !s) {
17                 errno = EINVAL;
18                 return -1;
19         }
20
21         if (!*s) *n=0;
22
23         FLOCK(f);
24
25         for (;;) {
26                 z = memchr(f->rpos, delim, f->rend - f->rpos);
27                 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
28                 if (i+k >= *n) {
29                         if (k >= SIZE_MAX/2-i) goto oom;
30                         *n = i+k+2;
31                         if (*n < SIZE_MAX/4) *n *= 2;
32                         tmp = realloc(*s, *n);
33                         if (!tmp) {
34                                 *n = i+k+2;
35                                 tmp = realloc(*s, *n);
36                                 if (!tmp) goto oom;
37                         }
38                         *s = tmp;
39                 }
40                 memcpy(*s+i, f->rpos, k);
41                 f->rpos += k;
42                 i += k;
43                 if (z) break;
44                 if ((c = getc_unlocked(f)) == EOF) {
45                         if (!i || !feof(f)) {
46                                 FUNLOCK(f);
47                                 return -1;
48                         }
49                         break;
50                 }
51                 if (((*s)[i++] = c) == delim) break;
52         }
53         (*s)[i] = 0;
54
55         FUNLOCK(f);
56
57         return i;
58 oom:
59         FUNLOCK(f);
60         errno = ENOMEM;
61         return -1;
62 }
63
64 weak_alias(getdelim, __getdelim);