67 lines
1.5 KiB
C++
67 lines
1.5 KiB
C++
#include "Utility.hpp"
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <unordered_map>
|
|
|
|
std::unordered_map<std::string, std::optional<int>> prs_cache
|
|
{ // initialize with constants
|
|
{ "FALSE", 0 },
|
|
{ "TRUE", 1 },
|
|
};
|
|
|
|
std::optional<int> prsi(std::string str)
|
|
{
|
|
auto found = prs_cache.find(str);
|
|
if (found != prs_cache.end()) return found->second; // cache hit
|
|
try
|
|
{ // cache miss, trying to parse and caching the result
|
|
int v;
|
|
if (str.starts_with("0x")) v = std::stoul(str.data(), 0, 16); // hex parsing
|
|
else v = std::stoul(str.data());
|
|
prs_cache[str] = v;
|
|
}
|
|
catch (std::invalid_argument e)
|
|
{ // was not parsable, cache negative parse result
|
|
prs_cache[str] = std::nullopt; // value doesn't matter
|
|
}
|
|
return prs_cache[str];
|
|
}
|
|
|
|
std::vector<char>* lf(std::string& path)
|
|
{
|
|
return lf(path.c_str());
|
|
}
|
|
|
|
std::vector<char>* lf(const char* path)
|
|
{
|
|
std::ifstream file(path, std::ios::binary);
|
|
if (!file.is_open()) return nullptr;
|
|
file.seekg(0, std::ios::end);
|
|
auto vec = new std::vector<char>(file.tellg());
|
|
if (vec->capacity() > 0)
|
|
{
|
|
file.seekg(0, std::ios::beg);
|
|
file.read(vec->data(), vec->capacity());
|
|
}
|
|
return vec;
|
|
}
|
|
|
|
bool lnew(std::string& ln, const char* ew)
|
|
{
|
|
return ln.ends_with(ew);
|
|
}
|
|
|
|
bool lnsw(std::string& ln, int idx, const char* sw)
|
|
{
|
|
int len = strlen(sw);
|
|
return ln.length() - idx + 1 > len && ln.substr(idx, len) == sw;
|
|
}
|
|
|
|
void ssie(std::string& str, std::string repl)
|
|
{
|
|
if (str.empty()) str = repl;
|
|
}
|