Introduce a "double_up" function for doubling up escaping

This commit is contained in:
Maxime Coste 2018-06-23 12:43:39 +10:00
parent 6a31d0ebc7
commit 18dfecfa9d
2 changed files with 22 additions and 1 deletions

View File

@ -339,6 +339,23 @@ String format(StringView fmt, ArrayView<const StringView> params)
return res; return res;
} }
String double_up(StringView s, StringView characters)
{
String res;
auto pos = s.begin();
for (auto it = s.begin(), end = s.end(); it != end; ++it)
{
if (contains(characters, *it))
{
res += StringView{pos, it+1};
res += *it;
pos = it+1;
}
}
res += StringView{pos, s.end()};
return res;
}
UnitTest test_string{[]() UnitTest test_string{[]()
{ {
kak_assert(String("youpi ") + "matin" == "youpi matin"); kak_assert(String("youpi ") + "matin" == "youpi matin");
@ -382,6 +399,8 @@ UnitTest test_string{[]()
kak_assert(str_to_int("00") == 0); kak_assert(str_to_int("00") == 0);
kak_assert(str_to_int("-0") == 0); kak_assert(str_to_int("-0") == 0);
kak_assert(double_up(R"('foo%"bar"')", "'\"%") == R"(''foo%%""bar""'')");
kak_assert(replace("tchou/tcha/tchi", "/", "!!") == "tchou!!tcha!!tchi"); kak_assert(replace("tchou/tcha/tchi", "/", "!!") == "tchou!!tcha!!tchi");
}}; }};

View File

@ -128,9 +128,11 @@ StringView format_to(ArrayView<char> buffer, StringView fmt, Types&&... params)
return format_to(buffer, fmt, ArrayView<const StringView>{detail::format_param(std::forward<Types>(params))...}); return format_to(buffer, fmt, ArrayView<const StringView>{detail::format_param(std::forward<Types>(params))...});
} }
String double_up(StringView s, StringView characters);
inline String quote(StringView s) inline String quote(StringView s)
{ {
return format("'{}'", replace(s, "'", "''")); return format("'{}'", double_up(s, "'"));
} }
} }