0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2024-11-17 23:40:57 +01:00
construct/ircd/stringops.cc

96 lines
1.9 KiB
C++

// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
ircd::string_view
ircd::toupper(const mutable_buffer &out,
const string_view &in)
noexcept
{
const auto stop
{
std::next(begin(in), std::min(size(in), size(out)))
};
const auto end
{
std::transform(begin(in), stop, begin(out), []
(const auto &c)
{
return std::toupper(c);
})
};
assert(intptr_t(begin(out)) <= intptr_t(end));
return string_view
{
data(out), size_t(std::distance(begin(out), end))
};
}
ircd::string_view
ircd::tolower(const mutable_buffer &out,
const string_view &in)
noexcept
{
const auto stop
{
std::next(begin(in), std::min(size(in), size(out)))
};
const auto end
{
std::transform(begin(in), stop, begin(out), []
(const auto &c)
{
return std::tolower(c);
})
};
assert(intptr_t(begin(out)) <= intptr_t(end));
return string_view
{
data(out), size_t(std::distance(begin(out), end))
};
}
std::string
ircd::replace(const string_view &s,
const char &before,
const string_view &after)
{
const uint32_t occurs
(
std::count(begin(s), end(s), before)
);
const size_t size
{
occurs? s.size() + (occurs * after.size()):
s.size() - occurs
};
return string(size, [&s, &before, &after]
(const mutable_buffer &buf)
{
char *p{begin(buf)};
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;
});
return std::distance(begin(buf), p);
});
}