shuf.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2021, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
  3. * Copyright (c) 2022, Eli Youngs <eli.m.youngs@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/DeprecatedString.h>
  8. #include <AK/Random.h>
  9. #include <AK/Vector.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/Stream.h>
  12. #include <LibCore/System.h>
  13. #include <LibMain/Main.h>
  14. ErrorOr<int> serenity_main(Main::Arguments arguments)
  15. {
  16. TRY(Core::System::pledge("stdio rpath"));
  17. Core::ArgsParser args_parser;
  18. StringView path;
  19. Optional<size_t> head_count;
  20. bool is_zero_terminated = false;
  21. args_parser.add_positional_argument(path, "File", "file", Core::ArgsParser::Required::No);
  22. args_parser.add_option(head_count, "Output at most \"count\" lines", "head-count", 'n', "count");
  23. args_parser.add_option(is_zero_terminated, "Split input on \\0, not newline", "zero-terminated", 'z');
  24. args_parser.parse(arguments);
  25. auto file = TRY(Core::Stream::File::open_file_or_standard_stream(path, Core::Stream::OpenMode::Read));
  26. ByteBuffer buffer = TRY(file->read_until_eof());
  27. u8 input_delimiter = is_zero_terminated ? '\0' : '\n';
  28. Vector<Bytes> lines;
  29. auto bytes = buffer.span();
  30. size_t line_start = 0;
  31. size_t line_length = 0;
  32. for (size_t i = 0; i < bytes.size(); ++i) {
  33. if (bytes[i] == input_delimiter) {
  34. lines.append(bytes.slice(line_start, line_length));
  35. line_start = i + 1;
  36. line_length = 0;
  37. } else {
  38. ++line_length;
  39. }
  40. }
  41. if (line_length > 0) {
  42. lines.append(bytes.slice(line_start));
  43. }
  44. if (lines.is_empty())
  45. return 0;
  46. AK::shuffle(lines);
  47. Array<u8, 1> output_delimiter = { '\n' };
  48. for (size_t i = 0; i < min(head_count.value_or(lines.size()), lines.size()); ++i) {
  49. TRY(Core::System::write(STDOUT_FILENO, lines.at(i)));
  50. TRY(Core::System::write(STDOUT_FILENO, output_delimiter));
  51. }
  52. return 0;
  53. }