feat: add option to escape characters in VarList.cpp and added a test case for it

This commit is contained in:
LOSEARDES77 2025-05-05 15:11:12 +02:00
parent 05878d9470
commit 6770c062bf
2 changed files with 42 additions and 12 deletions

View file

@ -6,23 +6,49 @@
using namespace Hyprutils::String; using namespace Hyprutils::String;
Hyprutils::String::CVarList::CVarList(const std::string& in, const size_t lastArgNo, const char delim, const bool removeEmpty) { Hyprutils::String::CVarList::CVarList(const std::string& in, const size_t lastArgNo, const char delim, const bool removeEmpty) {
if (!removeEmpty && in.empty()) if (!removeEmpty && in.empty()) {
m_vArgs.emplace_back(""); m_vArgs.emplace_back("");
return;
}
std::string args{in}; std::string currentArg;
size_t idx = 0; bool escaped = false;
size_t pos = 0; size_t idx = 0;
std::ranges::replace_if(args, [&](const char& c) { return delim == 's' ? std::isspace(c) : c == delim; }, 0);
for (const auto& s : args | std::views::split(0)) { for (size_t i = 0; i < in.length(); ++i) {
if (removeEmpty && s.empty()) char c = in[i];
// Handle escape character
if (c == '\\' && !escaped) {
escaped = true;
continue; continue;
if (++idx == lastArgNo) {
m_vArgs.emplace_back(trim(in.substr(pos)));
break;
} }
pos += s.size() + 1;
m_vArgs.emplace_back(trim(s.data())); // Check if we've hit a delimiter that's not escaped
bool isDelim = (delim == 's' ? std::isspace(c) : c == delim) && !escaped;
if (isDelim) {
if (!removeEmpty || !currentArg.empty()) {
m_vArgs.emplace_back(trim(currentArg));
currentArg.clear();
idx++;
}
// If this is the last argument we want to parse separately
if (idx == lastArgNo - 1) {
m_vArgs.emplace_back(trim(in.substr(i + 1)));
return;
}
} else {
currentArg += c;
}
escaped = false;
}
// Add the last argument if there is one
if (!removeEmpty || !currentArg.empty()) {
m_vArgs.emplace_back(trim(currentArg));
} }
} }

View file

@ -38,6 +38,10 @@ int main(int argc, char** argv, char** envp) {
EXPECT(list[0], "hello"); EXPECT(list[0], "hello");
EXPECT(list[1], "world!"); EXPECT(list[1], "world!");
CVarList list2("test:test\\:test", 0, ':', true);
EXPECT(list2[0], "test");
EXPECT(list2[1], "test:test");
std::string hello = "hello world!"; std::string hello = "hello world!";
replaceInString(hello, "hello", "hi"); replaceInString(hello, "hello", "hi");
EXPECT(hello, "hi world!"); EXPECT(hello, "hi world!");