diff --git a/Sming/Core/Data/Stream/MemoryDataStream.cpp b/Sming/Core/Data/Stream/MemoryDataStream.cpp index 88f26fcaea..03d700ff0a 100644 --- a/Sming/Core/Data/Stream/MemoryDataStream.cpp +++ b/Sming/Core/Data/Stream/MemoryDataStream.cpp @@ -21,6 +21,10 @@ MemoryDataStream::MemoryDataStream(String&& string) noexcept bool MemoryDataStream::ensureCapacity(size_t minCapacity) { if(capacity < minCapacity) { + if(minCapacity > maxCapacity) { + debug_e("MemoryDataStream too large, requested %u limit is %u", minCapacity, maxCapacity); + return false; + } size_t newCapacity = minCapacity; if(capacity != 0) { // If expanding stream, increase buffer capacity in anticipation of further writes @@ -30,6 +34,7 @@ bool MemoryDataStream::ensureCapacity(size_t minCapacity) // realloc can fail, store the result in temporary pointer auto newBuffer = (char*)realloc(buffer, newCapacity); if(newBuffer == nullptr) { + debug_e("MemoryDataStream realloc(%u) failed", newCapacity); return false; } diff --git a/Sming/Core/Data/Stream/MemoryDataStream.h b/Sming/Core/Data/Stream/MemoryDataStream.h index f8e7016df1..75a1f06607 100644 --- a/Sming/Core/Data/Stream/MemoryDataStream.h +++ b/Sming/Core/Data/Stream/MemoryDataStream.h @@ -26,7 +26,9 @@ class MemoryDataStream : public ReadWriteStream { public: - MemoryDataStream() = default; + MemoryDataStream(size_t maxCapacity = UINT16_MAX) : maxCapacity(maxCapacity) + { + } /** * @brief Stream takes ownership of String content using move semantics @@ -103,8 +105,9 @@ class MemoryDataStream : public ReadWriteStream } private: - char* buffer = nullptr; ///< Stream content stored here - size_t readPos = 0; ///< Offset to current read position - size_t size = 0; ///< Number of bytes stored in stream (i.e. the write position) - size_t capacity = 0; ///< Number of bytes allocated in buffer + char* buffer = nullptr; ///< Stream content stored here + size_t maxCapacity{UINT16_MAX}; ///< Limit size of stream + size_t readPos = 0; ///< Offset to current read position + size_t size = 0; ///< Number of bytes stored in stream (i.e. the write position) + size_t capacity = 0; ///< Number of bytes allocated in buffer }; diff --git a/Sming/Wiring/FIFO.h b/Sming/Wiring/FIFO.h index 2ea887d19c..a86a35d9a9 100644 --- a/Sming/Wiring/FIFO.h +++ b/Sming/Wiring/FIFO.h @@ -73,8 +73,10 @@ template bool FIFO::enqueue(T element) } numberOfElements++; raw[nextIn] = element; - if(++nextIn >= rawSize) // advance to next index, wrap if needed + // advance to next index, wrap if needed + if(++nextIn >= rawSize) { nextIn = 0; + } return true; }