mirror of
https://github.com/fluencelabs/musl
synced 2025-06-16 00:11:36 +00:00
clean up allocation/setup logic for fmemopen
rather than manually performing pointer arithmetic to carve multiple objects out of one allocation, use a containing struct that encompasses them all.
This commit is contained in:
@ -9,6 +9,12 @@ struct cookie {
|
|||||||
int mode;
|
int mode;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
struct mem_FILE {
|
||||||
|
FILE f;
|
||||||
|
struct cookie c;
|
||||||
|
unsigned char buf[UNGET+BUFSIZ], buf2[];
|
||||||
|
};
|
||||||
|
|
||||||
static off_t mseek(FILE *f, off_t off, int whence)
|
static off_t mseek(FILE *f, off_t off, int whence)
|
||||||
{
|
{
|
||||||
ssize_t base;
|
ssize_t base;
|
||||||
@ -72,8 +78,7 @@ static int mclose(FILE *m)
|
|||||||
|
|
||||||
FILE *fmemopen(void *restrict buf, size_t size, const char *restrict mode)
|
FILE *fmemopen(void *restrict buf, size_t size, const char *restrict mode)
|
||||||
{
|
{
|
||||||
FILE *f;
|
struct mem_FILE *f;
|
||||||
struct cookie *c;
|
|
||||||
int plus = !!strchr(mode, '+');
|
int plus = !!strchr(mode, '+');
|
||||||
|
|
||||||
if (!size || !strchr("rwa", *mode)) {
|
if (!size || !strchr("rwa", *mode)) {
|
||||||
@ -86,29 +91,34 @@ FILE *fmemopen(void *restrict buf, size_t size, const char *restrict mode)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
f = calloc(sizeof *f + sizeof *c + UNGET + BUFSIZ + (buf?0:size), 1);
|
f = malloc(sizeof *f + (buf?0:size));
|
||||||
if (!f) return 0;
|
if (!f) return 0;
|
||||||
f->cookie = c = (void *)(f+1);
|
memset(&f->f, 0, sizeof f->f);
|
||||||
f->fd = -1;
|
f->f.cookie = &f->c;
|
||||||
f->lbf = EOF;
|
f->f.fd = -1;
|
||||||
f->buf = (unsigned char *)(c+1) + UNGET;
|
f->f.lbf = EOF;
|
||||||
f->buf_size = BUFSIZ;
|
f->f.buf = f->buf + UNGET;
|
||||||
if (!buf) buf = f->buf + BUFSIZ;
|
f->f.buf_size = sizeof f->buf - UNGET;
|
||||||
|
if (!buf) {
|
||||||
c->buf = buf;
|
buf = f->buf2;;
|
||||||
c->size = size;
|
memset(buf, 0, size);
|
||||||
c->mode = *mode;
|
}
|
||||||
|
|
||||||
if (!plus) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
|
memset(&f->c, 0, sizeof f->c);
|
||||||
if (*mode == 'r') c->len = size;
|
f->c.buf = buf;
|
||||||
else if (*mode == 'a') c->len = c->pos = strnlen(buf, size);
|
f->c.size = size;
|
||||||
|
f->c.mode = *mode;
|
||||||
f->read = mread;
|
|
||||||
f->write = mwrite;
|
if (!plus) f->f.flags = (*mode == 'r') ? F_NOWR : F_NORD;
|
||||||
f->seek = mseek;
|
if (*mode == 'r') f->c.len = size;
|
||||||
f->close = mclose;
|
else if (*mode == 'a') f->c.len = f->c.pos = strnlen(buf, size);
|
||||||
|
|
||||||
if (!libc.threaded) f->lock = -1;
|
f->f.read = mread;
|
||||||
|
f->f.write = mwrite;
|
||||||
return __ofl_add(f);
|
f->f.seek = mseek;
|
||||||
|
f->f.close = mclose;
|
||||||
|
|
||||||
|
if (!libc.threaded) f->f.lock = -1;
|
||||||
|
|
||||||
|
return __ofl_add(&f->f);
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user