1 #include "stdio_impl.h"
9 static off_t mseek(FILE *f, off_t off, int whence)
12 struct cookie *c = f->cookie;
18 base = (size_t [3]){0, c->pos, c->len}[whence];
19 if (off < -base || off > (ssize_t)c->size-base) goto fail;
20 return c->pos = base+off;
23 static size_t mread(FILE *f, unsigned char *buf, size_t len)
25 struct cookie *c = f->cookie;
26 size_t rem = c->size - c->pos;
31 memcpy(buf, c->buf+c->pos, len);
34 if (rem > f->buf_size) rem = f->buf_size;
36 f->rend = f->buf + rem;
37 memcpy(f->rpos, c->buf+c->pos, rem);
42 static size_t mwrite(FILE *f, const unsigned char *buf, size_t len)
44 struct cookie *c = f->cookie;
46 size_t len2 = f->wpos - f->wbase;
49 if (mwrite(f, f->wpos, len2) < len2) return 0;
51 if (c->mode == 'a') c->pos = c->size;
52 rem = c->size - c->pos;
53 if (len > rem) len = rem;
54 memcpy(c->buf+c->pos, buf, len);
56 if (c->pos >= c->len) c->len = c->pos;
57 c->buf[c->len==c->size ? c->len-1 : c->len] = 0;
61 static int mclose(FILE *m)
66 FILE *fmemopen(void *buf, size_t size, const char *mode)
70 int plus = !!strchr(mode, '+');
72 if (!size || !strchr("rwa", *mode)) {
77 if (!buf && size > SIZE_MAX-sizeof(FILE)-BUFSIZ-UNGET) {
82 f = calloc(sizeof *f + sizeof *c + UNGET + BUFSIZ + (buf?0:size), 1);
84 f->cookie = c = (void *)(f+1);
87 f->buf = (unsigned char *)(c+1) + UNGET;
89 if (!buf) buf = f->buf + BUFSIZ;
95 if (!plus) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
96 if (*mode == 'r') c->len = size;
97 else if (*mode == 'a') c->len = c->pos = strnlen(buf, size);
104 if (!libc.threaded) {
106 f->next = libc.ofl_head;
107 if (libc.ofl_head) libc.ofl_head->prev = f;