1 /*
2  * Copyright (C) 2016 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 #ifndef OTAPREOPT_FILE_PARSING_H_
18 #define OTAPREOPT_FILE_PARSING_H_
19 
20 #include <fstream>
21 #include <functional>
22 #include <string_view>
23 #include "android-base/unique_fd.h"
24 
25 namespace android {
26 namespace installd {
27 
28 template<typename Func>
ParseFile(std::istream & input_stream,Func parse)29 bool ParseFile(std::istream& input_stream, Func parse) {
30     while (!input_stream.eof()) {
31         // Read the next line.
32         std::string line;
33         getline(input_stream, line);
34 
35         // Is the line empty? Simplifies the next check.
36         if (line.empty()) {
37             continue;
38         }
39 
40         // Is this a comment (starts with pound)?
41         if (line[0] == '#') {
42             continue;
43         }
44 
45         if (!parse(line)) {
46             return false;
47         }
48     }
49 
50     return true;
51 }
52 
53 template<typename Func>
ParseFile(const std::string & str_file,Func parse)54 bool ParseFile(const std::string& str_file, Func parse) {
55   std::ifstream ifs(str_file);
56   if (!ifs.is_open()) {
57     return false;
58   }
59   return ParseFile(ifs, parse);
60 }
61 
62 }  // namespace installd
63 }  // namespace android
64 
65 #endif  // OTAPREOPT_FILE_PARSING_H_
66