open_wmemstream.c 1.9 KB

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