blah/src/streams/bufferstream.cpp

117 lines
2.1 KiB
C++
Raw Normal View History

2021-05-07 11:47:52 +08:00
#include "blah/streams/bufferstream.h"
2020-08-26 15:38:01 +08:00
#include <string.h>
using namespace Blah;
BufferStream::BufferStream()
: m_buffer(nullptr), m_capacity(0), m_length(0), m_position(0) {}
2020-08-26 15:38:01 +08:00
BufferStream::BufferStream(int capacity)
: m_buffer(nullptr), m_capacity(0), m_length(0), m_position(0)
2020-08-26 15:38:01 +08:00
{
if (capacity > 0)
{
m_buffer = new char[capacity];
m_capacity = capacity;
}
}
BufferStream::BufferStream(BufferStream&& src) noexcept
{
m_buffer = src.m_buffer;
m_length = src.m_length;
m_capacity = src.m_capacity;
m_position = src.m_position;
src.m_buffer = nullptr;
src.m_position = src.m_length = src.m_capacity = 0;
}
BufferStream& BufferStream::operator=(BufferStream&& src) noexcept
{
m_buffer = src.m_buffer;
m_length = src.m_length;
m_capacity = src.m_capacity;
m_position = src.m_position;
src.m_buffer = nullptr;
src.m_position = src.m_length = src.m_capacity = 0;
return *this;
}
BufferStream::~BufferStream()
{
delete[] m_buffer;
}
size_t BufferStream::read_into(void* ptr, size_t len)
2020-08-26 15:38:01 +08:00
{
if (m_buffer == nullptr || ptr == nullptr)
return 0;
if (len < 0)
return 0;
if (len > m_length - m_position)
len = m_length - m_position;
memcpy(ptr, m_buffer + m_position, (size_t)len);
m_position += len;
return len;
}
size_t BufferStream::write_from(const void* ptr, size_t len)
2020-08-26 15:38:01 +08:00
{
if (len < 0)
return 0;
// resize
2021-05-07 11:47:52 +08:00
if (m_position + len > m_length)
resize(m_position + len);
// copy data
if (ptr != nullptr)
memcpy(m_buffer + m_position, ptr, (size_t)len);
// increment position
m_position += len;
// return the amount we wrote
return len;
}
void BufferStream::resize(size_t length)
2021-05-07 11:47:52 +08:00
{
if (m_capacity > length)
{
m_length = length;
}
else
2020-08-26 15:38:01 +08:00
{
auto last_capacity = m_capacity;
if (m_capacity <= 0)
m_capacity = 16;
2021-05-07 11:47:52 +08:00
while (length >= m_capacity)
2020-08-26 15:38:01 +08:00
m_capacity *= 2;
char* new_buffer = new char[m_capacity];
2021-05-07 11:47:52 +08:00
2020-08-26 15:38:01 +08:00
if (m_buffer != nullptr)
{
memcpy(new_buffer, m_buffer, last_capacity);
delete[] m_buffer;
}
m_buffer = new_buffer;
}
2021-05-07 11:47:52 +08:00
m_length = length;
2020-08-26 15:38:01 +08:00
}
void BufferStream::close()
{
delete[] m_buffer;
m_buffer = nullptr;
m_position = 0;
m_length = 0;
m_capacity = 0;
}