From 60f3939ff7b58dd1249de4bcbb57d9f13f40b24e Mon Sep 17 00:00:00 2001 From: Noel Berry Date: Thu, 6 May 2021 20:47:52 -0700 Subject: [PATCH] added resize method to bufferstream --- include/blah/streams/bufferstream.h | 2 ++ src/streams/bufferstream.cpp | 40 ++++++++++++++++++----------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/include/blah/streams/bufferstream.h b/include/blah/streams/bufferstream.h index 3cf5965..d2d03b3 100644 --- a/include/blah/streams/bufferstream.h +++ b/include/blah/streams/bufferstream.h @@ -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; } diff --git a/src/streams/bufferstream.cpp b/src/streams/bufferstream.cpp index 92c35e9..284f806 100644 --- a/src/streams/bufferstream.cpp +++ b/src/streams/bufferstream.cpp @@ -1,4 +1,4 @@ -#include +#include "blah/streams/bufferstream.h" #include using namespace Blah; @@ -64,17 +64,37 @@ 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]; - + if (m_buffer != nullptr) { memcpy(new_buffer, m_buffer, last_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()