1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 08:44:58 +00:00

AK: Replace the mutable String::replace API with an immutable version

This removes the awkward String::replace API which was the only String
API which mutated the String and replaces it with a new immutable
version that returns a new String with the replacements applied. This
also fixes a couple of UAFs that were caused by the use of this API.

As an optimization an equivalent StringView::replace API was also added
to remove an unnecessary String allocations in the format of:
`String { view }.replace(...);`
This commit is contained in:
Idan Horowitz 2021-09-11 02:15:44 +03:00
parent aba4c9579f
commit 6704961c82
26 changed files with 72 additions and 118 deletions

View file

@ -427,6 +427,34 @@ String to_titlecase(StringView const& str)
return builder.to_string();
}
String replace(StringView const& str, StringView const& needle, StringView const& replacement, bool all_occurrences)
{
if (str.is_empty())
return str;
Vector<size_t> positions;
if (all_occurrences) {
positions = str.find_all(needle);
if (!positions.size())
return str;
} else {
auto pos = str.find(needle);
if (!pos.has_value())
return str;
positions.append(pos.value());
}
StringBuilder replaced_string;
size_t last_position = 0;
for (auto& position : positions) {
replaced_string.append(str.substring_view(last_position, position - last_position));
replaced_string.append(replacement);
last_position = position + needle.length();
}
replaced_string.append(str.substring_view(last_position, str.length() - last_position));
return replaced_string.build();
}
// TODO: Benchmark against KMP (AK/MemMem.h) and switch over if it's faster for short strings too
size_t count(StringView const& str, StringView const& needle)
{