1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 13:27:35 +00:00

LibCore+Userland+Tests: Convert Stream APIs to construct on heap

As per previous discussion, it was decided that the Stream classes
should be constructed on the heap.

While I don't personally agree with this change, it does have the
benefit of avoiding Function object reconstructions due to the lambda
passed to Notifier pointing to a stale object reference. This also has
the benefit of not having to "box" objects for virtual usage, as the
objects come pre-boxed.

However, it means that we now hit the heap everytime we construct a
TCPSocket for instance, which might not be desirable.
This commit is contained in:
sin-ack 2021-12-29 22:31:45 +00:00 committed by Ali Mohammad Pur
parent eb389db92c
commit dbd25916a3
14 changed files with 163 additions and 162 deletions

View file

@ -7,12 +7,12 @@
#include "Client.h"
#include "LibCore/EventLoop.h"
Client::Client(int id, Core::Stream::TCPSocket socket)
Client::Client(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket)
: m_id(id)
, m_socket(move(socket))
{
m_socket.on_ready_to_read = [this] {
if (m_socket.is_eof())
m_socket->on_ready_to_read = [this] {
if (m_socket->is_eof())
return;
auto result = drain_socket();
@ -32,17 +32,17 @@ ErrorOr<void> Client::drain_socket()
return ENOMEM;
auto buffer = maybe_buffer.release_value();
while (TRY(m_socket.can_read_without_blocking())) {
auto nread = TRY(m_socket.read(buffer));
while (TRY(m_socket->can_read_without_blocking())) {
auto nread = TRY(m_socket->read(buffer));
dbgln("Read {} bytes.", nread);
if (m_socket.is_eof()) {
if (m_socket->is_eof()) {
Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
break;
}
TRY(m_socket.write({ buffer.data(), nread }));
TRY(m_socket->write({ buffer.data(), nread }));
}
return {};
@ -50,7 +50,7 @@ ErrorOr<void> Client::drain_socket()
void Client::quit()
{
m_socket.close();
m_socket->close();
if (on_exit)
on_exit();
}

View file

@ -10,7 +10,7 @@
class Client : public RefCounted<Client> {
public:
static NonnullRefPtr<Client> create(int id, Core::Stream::TCPSocket socket)
static NonnullRefPtr<Client> create(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket)
{
return adopt_ref(*new Client(id, move(socket)));
}
@ -18,12 +18,12 @@ public:
Function<void()> on_exit;
protected:
Client(int id, Core::Stream::TCPSocket socket);
Client(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket);
ErrorOr<void> drain_socket();
void quit();
private:
int m_id { 0 };
Core::Stream::TCPSocket m_socket;
NonnullOwnPtr<Core::Stream::TCPSocket> m_socket;
};