#include #include #include #include #include "memory.h" #include "buffer.h" struct buffer buffer_make(size_t capacity) { struct buffer buffer = (struct buffer){malloc(capacity, char), capacity + 1, 0}; return buffer; } void buffer_free(struct buffer buffer) { free(buffer.buf); } void buffer_append_mem(struct buffer *buffer, const char *str, size_t len) { if (buffer->len + len >= buffer->cap) { do buffer->cap *= 2; while (buffer->len + len >= buffer->cap); buffer->buf = realloc(buffer->buf, buffer->cap, char); } memcpy(buffer->buf + buffer->len, str, len); buffer->len += len; buffer->buf[buffer->len] = 0; } void buffer_append_str(struct buffer *buffer, const char *str) { buffer_append_mem(buffer, str, strlen(str)); } // returns whether successful bool buffer_append_file(struct buffer *buffer, const char *path) { FILE *f = fopen(path, "rb"); if (!f) return false; char block[4096]; while (true) { size_t nr = fread(block, 1, sizeof block, f); if (nr > 0) buffer_append_mem(buffer, block, nr); if (nr < sizeof block) break; } bool has_error = ferror(f); fclose(f); return !has_error; }