From a145f337c0d7fab373179f95e57745128c961a7e Mon Sep 17 00:00:00 2001 From: Jack Andersen Date: Sun, 23 Aug 2015 13:52:01 -1000 Subject: [PATCH] Added ownership flag for memory reader --- include/Athena/MemoryReader.hpp | 9 +++++++-- src/Athena/MemoryReader.cpp | 18 ++++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/include/Athena/MemoryReader.hpp b/include/Athena/MemoryReader.hpp index 1fdf46e..6b87d18 100644 --- a/include/Athena/MemoryReader.hpp +++ b/include/Athena/MemoryReader.hpp @@ -21,12 +21,15 @@ namespace io class MemoryReader : public IStreamReader { public: + virtual ~MemoryReader(); + /*! \brief This constructor references an existing buffer to read from. * * \param data The existing buffer * \param length The length of the existing buffer + * \param takeOwnership Memory will be freed with the reader if set */ - MemoryReader(const atUint8* data, atUint64 length); + MemoryReader(const atUint8* data, atUint64 length, bool takeOwnership=false); /*! \brief Sets the buffers position relative to the specified position.
* It seeks relative to the current position by default. @@ -57,9 +60,10 @@ public: * as Stream now owns the address, this is done to keep memory usage down. * \param data The new buffer. * \param length The length of the new buffer. + * \param takeOwnership Memory will be freed with the reader if set * \throw IOException */ - void setData(const atUint8* data, atUint64 length); + void setData(const atUint8* data, atUint64 length, bool takeOwnership=false); /*! \brief Returns a copy of the current buffer.
@@ -82,6 +86,7 @@ protected: const atUint8* m_data; atUint64 m_length; atUint64 m_position; + bool m_owns; }; class MemoryCopyReader : public MemoryReader diff --git a/src/Athena/MemoryReader.cpp b/src/Athena/MemoryReader.cpp index 5968ee9..6cb9ad6 100644 --- a/src/Athena/MemoryReader.cpp +++ b/src/Athena/MemoryReader.cpp @@ -14,10 +14,11 @@ namespace Athena { namespace io { -MemoryReader::MemoryReader(const atUint8* data, atUint64 length) +MemoryReader::MemoryReader(const atUint8* data, atUint64 length, bool takeOwnership) : m_data(data), m_length(length), - m_position(0) + m_position(0), + m_owns(takeOwnership) { if (!data) { @@ -34,8 +35,14 @@ MemoryReader::MemoryReader(const atUint8* data, atUint64 length) } } +MemoryReader::~MemoryReader() +{ + if (m_owns) + delete[] m_data; +} + MemoryCopyReader::MemoryCopyReader(const atUint8* data, atUint64 length) - : MemoryReader(data, length) + : MemoryReader(data, length, false) { if (!data) { @@ -95,11 +102,14 @@ void MemoryReader::seek(atInt64 position, SeekOrigin origin) } } -void MemoryReader::setData(const atUint8* data, atUint64 length) +void MemoryReader::setData(const atUint8* data, atUint64 length, bool takeOwnership) { + if (m_owns && m_data) + delete[] m_data; m_data = (atUint8*)data; m_length = length; m_position = 0; + m_owns = takeOwnership; } void MemoryCopyReader::setData(const atUint8* data, atUint64 length)