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/string_utils.h" 23 24 namespace netsim { 25 Read()26bool IniFile::Read() { 27 data.clear(); 28 29 if (filepath.empty()) { 30 std::cerr << "Read called without a backing file!"; 31 return false; 32 } 33 34 std::ifstream inFile(filepath); 35 36 if (!inFile) { 37 std::cerr << "Failed to process .ini file " << filepath << " for reading." 38 << std::endl; 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()53bool IniFile::Write() { 54 if (filepath.empty()) { 55 std::cerr << "Write called without a backing file!"; 56 return false; 57 } 58 59 std::ofstream outFile(filepath); 60 61 if (!outFile) { 62 std::cerr << "Failed to open .ini file " << filepath << " for writing."; 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) const72bool IniFile::HasKey(const std::string &key) const { 73 return data.find(key) != std::end(data); 74 } 75 Get(const std::string & key) const76std::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)82void IniFile::Set(const std::string &key, std::string_view value) { 83 data[key] = std::string(value); 84 } 85 86 } // namespace netsim 87