From 48a925b1d23003565da44bcd74029d1eef714dee Mon Sep 17 00:00:00 2001 From: Karol Kosek Date: Sat, 25 Sep 2021 12:58:23 +0200 Subject: [PATCH] LibCore: Add optional custom read size argument in populate_read_buffer This is a small preparation so IODevice::read() can use it in the next commit. --- Userland/Libraries/LibCore/IODevice.cpp | 18 ++++++++++++++---- Userland/Libraries/LibCore/IODevice.h | 2 +- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Userland/Libraries/LibCore/IODevice.cpp b/Userland/Libraries/LibCore/IODevice.cpp index 09bd63fba7..686d75ea84 100644 --- a/Userland/Libraries/LibCore/IODevice.cpp +++ b/Userland/Libraries/LibCore/IODevice.cpp @@ -218,12 +218,22 @@ String IODevice::read_line(size_t max_size) return {}; } -bool IODevice::populate_read_buffer() const +bool IODevice::populate_read_buffer(size_t size) const { if (m_fd < 0) return false; - u8 buffer[1024]; - int nread = ::read(m_fd, buffer, sizeof(buffer)); + if (!size) + return false; + + auto buffer_result = ByteBuffer::create_uninitialized(size); + if (!buffer_result.has_value()) { + dbgln("IODevice::populate_read_buffer: Not enough memory to allocate a buffer of {} bytes", size); + return {}; + } + auto buffer = buffer_result.release_value(); + auto* buffer_ptr = (char*)buffer.data(); + + int nread = ::read(m_fd, buffer_ptr, size); if (nread < 0) { set_error(errno); return false; @@ -232,7 +242,7 @@ bool IODevice::populate_read_buffer() const set_eof(true); return false; } - m_buffered_data.append(buffer, nread); + m_buffered_data.append(buffer.data(), nread); return true; } diff --git a/Userland/Libraries/LibCore/IODevice.h b/Userland/Libraries/LibCore/IODevice.h index 86e4ac8f8a..6941dfc789 100644 --- a/Userland/Libraries/LibCore/IODevice.h +++ b/Userland/Libraries/LibCore/IODevice.h @@ -103,7 +103,7 @@ protected: virtual void did_update_fd(int) { } private: - bool populate_read_buffer() const; + bool populate_read_buffer(size_t size = 1024) const; bool can_read_from_fd() const; int m_fd { -1 };