github.com/afumu/libc@v0.0.6/musl/src/stdio/open_wmemstream.c (about) 1 #include "stdio_impl.h" 2 #include <wchar.h> 3 #include <errno.h> 4 #include <limits.h> 5 #include <string.h> 6 #include <stdlib.h> 7 #include "libc.h" 8 9 struct cookie { 10 wchar_t **bufp; 11 size_t *sizep; 12 size_t pos; 13 wchar_t *buf; 14 size_t len; 15 size_t space; 16 mbstate_t mbs; 17 }; 18 19 struct wms_FILE { 20 FILE f; 21 struct cookie c; 22 unsigned char buf[1]; 23 }; 24 25 static off_t wms_seek(FILE *f, off_t off, int whence) 26 { 27 ssize_t base; 28 struct cookie *c = f->cookie; 29 if (whence>2U) { 30 fail: 31 errno = EINVAL; 32 return -1; 33 } 34 base = (size_t [3]){0, c->pos, c->len}[whence]; 35 if (off < -base || off > SSIZE_MAX/4-base) goto fail; 36 memset(&c->mbs, 0, sizeof c->mbs); 37 return c->pos = base+off; 38 } 39 40 static size_t wms_write(FILE *f, const unsigned char *buf, size_t len) 41 { 42 struct cookie *c = f->cookie; 43 size_t len2; 44 wchar_t *newbuf; 45 if (len + c->pos >= c->space) { 46 len2 = 2*c->space+1 | c->pos+len+1; 47 if (len2 > SSIZE_MAX/4) return 0; 48 newbuf = realloc(c->buf, len2*4); 49 if (!newbuf) return 0; 50 *c->bufp = c->buf = newbuf; 51 memset(c->buf + c->space, 0, 4*(len2 - c->space)); 52 c->space = len2; 53 } 54 55 len2 = mbsnrtowcs(c->buf+c->pos, (void *)&buf, len, c->space-c->pos, &c->mbs); 56 if (len2 == -1) return 0; 57 c->pos += len2; 58 if (c->pos >= c->len) c->len = c->pos; 59 *c->sizep = c->pos; 60 return len; 61 } 62 63 static int wms_close(FILE *f) 64 { 65 return 0; 66 } 67 68 FILE *open_wmemstream(wchar_t **bufp, size_t *sizep) 69 { 70 struct wms_FILE *f; 71 wchar_t *buf; 72 73 if (!(f=malloc(sizeof *f))) return 0; 74 if (!(buf=malloc(sizeof *buf))) { 75 free(f); 76 return 0; 77 } 78 memset(&f->f, 0, sizeof f->f); 79 memset(&f->c, 0, sizeof f->c); 80 f->f.cookie = &f->c; 81 82 f->c.bufp = bufp; 83 f->c.sizep = sizep; 84 f->c.pos = f->c.len = f->c.space = *sizep = 0; 85 f->c.buf = *bufp = buf; 86 *buf = 0; 87 88 f->f.flags = F_NORD; 89 f->f.fd = -1; 90 f->f.buf = f->buf; 91 f->f.buf_size = 0; 92 f->f.lbf = EOF; 93 f->f.write = wms_write; 94 f->f.seek = wms_seek; 95 f->f.close = wms_close; 96 97 if (!libc.threaded) f->f.lock = -1; 98 99 fwide(&f->f, 1); 100 101 return __ofl_add(&f->f); 102 }