Skip to content

Commit 4d1a2a9

Browse files
committed
EventsHandler: Serialize events into asio::streambuf
Instead of serializing the events into a JSON `String` and transforming it into an Asio buffer, we can directly write the JSON into an Asio `streambuf` which can then directly be passed into the Asio stream.
1 parent cd15745 commit 4d1a2a9

File tree

2 files changed

+13
-12
lines changed

2 files changed

+13
-12
lines changed

lib/remote/eventshandler.cpp

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
#include "base/io-engine.hpp"
1010
#include "base/objectlock.hpp"
1111
#include "base/json.hpp"
12-
#include <boost/asio/buffer.hpp>
1312
#include <boost/asio/write.hpp>
1413
#include <boost/algorithm/string/replace.hpp>
14+
#include <boost/asio/streambuf.hpp>
1515
#include <map>
1616
#include <set>
1717

@@ -110,21 +110,18 @@ bool EventsHandler::HandleRequest(
110110
http::async_write(stream, response, yc);
111111
stream.async_flush(yc);
112112

113-
asio::const_buffer newLine ("\n", 1);
113+
asio::streambuf eventsBuf;
114+
std::ostream eventsOS(&eventsBuf);
114115

115116
for (;;) {
116-
auto event (subscriber.GetInbox()->Shift(yc));
117+
if (auto event(subscriber.GetInbox()->Shift(yc)); event) {
118+
JsonEncode(event, eventsOS);
119+
// Put a newline at the end of each event to render them on a separate line.
120+
eventsOS << '\n';
117121

118-
if (event) {
119-
String body = JsonEncode(event);
120-
121-
boost::algorithm::replace_all(body, "\n", "");
122-
123-
asio::const_buffer payload (body.CStr(), body.GetLength());
124-
125-
asio::async_write(stream, payload, yc);
126-
asio::async_write(stream, newLine, yc);
122+
asio::async_write(stream, eventsBuf, yc);
127123
stream.async_flush(yc);
124+
eventsBuf.consume(eventsBuf.size()); // Remove already sent data from the buffer.
128125
} else if (server.Disconnected()) {
129126
return true;
130127
}

test/base-json.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ BOOST_AUTO_TEST_CASE(encode)
4444
auto got(JsonEncode(input, true));
4545
BOOST_CHECK_MESSAGE(output == got, "expected=" << output << "\ngot=" << got);
4646

47+
std::ostringstream oss;
48+
JsonEncode(input, oss, true);
49+
BOOST_CHECK_MESSAGE(oss.str() == output, "expected=" << output << "\ngot=" << oss.str());
50+
4751
boost::algorithm::replace_all(output, " ", "");
4852
boost::algorithm::replace_all(output, "Objectoftype'Function'", "Object of type 'Function'");
4953
boost::algorithm::replace_all(output, "\n", "");

0 commit comments

Comments
 (0)