blob: 66446c0cc5a9d2b8166453f8ee6729534833a169 [file] [log] [blame]
Christopher Wileyef140932015-11-03 09:29:19 -08001/*
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
17#include "line_reader.h"
18
19#include <fstream>
20#include <sstream>
21
22using std::istringstream;
23using std::ifstream;
24using std::string;
25using std::unique_ptr;
26
27namespace android {
28namespace aidl {
29
30class FileLineReader : public LineReader {
31 public:
32 FileLineReader() = default;
Yi Kongde138912019-03-30 01:38:17 -070033 ~FileLineReader() override {
Christopher Wileyef140932015-11-03 09:29:19 -080034 input_stream_.close();
35 }
36
37 bool Init(const std::string& file_path) {
38 input_stream_.open(file_path, ifstream::in | ifstream::binary);
39 return input_stream_.is_open() && input_stream_.good();
40 }
41
42 bool ReadLine(string* line) override {
43 if (!input_stream_.good()) {
44 return false;
45 }
46 line->clear();
47 std::getline(input_stream_, *line);
48 return true;
49 }
50
51 private:
52 ifstream input_stream_;
53
54 DISALLOW_COPY_AND_ASSIGN(FileLineReader);
55}; // class FileLineReader
56
57class MemoryLineReader : public LineReader {
58 public:
Chih-Hung Hsiehe4fecc72016-04-25 12:04:59 -070059 explicit MemoryLineReader(const string& contents) : input_stream_(contents) {}
Yi Kongde138912019-03-30 01:38:17 -070060 ~MemoryLineReader() override = default;
Christopher Wileyef140932015-11-03 09:29:19 -080061
62 bool ReadLine(string* line) override {
63 if (!input_stream_.good()) {
64 return false;
65 }
66 line->clear();
67 std::getline(input_stream_, *line);
68 return true;
69 }
70
71 private:
72 istringstream input_stream_;
73
74 DISALLOW_COPY_AND_ASSIGN(MemoryLineReader);
75}; // class MemoryLineReader
76
77unique_ptr<LineReader> LineReader::ReadFromFile(const string& file_path) {
78 unique_ptr<FileLineReader> file_reader(new FileLineReader());
79 unique_ptr<LineReader> ret;
80 if (file_reader->Init(file_path)) {
81 ret.reset(file_reader.release());
82 }
83 return ret;
84}
85
86unique_ptr<LineReader> LineReader::ReadFromMemory(const string& contents) {
87 return unique_ptr<LineReader>(new MemoryLineReader(contents));
88}
89
Christopher Wileyef140932015-11-03 09:29:19 -080090} // namespace aidl
Steven Morelandf4c64df2019-07-29 19:54:04 -070091} // namespace android