Skip to content

Commit 6cb8b66

Browse files
committed
Fix str.expandtab() for newlines
1 parent 199c75b commit 6cb8b66

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

Lib/test/string_tests.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,8 +327,6 @@ def test_upper(self):
327327
self.checkequal('HELLO', 'HELLO', 'upper')
328328
self.checkraises(TypeError, 'hello', 'upper', 42)
329329

330-
# TODO: RUSTPYTHON
331-
@unittest.expectedFailure
332330
def test_expandtabs(self):
333331
self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
334332
'expandtabs')

vm/src/obj/objstr.rs

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,12 @@ struct SplitLineArgs {
184184
keepends: OptionalArg<bool>,
185185
}
186186

187+
#[derive(FromArgs)]
188+
struct ExpandtabsArgs {
189+
#[pyarg(positional_or_keyword, optional = true)]
190+
tabsize: OptionalArg<usize>,
191+
}
192+
187193
#[pyimpl(flags(BASETYPE))]
188194
impl PyString {
189195
#[pyslot]
@@ -1079,21 +1085,28 @@ impl PyString {
10791085
}
10801086

10811087
#[pymethod]
1082-
fn expandtabs(&self, tab_stop: OptionalArg<usize>) -> String {
1083-
let tab_stop = tab_stop.into_option().unwrap_or(8 as usize);
1088+
fn expandtabs(&self, args: ExpandtabsArgs) -> String {
1089+
let tab_stop = args.tabsize.unwrap_or(8);
10841090
let mut expanded_str = String::with_capacity(self.value.len());
10851091
let mut tab_size = tab_stop;
10861092
let mut col_count = 0 as usize;
10871093
for ch in self.value.chars() {
1088-
// 0x0009 is tab
1089-
if ch == 0x0009 as char {
1090-
let num_spaces = tab_size - col_count;
1091-
col_count += num_spaces;
1092-
let expand = " ".repeat(num_spaces);
1093-
expanded_str.push_str(&expand);
1094-
} else {
1095-
expanded_str.push(ch);
1096-
col_count += 1;
1094+
match ch {
1095+
'\t' => {
1096+
let num_spaces = tab_size - col_count;
1097+
col_count += num_spaces;
1098+
let expand = " ".repeat(num_spaces);
1099+
expanded_str.push_str(&expand);
1100+
}
1101+
'\r' | '\n' => {
1102+
expanded_str.push(ch);
1103+
col_count = 0;
1104+
tab_size = 0;
1105+
}
1106+
_ => {
1107+
expanded_str.push(ch);
1108+
col_count += 1;
1109+
}
10971110
}
10981111
if col_count >= tab_size {
10991112
tab_size += tab_stop;

0 commit comments

Comments
 (0)