mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-22 15:40:19 +00:00
LibCore: Rewrite Core::Stream::read_all_impl
The previous version relied on manually setting the amount of data to read for the next chunk and was overall unclear. The new version uses the Bytes API to vastly improve readability, and fixes a bug where reading from files where a single read that wasn't of equal size to the block size would cause the byte buffer to be incorrectly resized causing corrupted output.
This commit is contained in:
parent
d3979b0bbd
commit
a192095594
Notes:
sideshowbarker
2024-07-18 03:23:00 +09:00
Author: https://github.com/sin-ack Commit: https://github.com/SerenityOS/serenity/commit/a192095594 Pull-request: https://github.com/SerenityOS/serenity/pull/15246
1 changed files with 10 additions and 15 deletions
|
@ -55,26 +55,21 @@ ErrorOr<ByteBuffer> Stream::read_all(size_t block_size)
|
|||
ErrorOr<ByteBuffer> Stream::read_all_impl(size_t block_size, size_t expected_file_size)
|
||||
{
|
||||
ByteBuffer data;
|
||||
data.ensure_capacity(file_size);
|
||||
data.ensure_capacity(expected_file_size);
|
||||
|
||||
size_t total_read {};
|
||||
size_t next_reading_size { block_size };
|
||||
for (Span<u8> chunk; !is_eof();) {
|
||||
if (next_reading_size == block_size)
|
||||
chunk = TRY(data.get_bytes_for_writing(next_reading_size));
|
||||
auto const nread = TRY(read(chunk)).size();
|
||||
|
||||
next_reading_size -= nread;
|
||||
|
||||
if (next_reading_size == 0)
|
||||
next_reading_size = block_size;
|
||||
size_t total_read = 0;
|
||||
Bytes buffer;
|
||||
while (!is_eof()) {
|
||||
if (buffer.is_empty()) {
|
||||
buffer = TRY(data.get_bytes_for_writing(block_size));
|
||||
}
|
||||
|
||||
auto nread = TRY(read(buffer)).size();
|
||||
total_read += nread;
|
||||
|
||||
if (nread < block_size)
|
||||
data.resize(total_read);
|
||||
buffer = buffer.slice(nread);
|
||||
}
|
||||
|
||||
data.resize(total_read);
|
||||
return data;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue