Utilities: Fix off by one error in uniq

Flags that rely on counting lines (-c and -d) were
producing results that were off by one. This is fixed
by initializing the `count` variable to 1, which is
consistent with behavior in the main loop, where it
is reset to 1 when lines don't match.
This commit is contained in:
dgaston 2024-04-22 21:21:18 -04:00 committed by Andrew Kaster
parent 82887473d2
commit 1d932d3ebf
Notes: sideshowbarker 2024-07-16 22:54:10 +09:00
2 changed files with 13 additions and 1 deletions

View file

@ -50,3 +50,13 @@ TEST_CASE(long_line)
run_uniq({}, StringView { input }, StringView { expected_output });
}
TEST_CASE(duplicate_flag)
{
run_uniq({ "-d" }, "AAA\nAAA\nBBB\n"sv, "AAA\n"sv);
}
TEST_CASE(count_flag)
{
run_uniq({ "-c" }, "AAA\nAAA\n"sv, "2 AAA\n"sv);
}

View file

@ -83,7 +83,9 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto infile = TRY(Core::InputBufferedFile::create(TRY(Core::File::open_file_or_standard_stream(inpath, Core::File::OpenMode::Read))));
auto outfile = TRY(Core::File::open_file_or_standard_stream(outpath, Core::File::OpenMode::Write));
size_t count = 0;
// The count starts at 1 since each line will appear at least once.
// Otherwise the -d and -c flags do not work as expected.
size_t count = 1;
ByteBuffer previous_buf = TRY(ByteBuffer::create_uninitialized(1024));
ByteBuffer current_buf = TRY(ByteBuffer::create_uninitialized(1024));