Skip to content

Commit

Permalink
Add maxCapacity constructor parameter to MemoryDataStream
Browse files Browse the repository at this point in the history
  • Loading branch information
mikee47 committed Dec 8, 2020
1 parent 215c1f7 commit d237a51
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
5 changes: 5 additions & 0 deletions Sming/Core/Data/Stream/MemoryDataStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}

Expand Down
13 changes: 8 additions & 5 deletions Sming/Core/Data/Stream/MemoryDataStream.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
};
4 changes: 3 additions & 1 deletion Sming/Wiring/FIFO.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ template <typename T, int rawSize> bool FIFO<T, rawSize>::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;
}

Expand Down

0 comments on commit d237a51

Please sign in to comment.