]>
git.proxmox.com Git - wasi-libc.git/blob - libc-top-half/musl/src/stdio/open_memstream.c
600d27705bf526e696c437845fd4844a8716c30e
1 #include "stdio_impl.h"
20 unsigned char buf
[BUFSIZ
];
23 static off_t
ms_seek(FILE *f
, off_t off
, int whence
)
26 struct cookie
*c
= f
->cookie
;
32 base
= (size_t [3]){0, c
->pos
, c
->len
}[whence
];
33 if (off
< -base
|| off
> SSIZE_MAX
-base
) goto fail
;
34 return c
->pos
= base
+off
;
37 static size_t ms_write(FILE *f
, const unsigned char *buf
, size_t len
)
39 struct cookie
*c
= f
->cookie
;
40 size_t len2
= f
->wpos
- f
->wbase
;
44 if (ms_write(f
, f
->wbase
, len2
) < len2
) return 0;
46 if (len
+ c
->pos
>= c
->space
) {
47 len2
= 2*c
->space
+1 | c
->pos
+len
+1;
48 newbuf
= realloc(c
->buf
, len2
);
49 if (!newbuf
) return 0;
50 *c
->bufp
= c
->buf
= newbuf
;
51 memset(c
->buf
+ c
->space
, 0, len2
- c
->space
);
54 memcpy(c
->buf
+c
->pos
, buf
, len
);
56 if (c
->pos
>= c
->len
) c
->len
= c
->pos
;
61 static int ms_close(FILE *f
)
66 FILE *open_memstream(char **bufp
, size_t *sizep
)
71 if (!(f
=malloc(sizeof *f
))) return 0;
72 if (!(buf
=malloc(sizeof *buf
))) {
76 memset(&f
->f
, 0, sizeof f
->f
);
77 memset(&f
->c
, 0, sizeof f
->c
);
82 f
->c
.pos
= f
->c
.len
= f
->c
.space
= *sizep
= 0;
83 f
->c
.buf
= *bufp
= buf
;
89 f
->f
.buf_size
= sizeof f
->buf
;
91 f
->f
.write
= ms_write
;
93 f
->f
.close
= ms_close
;
96 if (!libc
.threaded
) f
->f
.lock
= -1;
98 return __ofl_add(&f
->f
);