From 238f9a9b975ab97195b0982a08c8939e4eee2251 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 6 Jul 2025 14:27:25 +0200 Subject: [PATCH] made buffer more robust and supports unsigned char buffers --- src/buffer.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/buffer.h | 18 +++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/src/buffer.cpp b/src/buffer.cpp index d502600..0f14559 100644 --- a/src/buffer.cpp +++ b/src/buffer.cpp @@ -21,6 +21,10 @@ void buffer::remove(int offset, int remove_size) if (offset + remove_size > size) return ; char *new_data = (char *)calloc(allocated, sizeof(char)); + if (!new_data) + { + throw std::runtime_error("Allocation failed"); + } if (offset > 0) { std::memcpy(new_data, data, offset); @@ -30,4 +34,63 @@ void buffer::remove(int offset, int remove_size) free(data); data = new_data; size = new_size; + allocations++; +} + +void buffer::allocate(size_t s) +{ + data = (char *)realloc(data, allocated + s); + if (!data) + { + throw std::runtime_error("Allocation failed"); + } + allocated += s; +} + +void buffer_unsigned::write(unsigned char *data_in, size_t data_size) +{ + if (data_size > allocated - size) + { + allocated += (size + data_size) + BUFFER_SIZE; + data = (unsigned char *)realloc(data, allocated); + allocations++; + if (!data) + { + throw std::runtime_error("Allocation failed"); + } + } + std::memcpy(&data[size], data_in, data_size); + size += data_size; +} + +void buffer_unsigned::remove(int offset, int remove_size) +{ + if (offset + remove_size > size) + return ; + unsigned char *new_data = (unsigned char *)calloc(allocated, sizeof(char)); + if (!new_data) + { + throw std::runtime_error("Allocation failed"); + } + if (offset > 0) + { + std::memcpy(new_data, data, offset); + } + int new_size = size - remove_size; + std::memcpy(&new_data[offset], &data[offset + remove_size], new_size - offset); + free(data); + data = new_data; + size = new_size; + allocations++; +} + +void buffer_unsigned::allocate(size_t s) +{ + data = (unsigned char *)realloc(data, allocated + s); + if (!data) + { + throw std::runtime_error("Allocation failed"); + } + allocations++; + allocated += s; } diff --git a/src/buffer.h b/src/buffer.h index 4ecb324..9fbce09 100644 --- a/src/buffer.h +++ b/src/buffer.h @@ -13,9 +13,27 @@ struct buffer void write(char *data_in, size_t data_size); void remove(int offset, int remove_size); + void allocate(size_t s); ~buffer() { free(data); } }; + +struct buffer_unsigned +{ + unsigned char *data; + size_t size; + size_t allocated; + int allocations; + + void write(unsigned char *data_in, size_t data_size); + void remove(int offset, int remove_size); + void allocate(size_t s); + + ~buffer_unsigned() + { + free(data); + } +};