Skip to content

Commit 2e06e16

Browse files
authored
Merge pull request RustPython#1807 from youknowone/str-expandtabs
Fix str.expandtab() for newlines
2 parents 8ae6e55 + 6cb8b66 commit 2e06e16

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

Lib/test/string_tests.py

-2
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

+24-11
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]
@@ -1084,21 +1090,28 @@ impl PyString {
10841090
}
10851091

10861092
#[pymethod]
1087-
fn expandtabs(&self, tab_stop: OptionalArg<usize>) -> String {
1088-
let tab_stop = tab_stop.into_option().unwrap_or(8 as usize);
1093+
fn expandtabs(&self, args: ExpandtabsArgs) -> String {
1094+
let tab_stop = args.tabsize.unwrap_or(8);
10891095
let mut expanded_str = String::with_capacity(self.value.len());
10901096
let mut tab_size = tab_stop;
10911097
let mut col_count = 0 as usize;
10921098
for ch in self.value.chars() {
1093-
// 0x0009 is tab
1094-
if ch == 0x0009 as char {
1095-
let num_spaces = tab_size - col_count;
1096-
col_count += num_spaces;
1097-
let expand = " ".repeat(num_spaces);
1098-
expanded_str.push_str(&expand);
1099-
} else {
1100-
expanded_str.push(ch);
1101-
col_count += 1;
1099+
match ch {
1100+
'\t' => {
1101+
let num_spaces = tab_size - col_count;
1102+
col_count += num_spaces;
1103+
let expand = " ".repeat(num_spaces);
1104+
expanded_str.push_str(&expand);
1105+
}
1106+
'\r' | '\n' => {
1107+
expanded_str.push(ch);
1108+
col_count = 0;
1109+
tab_size = 0;
1110+
}
1111+
_ => {
1112+
expanded_str.push(ch);
1113+
col_count += 1;
1114+
}
11021115
}
11031116
if col_count >= tab_size {
11041117
tab_size += tab_stop;

0 commit comments

Comments
 (0)