#include "../../include/std/buffer.h" #include #include #include #include void tsl_buffer_init(TslBuffer *self) { self->data = NULL; self->size = 0; self->capacity = 0; } void tsl_buffer_deinit(TslBuffer *self) { free(self->data); } static int tsl_buffer_ensure_capacity(TslBuffer *self, size_t new_size) { void *new_ptr; if(new_size <= self->capacity) return 1; if(self->capacity != 0) { size_t new_capacity = self->capacity; while(new_capacity < new_size) { new_capacity <<= 1; } new_size = new_capacity; } new_ptr = realloc(self->data, new_size); if(!new_ptr) { fprintf(stderr, "Error: buffer append failed. Reason: out of memory\n"); return 0; } self->data = new_ptr; self->capacity = new_size; return 1; } int tsl_buffer_append(TslBuffer *self, const void *data, size_t size) { if(!tsl_buffer_ensure_capacity(self, self->size + size)) return 0; memcpy((char*)self->data + self->size, data, size); self->size += size; return 1; } void tsl_buffer_pop(TslBuffer *self, size_t size) { assert(self->size >= size); self->size -= size; } void* tsl_buffer_begin(TslBuffer *self) { return self->data; } void* tsl_buffer_end(TslBuffer *self) { return (char*)self->data + self->size; }