line_reader.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (C) 2015, The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "line_reader.h"
  17. #include <fstream>
  18. #include <sstream>
  19. using std::istringstream;
  20. using std::ifstream;
  21. using std::string;
  22. using std::unique_ptr;
  23. namespace android {
  24. namespace aidl {
  25. class FileLineReader : public LineReader {
  26. public:
  27. FileLineReader() = default;
  28. ~FileLineReader() override {
  29. input_stream_.close();
  30. }
  31. bool Init(const std::string& file_path) {
  32. input_stream_.open(file_path, ifstream::in | ifstream::binary);
  33. return input_stream_.is_open() && input_stream_.good();
  34. }
  35. bool ReadLine(string* line) override {
  36. if (!input_stream_.good()) {
  37. return false;
  38. }
  39. line->clear();
  40. std::getline(input_stream_, *line);
  41. return true;
  42. }
  43. private:
  44. ifstream input_stream_;
  45. DISALLOW_COPY_AND_ASSIGN(FileLineReader);
  46. }; // class FileLineReader
  47. class MemoryLineReader : public LineReader {
  48. public:
  49. explicit MemoryLineReader(const string& contents) : input_stream_(contents) {}
  50. ~MemoryLineReader() override = default;
  51. bool ReadLine(string* line) override {
  52. if (!input_stream_.good()) {
  53. return false;
  54. }
  55. line->clear();
  56. std::getline(input_stream_, *line);
  57. return true;
  58. }
  59. private:
  60. istringstream input_stream_;
  61. DISALLOW_COPY_AND_ASSIGN(MemoryLineReader);
  62. }; // class MemoryLineReader
  63. unique_ptr<LineReader> LineReader::ReadFromFile(const string& file_path) {
  64. unique_ptr<FileLineReader> file_reader(new FileLineReader());
  65. unique_ptr<LineReader> ret;
  66. if (file_reader->Init(file_path)) {
  67. ret.reset(file_reader.release());
  68. }
  69. return ret;
  70. }
  71. unique_ptr<LineReader> LineReader::ReadFromMemory(const string& contents) {
  72. return unique_ptr<LineReader>(new MemoryLineReader(contents));
  73. }
  74. } // namespace android
  75. } // namespace aidl