line_file_reader.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #pragma once
  6. #include <array>
  7. #include "file/sequence_file_reader.h"
  8. namespace ROCKSDB_NAMESPACE {
  9. // A wrapper on top of Env::SequentialFile for reading text lines from a file.
  10. // Lines are delimited by '\n'. The last line may or may not include a
  11. // trailing newline. Uses SequentialFileReader internally.
  12. class LineFileReader {
  13. private:
  14. std::array<char, 8192> buf_;
  15. SequentialFileReader sfr_;
  16. IOStatus io_status_;
  17. const char* buf_begin_ = buf_.data();
  18. const char* buf_end_ = buf_.data();
  19. size_t line_number_ = 0;
  20. bool at_eof_ = false;
  21. public:
  22. // See SequentialFileReader constructors
  23. template <typename... Args>
  24. explicit LineFileReader(Args&&... args)
  25. : sfr_(std::forward<Args&&>(args)...) {}
  26. static IOStatus Create(const std::shared_ptr<FileSystem>& fs,
  27. const std::string& fname, const FileOptions& file_opts,
  28. std::unique_ptr<LineFileReader>* reader,
  29. IODebugContext* dbg, RateLimiter* rate_limiter);
  30. LineFileReader(const LineFileReader&) = delete;
  31. LineFileReader& operator=(const LineFileReader&) = delete;
  32. // Reads another line from the file, returning true on success and saving
  33. // the line to `out`, without delimiter, or returning false on failure. You
  34. // must check GetStatus() to determine whether the failure was just
  35. // end-of-file (OK status) or an I/O error (another status).
  36. // The internal rate limiter will be charged at the specified priority.
  37. bool ReadLine(std::string* out, Env::IOPriority rate_limiter_priority);
  38. // Returns the number of the line most recently returned from ReadLine.
  39. // Return value is unspecified if ReadLine has returned false due to
  40. // I/O error. After ReadLine returns false due to end-of-file, return
  41. // value is the last returned line number, or equivalently the total
  42. // number of lines returned.
  43. size_t GetLineNumber() const { return line_number_; }
  44. // Returns any error encountered during read. The error is considered
  45. // permanent and no retry or recovery is attempted with the same
  46. // LineFileReader.
  47. const IOStatus& GetStatus() const { return io_status_; }
  48. };
  49. } // namespace ROCKSDB_NAMESPACE