diff --git a/include/commoncpp/utils.hpp b/include/commoncpp/utils.hpp index 17462a5..afe69ca 100644 --- a/include/commoncpp/utils.hpp +++ b/include/commoncpp/utils.hpp @@ -10,11 +10,13 @@ namespace utils { std::vector str_split(std::string_view s, char delimiter, size_t times = -1); bool str_replace_in_place(std::string& subject, std::string_view search, const std::string& replace); std::string_view max_words(std::string_view text, unsigned count); -bool contains(std::string_view value, std::string_view ending); -bool starts_with(std::string_view value, std::string_view ending); +bool contains(std::string_view value, std::string_view other); +bool starts_with(std::string_view value, std::string_view beginning); bool ends_with(std::string_view value, std::string_view ending); +bool force_trailing(std::string& value, std::string_view ending); bool chop_down(std::string& s, char delim); std::string remove_nonprintable(std::string_view); +std::string read_text_file(const std::string& path); [[noreturn]] inline void unreachable() { // Uses compiler specific extensions if possible. diff --git a/utils.cpp b/utils.cpp index 71d2b9e..3bbeb8d 100644 --- a/utils.cpp +++ b/utils.cpp @@ -1,5 +1,10 @@ #include "utils.hpp" +#include +#include +#include +#include + namespace common { @@ -49,12 +54,12 @@ std::string_view max_words(std::string_view text, unsigned count) { return {text.data(), idx}; } -bool contains(std::string_view value, std::string_view ending) { - return value.find(ending) != value.npos; +bool contains(std::string_view value, std::string_view other) { + return value.find(other) != value.npos; } -bool starts_with(std::string_view value, std::string_view ending) { - return value.find(ending) == 0; +bool starts_with(std::string_view value, std::string_view beginning) { + return value.find(beginning) == 0; } bool ends_with(std::string_view value, std::string_view ending) { @@ -62,6 +67,12 @@ bool ends_with(std::string_view value, std::string_view ending) { return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } +bool force_trailing(std::string &value, std::string_view ending) { + bool fres = ends_with(value, ending); + if (!fres) value.append(ending); + return fres; +} + bool chop_down(std::string& s, char delim) { const auto pos = s.find(delim); if (pos == s.npos) return false; @@ -76,5 +87,13 @@ std::string remove_nonprintable(std::string_view str) { } return fres; } + +std::string read_text_file(const std::string& path) { + std::ifstream in(path); + if (!in) throw std::system_error(std::error_code(errno, std::system_category()), path); + std::ostringstream sstr; + sstr << in.rdbuf(); + return sstr.str(); +} } }