#include "buffer.h" #include "alloc.h" #include #include #include void buffer_init(Buffer *self) { self->data = NULL; self->size = 0; self->capacity = 0; } void buffer_deinit(Buffer *self) { free(self->data); self->data = NULL; self->size = 0; self->capacity = 0; } static void buffer_ensure_capacity(Buffer *self, size_t new_size) { size_t new_capacity = self->capacity; if(new_size <= self->capacity) return; if(new_capacity == 0) new_capacity = 8; while(new_capacity < new_size) { /* new_capacity *= 1.5 */ new_capacity += (new_capacity >> 1); } self->data = realloc_or_crash(self->data, new_capacity); self->capacity = new_capacity; } void buffer_append(Buffer *self, const void *data, size_t size) { buffer_ensure_capacity(self, self->size + size); memcpy((char*)self->data + self->size, data, size); self->size += size; } void* buffer_pop(Buffer *self, size_t size) { assert(self->size >= size); self->size -= size; return (char*)self->data + self->size; } void* buffer_begin(Buffer *self) { return self->data; } void* buffer_end(Buffer *self) { return (char*)self->data + self->size; } size_t buffer_get_size(Buffer *self, size_t type_size) { return self->size / type_size; } void buffer_clear(Buffer *self) { self->size = 0; }