1 #include "stdio_impl.h"
15 static off_t ms_seek(FILE *f, off_t off, int whence)
18 struct cookie *c = f->cookie;
24 base = (size_t [3]){0, c->pos, c->len}[whence];
25 if (off < -base || off > SSIZE_MAX-base) goto fail;
26 return c->pos = base+off;
29 static size_t ms_write(FILE *f, const unsigned char *buf, size_t len)
31 struct cookie *c = f->cookie;
32 size_t len2 = f->wpos - f->wbase;
36 if (ms_write(f, f->wbase, len2) < len2) return 0;
38 if (len + c->pos >= c->space) {
39 len2 = 2*c->space+1 | c->pos+len+1;
40 newbuf = realloc(c->buf, len2);
41 if (!newbuf) return 0;
42 *c->bufp = c->buf = newbuf;
43 memset(c->buf + c->space, 0, len2 - c->space);
46 memcpy(c->buf+c->pos, buf, len);
48 if (c->pos >= c->len) c->len = c->pos;
53 static int ms_close(FILE *f)
58 FILE *open_memstream(char **bufp, size_t *sizep)
64 if (!(f=malloc(sizeof *f + sizeof *c + BUFSIZ))) return 0;
65 if (!(buf=malloc(sizeof *buf))) {
69 memset(f, 0, sizeof *f + sizeof *c);
70 f->cookie = c = (void *)(f+1);
74 c->pos = c->len = c->space = *sizep = 0;
80 f->buf = (void *)(c+1);
87 if (!libc.threaded) f->lock = -1;