rbuffer: Enhance rbuffer_reset to work with filled RBuffers

This commit is contained in:
Thiago de Arruda
2015-09-27 11:58:54 -03:00
parent 0e4e69e52e
commit 394c0c4402
2 changed files with 16 additions and 4 deletions

View File

@@ -24,11 +24,13 @@ RBuffer *rbuffer_new(size_t capacity)
rv->size = 0; rv->size = 0;
rv->write_ptr = rv->read_ptr = rv->start_ptr; rv->write_ptr = rv->read_ptr = rv->start_ptr;
rv->end_ptr = rv->start_ptr + capacity; rv->end_ptr = rv->start_ptr + capacity;
rv->temp = NULL;
return rv; return rv;
} }
void rbuffer_free(RBuffer *buf) void rbuffer_free(RBuffer *buf)
{ {
xfree(buf->temp);
xfree(buf); xfree(buf);
} }
@@ -69,12 +71,20 @@ char *rbuffer_write_ptr(RBuffer *buf, size_t *write_count) FUNC_ATTR_NONNULL_ALL
return buf->write_ptr; return buf->write_ptr;
} }
// Set read and write pointer for an empty RBuffer to the beginning of the // Reset an RBuffer so read_ptr is at the beginning of the memory. If
// buffer. // necessary, this moves existing data by allocating temporary memory.
void rbuffer_reset(RBuffer *buf) FUNC_ATTR_NONNULL_ALL void rbuffer_reset(RBuffer *buf) FUNC_ATTR_NONNULL_ALL
{ {
if (buf->size == 0) { size_t temp_size;
buf->write_ptr = buf->read_ptr = buf->start_ptr; if ((temp_size = rbuffer_size(buf))) {
if (buf->temp == NULL) {
buf->temp = xmalloc(rbuffer_capacity(buf));
}
rbuffer_read(buf, buf->temp, buf->size);
}
buf->read_ptr = buf->write_ptr = buf->start_ptr;
if (temp_size) {
rbuffer_write(buf, buf->temp, temp_size);
} }
} }

View File

@@ -72,6 +72,8 @@ struct rbuffer {
rbuffer_callback full_cb, nonfull_cb; rbuffer_callback full_cb, nonfull_cb;
void *data; void *data;
size_t size; size_t size;
// helper memory used to by rbuffer_reset if required
char *temp;
char *end_ptr, *read_ptr, *write_ptr; char *end_ptr, *read_ptr, *write_ptr;
char start_ptr[]; char start_ptr[];
}; };