gunzip+LibCompress: Move utility to decompress files to GzipDecompressor

This is to allow re-using this method (and any optimization it receives)
by other utilities, like gzip.
This commit is contained in:
Timothy Flynn 2023-03-31 19:01:39 -04:00 committed by Andreas Kling
parent df577b457a
commit 857f559a06
Notes: sideshowbarker 2024-07-17 14:33:07 +09:00
3 changed files with 20 additions and 18 deletions

View file

@ -11,6 +11,7 @@
#include <AK/DeprecatedString.h>
#include <AK/MemoryStream.h>
#include <LibCore/DateTime.h>
#include <LibCore/File.h>
namespace Compress {
@ -179,6 +180,22 @@ ErrorOr<ByteBuffer> GzipDecompressor::decompress_all(ReadonlyBytes bytes)
return output_buffer;
}
ErrorOr<void> GzipDecompressor::decompress_file(StringView input_filename, NonnullOwnPtr<Stream> output_stream)
{
auto input_file = TRY(Core::File::open(input_filename, Core::File::OpenMode::Read));
auto input_stream = TRY(Core::BufferedFile::create(move(input_file), 256 * KiB));
auto gzip_stream = GzipDecompressor { move(input_stream) };
auto buffer = TRY(ByteBuffer::create_uninitialized(256 * KiB));
while (!gzip_stream.is_eof()) {
auto span = TRY(gzip_stream.read_some(buffer));
TRY(output_stream->write_until_depleted(span));
}
return {};
}
bool GzipDecompressor::is_eof() const { return m_input_stream->is_eof(); }
ErrorOr<size_t> GzipDecompressor::write_some(ReadonlyBytes)

View file

@ -52,6 +52,8 @@ public:
virtual void close() override {};
static ErrorOr<ByteBuffer> decompress_all(ReadonlyBytes);
static ErrorOr<void> decompress_file(StringView input_file, NonnullOwnPtr<Stream> output_stream);
static Optional<DeprecatedString> describe_header(ReadonlyBytes);
static bool is_likely_compressed(ReadonlyBytes bytes);

View file

@ -11,19 +11,6 @@
#include <LibMain/Main.h>
#include <unistd.h>
static ErrorOr<void> decompress_file(NonnullOwnPtr<Stream> input_stream, Stream& output_stream)
{
auto gzip_stream = Compress::GzipDecompressor { move(input_stream) };
auto buffer = TRY(ByteBuffer::create_uninitialized(256 * KiB));
while (!gzip_stream.is_eof()) {
auto span = TRY(gzip_stream.read_some(buffer));
TRY(output_stream.write_until_depleted(span));
}
return {};
}
ErrorOr<int> serenity_main(Main::Arguments args)
{
Vector<StringView> filenames;
@ -51,12 +38,8 @@ ErrorOr<int> serenity_main(Main::Arguments args)
output_filename = filename;
}
auto input_file = TRY(Core::File::open(input_filename, Core::File::OpenMode::Read));
auto buffered_input_file = TRY(Core::BufferedFile::create(move(input_file), 256 * KiB));
auto output_stream = write_to_stdout ? TRY(Core::File::standard_output()) : TRY(Core::File::open(output_filename, Core::File::OpenMode::Write));
TRY(decompress_file(move(buffered_input_file), *output_stream));
TRY(Compress::GzipDecompressor::decompress_file(input_filename, move(output_stream)));
if (!keep_input_files)
TRY(Core::System::unlink(input_filename));