From 1d932d3ebf3e3a4781ca7b73324f9ce16cb3e9fd Mon Sep 17 00:00:00 2001 From: dgaston Date: Mon, 22 Apr 2024 21:21:18 -0400 Subject: [PATCH] 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. --- Tests/Utilities/TestUniq.cpp | 10 ++++++++++ Userland/Utilities/uniq.cpp | 4 +++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Tests/Utilities/TestUniq.cpp b/Tests/Utilities/TestUniq.cpp index 2da57cd73d0..8dddfeb2d38 100644 --- a/Tests/Utilities/TestUniq.cpp +++ b/Tests/Utilities/TestUniq.cpp @@ -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); +} diff --git a/Userland/Utilities/uniq.cpp b/Userland/Utilities/uniq.cpp index 5591d745011..ac349a23d61 100644 --- a/Userland/Utilities/uniq.cpp +++ b/Userland/Utilities/uniq.cpp @@ -83,7 +83,9 @@ ErrorOr 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));