made buffer more robust and supports unsigned char buffers

This commit is contained in:
Luna 2025-07-06 14:27:25 +02:00
parent 35c95790ed
commit 238f9a9b97
2 changed files with 81 additions and 0 deletions

View file

@ -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;
}

View file

@ -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);
}
};