Fix to implements in-place stdx::replace

This commit is contained in:
A4-Tacks 2025-09-20 12:04:59 +08:00
parent 259a01d73d
commit 48dc150f31
No known key found for this signature in database
GPG Key ID: DBD861323040663B

View File

@ -187,11 +187,19 @@ pub fn is_upper_snake_case(s: &str) -> bool {
}
pub fn replace(buf: &mut String, from: char, to: &str) {
if !buf.contains(from) {
let replace_count = buf.chars().filter(|&ch| ch == from).count();
if replace_count == 0 {
return;
}
// FIXME: do this in place.
*buf = buf.replace(from, to);
let from_len = from.len_utf8();
let additional = to.len().saturating_sub(from_len);
buf.reserve(additional * replace_count);
let mut end = buf.len();
while let Some(i) = buf[..end].rfind(from) {
buf.replace_range(i..i + from_len, to);
end = i;
}
}
#[must_use]