open_wmemstream.c 1.9 KB

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