2021-01-19 21:58:55 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
|
2022-11-24 17:10:47 +00:00
|
|
|
* Copyright (c) 2022, Eli Youngs <eli.m.youngs@gmail.com>
|
2021-01-19 21:58:55 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2021-01-19 21:58:55 +00:00
|
|
|
*/
|
|
|
|
|
2021-05-14 15:17:26 +00:00
|
|
|
#include <AK/Random.h>
|
2021-01-19 21:58:55 +00:00
|
|
|
#include <AK/String.h>
|
|
|
|
#include <AK/Vector.h>
|
2022-11-24 17:10:47 +00:00
|
|
|
#include <LibCore/ArgsParser.h>
|
|
|
|
#include <LibCore/Stream.h>
|
2022-01-20 20:12:35 +00:00
|
|
|
#include <LibCore/System.h>
|
|
|
|
#include <LibMain/Main.h>
|
2021-01-19 21:58:55 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
2022-11-24 17:10:47 +00:00
|
|
|
ErrorOr<int> serenity_main(Main::Arguments arguments)
|
2021-01-19 21:58:55 +00:00
|
|
|
{
|
2022-11-24 17:10:47 +00:00
|
|
|
TRY(Core::System::pledge("stdio rpath"));
|
|
|
|
|
|
|
|
Core::ArgsParser args_parser;
|
|
|
|
StringView path;
|
|
|
|
|
|
|
|
args_parser.add_positional_argument(path, "File", "file", Core::ArgsParser::Required::No);
|
|
|
|
|
|
|
|
args_parser.parse(arguments);
|
|
|
|
|
|
|
|
auto file = TRY(Core::Stream::File::open_file_or_standard_stream(path, Core::Stream::OpenMode::Read));
|
|
|
|
ByteBuffer buffer = TRY(file->read_all());
|
|
|
|
|
|
|
|
Vector<Bytes> lines;
|
|
|
|
|
|
|
|
auto bytes = buffer.span();
|
|
|
|
size_t line_start = 0;
|
|
|
|
size_t line_length = 0;
|
|
|
|
for (size_t i = 0; i < bytes.size(); ++i) {
|
|
|
|
if (bytes[i] == '\n') {
|
|
|
|
lines.append(bytes.slice(line_start, line_length));
|
|
|
|
line_start = i + 1;
|
|
|
|
line_length = 0;
|
|
|
|
} else {
|
|
|
|
++line_length;
|
2021-01-19 21:58:55 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-24 17:10:47 +00:00
|
|
|
if (line_length > 0) {
|
|
|
|
lines.append(bytes.slice(line_start));
|
|
|
|
}
|
2021-01-19 21:58:55 +00:00
|
|
|
|
2021-10-13 23:58:48 +00:00
|
|
|
if (lines.is_empty())
|
|
|
|
return 0;
|
|
|
|
|
2021-01-19 21:58:55 +00:00
|
|
|
// Fisher-Yates shuffle
|
2022-11-24 17:10:47 +00:00
|
|
|
Bytes tmp;
|
2021-01-19 21:58:55 +00:00
|
|
|
for (size_t i = lines.size() - 1; i >= 1; --i) {
|
2021-05-14 15:17:26 +00:00
|
|
|
size_t j = get_random_uniform(i + 1);
|
2021-01-19 21:58:55 +00:00
|
|
|
// Swap i and j
|
|
|
|
if (i == j)
|
|
|
|
continue;
|
2022-11-24 17:10:47 +00:00
|
|
|
tmp = lines[j];
|
|
|
|
lines[j] = lines[i];
|
|
|
|
lines[i] = tmp;
|
2021-01-19 21:58:55 +00:00
|
|
|
}
|
|
|
|
|
2022-11-24 17:10:47 +00:00
|
|
|
Array<u8, 1> output_delimiter = { '\n' };
|
|
|
|
for (auto const& line : lines) {
|
|
|
|
TRY(Core::System::write(STDOUT_FILENO, line));
|
|
|
|
TRY(Core::System::write(STDOUT_FILENO, output_delimiter));
|
2021-01-19 21:58:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|