mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 18:38:10 +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:
parent
aba4c9579f
commit
6704961c82
26 changed files with 72 additions and 118 deletions
|
@ -352,36 +352,6 @@ bool String::equals_ignoring_case(const StringView& other) const
|
|||
return StringUtils::equals_ignoring_case(view(), other);
|
||||
}
|
||||
|
||||
int String::replace(const String& needle, const String& replacement, bool all_occurrences)
|
||||
{
|
||||
if (is_empty())
|
||||
return 0;
|
||||
|
||||
Vector<size_t> positions;
|
||||
if (all_occurrences) {
|
||||
positions = find_all(needle);
|
||||
} else {
|
||||
auto pos = find(needle);
|
||||
if (!pos.has_value())
|
||||
return 0;
|
||||
positions.append(pos.value());
|
||||
}
|
||||
|
||||
if (!positions.size())
|
||||
return 0;
|
||||
|
||||
StringBuilder b;
|
||||
size_t lastpos = 0;
|
||||
for (auto& pos : positions) {
|
||||
b.append(substring_view(lastpos, pos - lastpos));
|
||||
b.append(replacement);
|
||||
lastpos = pos + needle.length();
|
||||
}
|
||||
b.append(substring_view(lastpos, length() - lastpos));
|
||||
m_impl = StringImpl::create(b.build().characters());
|
||||
return positions.size();
|
||||
}
|
||||
|
||||
String String::reverse() const
|
||||
{
|
||||
StringBuilder reversed_string(length());
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue