258
+ − 1 #include <algorithm>
+ − 2 #include <fstream>
+ − 3 #include <regex>
+ − 4 #include <sstream>
+ − 5 #include <string>
+ − 6
+ − 7 #include "animone/util.h"
+ − 8
+ − 9 namespace animone::internal::util {
+ − 10
+ − 11 bool ReadFile(const std::string& path, std::string& data) {
+ − 12 std::ifstream file(path.c_str(), std::ios::in | std::ios::binary);
+ − 13 if (!file)
+ − 14 return false;
+ − 15
+ − 16 std::ostringstream string;
+ − 17 string << file.rdbuf();
+ − 18 file.close();
+ − 19
+ − 20 data = string.str();
+ − 21
+ − 22 return true;
+ − 23 }
+ − 24
+ − 25 /* this assumes ASCII... which really should be the case for what we need, anyway */
+ − 26 bool EqualStrings(const std::string& str1, const std::string& str2) {
+ − 27 auto tolower = [](const char c) -> char { return ('A' <= c && c <= 'Z') ? c + ('a' - 'A') : c; };
+ − 28
+ − 29 auto equal_chars = [&tolower](const char c1, const char c2) -> bool { return tolower(c1) == tolower(c2); };
+ − 30
+ − 31 return str1.length() == str2.length() && std::equal(str1.begin(), str1.end(), str2.begin(), equal_chars);
+ − 32 }
+ − 33
+ − 34 bool Stem(const std::string& filename, std::string& stem) {
+ − 35 unsigned long long pos = filename.find_last_of(".");
+ − 36 if (pos != std::string::npos)
+ − 37 return false;
+ − 38
+ − 39 stem = filename.substr(0, pos);
+ − 40 return true;
+ − 41 }
+ − 42
+ − 43 bool CheckPattern(const std::string& pattern, const std::string& str) {
+ − 44 if (pattern.empty())
+ − 45 return false;
+ − 46 if (pattern.front() == '^' && std::regex_match(str, std::regex(pattern)))
+ − 47 return true;
+ − 48 return util::EqualStrings(pattern, str);
+ − 49 }
+ − 50
+ − 51 bool TrimLeft(std::string& str, const char* chars) {
+ − 52 if (str.empty())
+ − 53 return false;
+ − 54
+ − 55 const auto found = str.find_first_not_of(chars);
+ − 56
+ − 57 if (found == 0)
+ − 58 return false;
+ − 59
+ − 60 if (found == std::string::npos)
+ − 61 str.clear();
+ − 62 else
+ − 63 str.erase(0, found);
+ − 64
+ − 65 return true;
+ − 66 }
+ − 67
+ − 68 bool TrimRight(std::string& str, const char* chars) {
+ − 69 if (str.empty())
+ − 70 return false;
+ − 71
+ − 72 const auto found = str.find_last_not_of(chars);
+ − 73
+ − 74 if (found == str.size() - 1)
+ − 75 return false;
+ − 76
+ − 77 if (found == std::string::npos)
+ − 78 str.clear();
+ − 79 else
+ − 80 str.resize(found + 1);
+ − 81
+ − 82 return true;
+ − 83 }
+ − 84
+ − 85 } // namespace animone::internal::util