Esempio n. 1
0
static fpos_t memstream_seek(void *cookie, fpos_t offset, int whence) {
    struct memstream *ms = (struct memstream *)cookie;
    fpos_t pos = 0;
    memstream_check(ms);
    memstream_info(("memstream_seek %p %i %i\n", ms, (int)offset, whence));
    switch (whence) {
    case SEEK_SET:
        pos = offset;
        break;
    case SEEK_CUR:
        pos = ms->position + offset;
        break;
    case SEEK_END:
        pos = ms->size + offset;
        break;
    default:
        errno = EINVAL;
        return -1;
    }
    if (pos >= ms->capacity)
        memstream_grow(ms, pos);
    ms->position = pos;
    if (ms->size < ms->position)
        *ms->sizeloc = ms->size = ms->position;
    memstream_print(ms);
    memstream_info(("=> %i\n", (int)pos));
    assert(ms->size < ms->capacity && ms->contents[ms->size] == 0);
    return pos;
}
Esempio n. 2
0
static int memstream_read(void *cookie, char *buf, int count)
{
    struct memstream *ms= (struct memstream *)cookie;			memstream_check(ms);
    int n= min(ms->size - ms->position, count);				memstream_info(("memstream_read %p %i\n", ms, count));
    if (n < 1) return 0;
    memcpy(buf, ms->contents, n);
    ms->position += n;							memstream_print(ms);
    return n;
}
Esempio n. 3
0
static int memstream_grow(struct memstream *ms, int minsize)
{
    int newcap= ms->capacity * 2;					memstream_check(ms);
    while (newcap <= minsize) newcap *= 2;				memstream_info(("grow %p to %i\n", ms, newcap));
    ms->contents= realloc(ms->contents, newcap);
    if (!ms->contents) return -1;	/* errno == ENOMEM */
    memset(ms->contents + ms->capacity, 0, newcap - ms->capacity);
    ms->capacity= newcap;
    *ms->ptr= ms->contents;		/* size has not changed */
    return 0;
}
Esempio n. 4
0
static int memstream_write(void *cookie, const char *buf, int count)
{
    struct memstream *ms= (struct memstream *)cookie;			memstream_check(ms);
    if (ms->capacity <= ms->position + count)
	if (memstream_grow(ms, ms->position + count) < 0)		/* errno == ENOMEM */
	    return -1;
    memcpy(ms->contents + ms->position, buf, count);			memstream_info(("memstream_write %p %i\n", ms, count));
    ms->position += count;
    if (ms->size < ms->position) *ms->sizeloc= ms->size= ms->position;	memstream_print(ms);
									assert(ms->size < ms->capacity);
									assert(ms->contents[ms->size] == 0);
    return count;
}