0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2025-02-16 16:50:12 +01:00

ircd: Add string replace() utils.

This commit is contained in:
Jason Volk 2017-10-11 17:57:50 -07:00
parent 239de5c072
commit 908fde12c4
2 changed files with 46 additions and 0 deletions
include/ircd
ircd

View file

@ -95,12 +95,24 @@ namespace ircd
string_view unquote(const string_view &str);
std::string unquote(std::string &&);
std::string replace(std::string, const char &before, const char &after);
std::string replace(const string_view &, const char &before, const string_view &after);
// Legacy
char *strip_colour(char *string);
char *strip_unprintable(char *string);
char *reconstruct_parv(int parc, const char **parv);
}
inline std::string
ircd::replace(std::string s,
const char &before,
const char &after)
{
std::replace(begin(s), end(s), before, after);
return s;
}
/// Remove quotes on an std::string. Only operates on an rvalue reference so
/// that a copy of the string is not created when no quotes are found, and
/// movements can take place if they are. This overload is not needed often;

View file

@ -560,6 +560,40 @@ ircd::try_lex_cast<long double>(const string_view &s)
// ircd/stringops.h
//
std::string
ircd::replace(const string_view &s,
const char &before,
const string_view &after)
{
const auto occurs
{
std::count(begin(s), end(s), before)
};
const size_t size
{
occurs? s.size() + (occurs * after.size()):
s.size() - occurs
};
std::string ret(size, char{});
auto *p{const_cast<char *>(ret.data())};
std::for_each(begin(s), end(s), [&before, &after, &p]
(const char &c)
{
if(c == before)
{
memcpy(p, after.data(), after.size());
p += after.size();
}
else *p++ = c;
});
//assert(ret.size() == size_t(std::distance(ret.data(), const_cast<const char *>(p))));
ret.resize(std::distance(ret.data(), const_cast<const char *>(p)));
return ret;
}
namespace ircd
{
const char _b64_pad_