mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-09 22:49:57 +09:00
Refactor string.splitlines
This commit is contained in:
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user