LibGfx/PortableFormat: Write to the output stream row by row

This is done by adding an intermediate buffer and flush it at the end of
every row. This makes the `add_pixels` method to drop from 50% to 7% in
profiles.
This commit is contained in:
Lucas CHOLLET 2023-04-30 19:17:08 -04:00 committed by Andreas Kling
parent d4d3c3f262
commit 44905ed395

View file

@ -5,6 +5,7 @@
*/
#include "PortableFormatWriter.h"
#include <AK/FixedArray.h>
#include <AK/Stream.h>
namespace Gfx {
@ -31,19 +32,30 @@ ErrorOr<void> PortableFormatWriter::add_header(Stream& output, Options const& op
ErrorOr<void> PortableFormatWriter::add_pixels(Stream& output, Options const& options, Bitmap const& bitmap)
{
if (options.format == Options::Format::Raw) {
auto row = TRY(FixedArray<u8>::create(bitmap.width() * 3ul));
for (int i = 0; i < bitmap.height(); ++i) {
for (int j = 0; j < bitmap.width(); ++j) {
auto const color = bitmap.get_pixel(j, i);
row[j * 3 + 0] = color.red();
row[j * 3 + 1] = color.green();
row[j * 3 + 2] = color.blue();
}
TRY(output.write_until_depleted(row.span()));
}
return {};
}
for (int i = 0; i < bitmap.height(); ++i) {
for (int j = 0; j < bitmap.width(); ++j) {
auto color = bitmap.get_pixel(j, i);
if (options.format == Options::Format::ASCII) {
TRY(output.write_formatted("{} {} {}\t", color.red(), color.green(), color.blue()));
} else {
TRY(output.write_value(color.red()));
TRY(output.write_value(color.green()));
TRY(output.write_value(color.blue()));
}
TRY(output.write_formatted("{} {} {}\t", color.red(), color.green(), color.blue()));
}
if (options.format == Options::Format::ASCII)
TRY(output.write_value('\n'));
TRY(output.write_value('\n'));
}
return {};