diff --git a/src/config.cc b/src/config.cc index 04e4ebda4768679b98afdbe0b278a3dc4ac2429d..8cfbf945f35f89155e3b7bbb2f08cfeaf5714272 100644 --- a/src/config.cc +++ b/src/config.cc @@ -5,12 +5,13 @@ #include <fstream> #include <iostream> #include <string> +#include <string_view> #include "json5cpp.h" #include "log.h" namespace tools { -bool ends_with(const std::string &str, const std::string &suffix) { +bool ends_with(std::string_view str, std::string_view suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } @@ -141,21 +142,22 @@ int ConfigMap::Parse<ConfigMap::EFormat::CONF>(std::ifstream &in) { return 0; } -Config::Config(const std::string &filename) { +Config::Config(std::string_view filename) { + const auto filename_str = std::string(filename); // Open file and check if valid - std::ifstream in(filename.c_str(), std::ios_base::in); + std::ifstream in(filename_str, std::ios_base::in); if (!in.is_open()) { - throw std::invalid_argument("Configuration file (" + filename + + throw std::invalid_argument("Configuration file (" + filename_str + ") could not be opened. Does it exist?"); } // Pass open file handle to parser according to filename ending - if (tools::ends_with(filename, ".json5")) { + if (tools::ends_with(filename_str, ".json5")) { dict_.Parse<ConfigMap::EFormat::JSON5>(in); - } else if (tools::ends_with(filename, ".conf")) { + } else if (tools::ends_with(filename_str, ".conf")) { dict_.Parse<ConfigMap::EFormat::CONF>(in); } else { - throw std::invalid_argument("Configuration file (" + filename + + throw std::invalid_argument("Configuration file (" + filename_str + ") has unrecognized suffix. Please specify the intended format."); } diff --git a/src/config.h b/src/config.h index 5146db0f4bb841ab70ef1b1caeeefd6b7490ee93..1abd1fc3be7449d6ddba80087376b7e9146169ce 100644 --- a/src/config.h +++ b/src/config.h @@ -8,6 +8,7 @@ #include <map> #include <stdexcept> #include <string> +#include <string_view> #include "log.h" @@ -21,6 +22,8 @@ class ConfigMap { template <EFormat> int Parse(std::ifstream &input); + // Insert (along with other functions) takes `key` as a const-ref since `ValueType`'s operator[] + // does not support `std::string_view`. void Insert(const std::string &key, ValueType val) { data_[key] = std::move(val); } void Import(const ValueType &values) { data_ = values; } @@ -63,7 +66,8 @@ class Config { std::string board; SconeAddress() = default; - SconeAddress(std::string h, std::string p, std::string b) : host(h), port(p), board(b) { + SconeAddress(std::string_view h, std::string_view p, std::string_view b) + : host(h), port(p), board(b) { assert(!host.empty() && !port.empty() && !board.empty()); } @@ -73,7 +77,7 @@ class Config { } }; - explicit Config(const std::string &filename); + explicit Config(std::string_view filename); void print() const; ////// Setup configurations ////////////