Skip to content

Commit 314ab76

Browse files
committed
Fix to implements in-place stdx::replace
1 parent b12a129 commit 314ab76

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

crates/stdx/src/lib.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,19 @@ pub fn is_upper_snake_case(s: &str) -> bool {
187187
}
188188

189189
pub fn replace(buf: &mut String, from: char, to: &str) {
190-
if !buf.contains(from) {
190+
let replace_count = buf.chars().filter(|&ch| ch == from).count();
191+
if replace_count == 0 {
191192
return;
192193
}
193-
// FIXME: do this in place.
194-
*buf = buf.replace(from, to);
194+
let from_len = from.len_utf8();
195+
let additional = to.len().saturating_sub(from_len);
196+
buf.reserve(additional * replace_count);
197+
198+
let mut end = buf.len();
199+
while let Some(i) = buf[..end].rfind(from) {
200+
buf.replace_range(i..i + from_len, to);
201+
end = i;
202+
}
195203
}
196204

197205
#[must_use]

0 commit comments

Comments
 (0)