• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "util/ini_file.h"
16 
17 #include <fstream>
18 #include <iostream>
19 #include <string>
20 #include <string_view>
21 
22 #include "util/log.h"
23 #include "util/string_utils.h"
24 
25 namespace netsim {
26 
Read()27 bool IniFile::Read() {
28   data.clear();
29 
30   if (filepath.empty()) {
31     BtsLogWarn("Read called without a backing ini file!");
32     return false;
33   }
34 
35   std::ifstream inFile(filepath);
36 
37   if (!inFile) {
38     BtsLogWarn("Failed to process .ini file %s for reading.", filepath.c_str());
39     return false;
40   }
41   std::string line;
42   while (std::getline(inFile, line)) {
43     auto argv = stringutils::Split(line, "=");
44 
45     if (argv.size() != 2) continue;
46     auto key = stringutils::Trim(argv[0]);
47     auto val = stringutils::Trim(argv[1]);
48     data.emplace(key, val);
49   }
50   return true;
51 }
52 
Write()53 bool IniFile::Write() {
54   if (filepath.empty()) {
55     BtsLogWarn("Write called without a backing ini file!");
56     return false;
57   }
58 
59   std::ofstream outFile(filepath);
60 
61   if (!outFile) {
62     BtsLogWarn("Failed to open .ini file %s for writing.", filepath.c_str());
63     return false;
64   }
65 
66   for (const auto &pair : data) {
67     outFile << pair.first << "=" << pair.second << std::endl;
68   }
69   return true;
70 }
71 
HasKey(const std::string & key) const72 bool IniFile::HasKey(const std::string &key) const {
73   return data.find(key) != std::end(data);
74 }
75 
Get(const std::string & key) const76 std::optional<std::string> IniFile::Get(const std::string &key) const {
77   auto citer = data.find(key);
78   return (citer == std::end(data)) ? std::nullopt
79                                    : std::optional(citer->second);
80 }
81 
Set(const std::string & key,std::string_view value)82 void IniFile::Set(const std::string &key, std::string_view value) {
83   data[key] = std::string(value);
84 }
85 
86 }  // namespace netsim
87