Skip to content

Commit f7eb512

Browse files
sapsalianyouknowone
authored andcommitted
Returns new string when (str|bytes).replace get empty original string
1 parent 3fde8f3 commit f7eb512

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

Lib/test/string_tests.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,9 @@ def test___contains__(self):
12021202
self.checkequal(False, 'asd', '__contains__', 'asdf')
12031203
self.checkequal(False, '', '__contains__', 'asdf')
12041204

1205+
1206+
# TODO: RUSTPYTHON
1207+
@unittest.expectedFailure
12051208
def test_subscript(self):
12061209
self.checkequal('a', 'abc', '__getitem__', 0)
12071210
self.checkequal('c', 'abc', '__getitem__', -1)

vm/src/builtins/str.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -826,9 +826,11 @@ impl PyStr {
826826
let s = self.as_str();
827827
match count {
828828
OptionalArg::Present(max_count) if max_count >= 0 => {
829-
if max_count == 0 || s.is_empty() {
829+
if max_count == 0 || (s.is_empty() && !old.is_empty()) {
830830
// nothing to do; return the original bytes
831-
s.into()
831+
s.to_owned()
832+
} else if s.is_empty() && old.is_empty() {
833+
new.as_str().to_owned()
832834
} else {
833835
s.replacen(old.as_str(), new.as_str(), max_count as usize)
834836
}

vm/src/bytesinner.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -847,9 +847,11 @@ impl PyBytesInner {
847847
// stringlib_replace in CPython
848848
let maxcount = match maxcount {
849849
OptionalArg::Present(maxcount) if maxcount >= 0 => {
850-
if maxcount == 0 || self.elements.is_empty() {
850+
if maxcount == 0 || (self.elements.is_empty() && !from.is_empty()) {
851851
// nothing to do; return the original bytes
852852
return Ok(self.elements.clone());
853+
} else if self.elements.is_empty() && from.is_empty() {
854+
return Ok(to.elements);
853855
}
854856
Some(maxcount as usize)
855857
}

0 commit comments

Comments
 (0)