Refactor string.splitlines

This commit is contained in:
Aviv Palivoda
2020-01-24 22:53:44 +02:00
parent 4a9e87b80d
commit 8bf0d93bb2
2 changed files with 20 additions and 12 deletions

View File

@@ -168,7 +168,9 @@ assert not 'abcd'.startswith('', 4, 3)
assert ' '.isspace()
assert 'hello\nhallo\nHallo'.splitlines() == ['hello', 'hallo', 'Hallo']
assert 'hello\nhallo\nHallo'.splitlines(keepends=True) == ['hello\n', 'hallo\n', 'Hallo\n']
assert 'hello\nhallo\nHallo\n'.splitlines() == ['hello', 'hallo', 'Hallo']
assert 'hello\nhallo\nHallo'.splitlines(keepends=True) == ['hello\n', 'hallo\n', 'Hallo']
assert 'hello\nhallo\nHallo\n'.splitlines(keepends=True) == ['hello\n', 'hallo\n', 'Hallo\n']
assert 'abc\t12345\txyz'.expandtabs() == 'abc 12345 xyz'
assert '-'.join(['1', '2', '3']) == '1-2-3'
assert 'HALLO'.isupper()

View File

@@ -782,19 +782,25 @@ impl PyString {
!self.value.is_empty() && self.value.chars().all(|c| c.is_ascii())
}
// doesn't implement keep new line delimiter just yet
#[pymethod]
fn splitlines(&self, args: SplitLineArgs, vm: &VirtualMachine) -> PyObjectRef {
let end = if let OptionalArg::Present(true) = args.keepends {
"\n"
} else {
""
};
let elements = self
.value
.split('\n')
.map(|e| vm.ctx.new_str(e.to_string() + end))
.collect();
let keepends = args.keepends.unwrap_or(false);
let mut elements = vec![];
let mut curr = "".to_string();
for ch in self.value.chars() {
if ch == '\n' {
if keepends {
curr.push(ch);
}
elements.push(vm.ctx.new_str(curr.clone()));
curr.clear();
} else {
curr.push(ch);
}
}
if !curr.is_empty() {
elements.push(vm.ctx.new_str(curr.clone()));
}
vm.ctx.new_list(elements)
}