added resize method to bufferstream

This commit is contained in:
Noel Berry 2021-05-06 20:47:52 -07:00
parent 5f9df4beee
commit 60f3939ff7
2 changed files with 27 additions and 15 deletions

View File

@ -19,6 +19,8 @@ namespace Blah
virtual bool is_readable() const override { return true; }
virtual bool is_writable() const override { return true; }
virtual void close() override;
void resize(i64 length);
void clear() { m_length = m_position = 0; }
char* data() { return m_buffer; }

View File

@ -1,4 +1,4 @@
#include <blah/streams/bufferstream.h>
#include "blah/streams/bufferstream.h"
#include <string.h>
using namespace Blah;
@ -64,13 +64,33 @@ i64 BufferStream::write_from(const void* ptr, i64 len)
return 0;
// resize
if (m_position + len >= m_capacity)
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(i64 length)
{
if (m_capacity > length)
{
m_length = length;
}
else
{
auto last_capacity = m_capacity;
if (m_capacity <= 0)
m_capacity = 16;
while (m_position + len >= m_capacity)
while (length >= m_capacity)
m_capacity *= 2;
char* new_buffer = new char[m_capacity];
@ -84,17 +104,7 @@ i64 BufferStream::write_from(const void* ptr, i64 len)
m_buffer = new_buffer;
}
// copy data
if (ptr != nullptr)
memcpy(m_buffer + m_position, ptr, (size_t)len);
// increment position
m_position += len;
if (m_position > m_length)
m_length = m_position;
// return the amount we wrote
return len;
m_length = length;
}
void BufferStream::close()