utils: cleanup ReplaceAll

This commit is contained in:
Peter Keresztes Schmidt 2021-04-03 23:43:28 +02:00
parent 664cd649f8
commit 3dbf13e00b
4 changed files with 16 additions and 17 deletions

View File

@ -92,7 +92,7 @@ void Authenticator::authHandleHeader(std::string headerData) {
} // end void Authenticator::authHandleHeader(std::string headerData)
std::string Authenticator::quote( const std::string &src ) {
return replaceAll(replaceAll(src, "\\", "\\\\"), "\"", "\\\"");
return ReplaceAll(ReplaceAll(src, "\\", "\\\\"), "\"", "\\\"");
}
std::string Authenticator::getAuthHeader(std::string method, std::string uri) {

View File

@ -50,13 +50,13 @@ std::string Trim(const std::string &str, const std::string &char_set) {
return str.substr(start_pos, end_pos - start_pos + 1);
}
std::string replaceAll(std::string str, std::string from, std::string to) {
if ( from.empty() )
std::string ReplaceAll(std::string str, const std::string &old_value, const std::string &new_value) {
if (old_value.empty())
return str;
size_t start_pos = 0;
while ( (start_pos = str.find(from, start_pos)) != std::string::npos ) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
while ((start_pos = str.find(old_value, start_pos)) != std::string::npos) {
str.replace(start_pos, old_value.length(), new_value);
start_pos += new_value.length(); // In case 'new_value' contains 'old_value', like replacing 'x' with 'yx'
}
return str;
}

View File

@ -33,8 +33,7 @@ typedef std::vector<std::string> StringVector;
std::string Trim(const std::string &str, const std::string &char_set);
inline std::string TrimSpaces(const std::string &str) { return Trim(str, " \t"); }
std::string replaceAll(std::string str, std::string from, std::string to);
std::string ReplaceAll(std::string str, const std::string& old_value, const std::string& new_value);
template<typename... Args>
std::string stringtf(const std::string &format, Args... args) {

View File

@ -51,18 +51,18 @@ TEST_CASE("TrimSpaces") {
REQUIRE(TrimSpaces("\t te st \t") == "te st");
}
TEST_CASE("replaceAll") {
REQUIRE(replaceAll("", "", "") == "");
TEST_CASE("ReplaceAll") {
REQUIRE(ReplaceAll("", "", "") == "");
REQUIRE(replaceAll("a", "", "b") == "a");
REQUIRE(replaceAll("a", "a", "b") == "b");
REQUIRE(replaceAll("a", "b", "c") == "a");
REQUIRE(ReplaceAll("a", "", "b") == "a");
REQUIRE(ReplaceAll("a", "a", "b") == "b");
REQUIRE(ReplaceAll("a", "b", "c") == "a");
REQUIRE(replaceAll("aa", "a", "b") == "bb");
REQUIRE(replaceAll("aba", "a", "c") == "cbc");
REQUIRE(ReplaceAll("aa", "a", "b") == "bb");
REQUIRE(ReplaceAll("aba", "a", "c") == "cbc");
REQUIRE(replaceAll("aTOKENa", "TOKEN", "VAL") == "aVALa");
REQUIRE(replaceAll("aTOKENaTOKEN", "TOKEN", "VAL") == "aVALaVAL");
REQUIRE(ReplaceAll("aTOKENa", "TOKEN", "VAL") == "aVALa");
REQUIRE(ReplaceAll("aTOKENaTOKEN", "TOKEN", "VAL") == "aVALaVAL");
}
TEST_CASE("startsWith") {