• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include "line_reader.h"
18 
19 #include <fstream>
20 #include <sstream>
21 
22 using std::istringstream;
23 using std::ifstream;
24 using std::string;
25 using std::unique_ptr;
26 
27 namespace android {
28 namespace aidl {
29 
30 class FileLineReader : public LineReader {
31  public:
32   FileLineReader() = default;
~FileLineReader()33   ~FileLineReader() override {
34     input_stream_.close();
35   }
36 
Init(const std::string & file_path)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 
ReadLine(string * line)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 
57 class MemoryLineReader : public LineReader {
58  public:
MemoryLineReader(const string & contents)59   explicit MemoryLineReader(const string& contents) : input_stream_(contents) {}
60   ~MemoryLineReader() override = default;
61 
ReadLine(string * line)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 
ReadFromFile(const string & file_path)77 unique_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 
ReadFromMemory(const string & contents)86 unique_ptr<LineReader> LineReader::ReadFromMemory(const string& contents) {
87   return unique_ptr<LineReader>(new MemoryLineReader(contents));
88 }
89 
90 }  // namespace android
91 }  // namespace aidl
92