1
0

open_memstream.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "stdio_impl.h"
  2. #include <errno.h>
  3. #include <limits.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include "libc.h"
  7. struct cookie {
  8. char **bufp;
  9. size_t *sizep;
  10. size_t pos;
  11. char *buf;
  12. size_t len;
  13. size_t space;
  14. };
  15. struct ms_FILE {
  16. FILE f;
  17. struct cookie c;
  18. unsigned char buf[BUFSIZ];
  19. };
  20. static off_t ms_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-base) goto fail;
  31. return c->pos = base+off;
  32. }
  33. static size_t ms_write(FILE *f, const unsigned char *buf, size_t len)
  34. {
  35. struct cookie *c = f->cookie;
  36. size_t len2 = f->wpos - f->wbase;
  37. char *newbuf;
  38. if (len2) {
  39. f->wpos = f->wbase;
  40. if (ms_write(f, f->wbase, len2) < len2) return 0;
  41. }
  42. if (len + c->pos >= c->space) {
  43. len2 = 2*c->space+1 | c->pos+len+1;
  44. newbuf = realloc(c->buf, len2);
  45. if (!newbuf) return 0;
  46. *c->bufp = c->buf = newbuf;
  47. memset(c->buf + c->space, 0, len2 - c->space);
  48. c->space = len2;
  49. }
  50. memcpy(c->buf+c->pos, buf, len);
  51. c->pos += len;
  52. if (c->pos >= c->len) c->len = c->pos;
  53. *c->sizep = c->pos;
  54. return len;
  55. }
  56. static int ms_close(FILE *f)
  57. {
  58. return 0;
  59. }
  60. FILE *open_memstream(char **bufp, size_t *sizep)
  61. {
  62. struct ms_FILE *f;
  63. char *buf;
  64. if (!(f=malloc(sizeof *f))) return 0;
  65. if (!(buf=malloc(sizeof *buf))) {
  66. free(f);
  67. return 0;
  68. }
  69. memset(&f->f, 0, sizeof f->f);
  70. memset(&f->c, 0, sizeof f->c);
  71. f->f.cookie = &f->c;
  72. f->c.bufp = bufp;
  73. f->c.sizep = sizep;
  74. f->c.pos = f->c.len = f->c.space = *sizep = 0;
  75. f->c.buf = *bufp = buf;
  76. *buf = 0;
  77. f->f.flags = F_NORD;
  78. f->f.fd = -1;
  79. f->f.buf = f->buf;
  80. f->f.buf_size = sizeof f->buf;
  81. f->f.lbf = EOF;
  82. f->f.write = ms_write;
  83. f->f.seek = ms_seek;
  84. f->f.close = ms_close;
  85. f->f.mode = -1;
  86. if (!libc.threaded) f->f.lock = -1;
  87. return __ofl_add(&f->f);
  88. }