Update StringBuffer to support partial reads test case.

Per #115, `ContentReader::match` must block until the whole pattern is
read or the underlying `Reader` is closed. The previous commit reverted
the change from #50 to ensure this behavior is still implemented.

This commit re-adds the unit test from #50 with an update to the
behavior of `StringBuffer` to correct implement `Reader` so that
the partial read test case is still covered by the unit tests.
This commit is contained in:
Dan McNulty 2023-07-05 11:29:39 -05:00 committed by Ben Clayton
parent 8399fbae7f
commit 93d94a7d85
2 changed files with 26 additions and 3 deletions

View File

@ -81,3 +81,16 @@ TEST(ContentStreamTest, ShortRead) {
ASSERT_EQ(cs.read(), "Content payload number three");
ASSERT_EQ(cs.read(), "");
}
TEST(ContentStreamTest, PartialReadAndParse) {
auto sb = std::make_shared<dap::StringBuffer>();
sb->write("Content");
sb->write("-Length: ");
sb->write("26");
sb->write("\r\n\r\n");
sb->write("Content payload number one");
dap::ContentReader cs(sb);
ASSERT_EQ(cs.read(), "Content payload number one");
ASSERT_EQ(cs.read(), "");
}

View File

@ -19,7 +19,8 @@
#include <algorithm> // std::min
#include <cstring> // memcpy
#include <memory> // std::unique_ptr
#include <deque>
#include <memory> // std::unique_ptr
#include <string>
namespace dap {
@ -39,6 +40,7 @@ class StringBuffer : public virtual Reader, public virtual Writer {
private:
std::string str;
std::deque<size_t> chunk_lengths;
bool closed = false;
};
@ -62,12 +64,19 @@ std::string StringBuffer::string() const {
}
size_t StringBuffer::read(void* buffer, size_t bytes) {
if (closed || bytes == 0 || str.size() == 0) {
if (closed || bytes == 0 || str.size() == 0 || chunk_lengths.size() == 0) {
return 0;
}
auto len = std::min(bytes, str.size());
size_t& chunk_length = chunk_lengths.front();
auto len = std::min(bytes, chunk_length);
memcpy(buffer, str.data(), len);
str = std::string(str.begin() + len, str.end());
if (bytes < chunk_length) {
chunk_length -= bytes;
} else {
chunk_lengths.pop_front();
}
return len;
}
@ -77,6 +86,7 @@ bool StringBuffer::write(const void* buffer, size_t bytes) {
}
auto chars = reinterpret_cast<const char*>(buffer);
str.append(chars, chars + bytes);
chunk_lengths.push_back(bytes);
return true;
}