Skip to content

Commit 29476dd

Browse files
committed
Runtime: Implemented str.partition
1 parent ad9e42d commit 29476dd

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

src/runtime/PyString.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,28 @@ PyResult<PyObject *> PyString::upper() const
919919
return PyString::create(new_string);
920920
}
921921

922+
PyResult<PyObject *> PyString::partition(PyObject *sep) const
923+
{
924+
if (!sep->type()->issubclass(types::str())) {
925+
return Err(type_error("must be str, not {}", sep->type()->name()));
926+
}
927+
928+
auto split_index = m_value.find(static_cast<const PyString &>(*sep).value());
929+
930+
if (split_index == std::string::npos) {
931+
return PyTuple::create(const_cast<PyString *>(this),
932+
PyString::create("").unwrap(),
933+
PyString::create("").unwrap());
934+
}
935+
936+
auto lhs = m_value.substr(0, split_index);
937+
std::string rhs{ m_value.begin() + split_index
938+
+ static_cast<const PyString &>(*sep).value().size(),
939+
m_value.end() };
940+
return PyTuple::create(PyString::create(lhs).unwrap(), sep, PyString::create(rhs).unwrap());
941+
}
942+
943+
922944
PyResult<PyObject *> PyString::rpartition(PyTuple *args, PyDict *kwargs) const
923945
{
924946
ASSERT(args && args->size() == 1)
@@ -1831,6 +1853,7 @@ namespace {
18311853
.def("join", &PyString::join)
18321854
.def("lower", &PyString::lower)
18331855
.def("upper", &PyString::upper)
1856+
.def("partition", &PyString::partition)
18341857
.def("rpartition", &PyString::rpartition)
18351858
.def("strip", &PyString::strip)
18361859
.def("rstrip", &PyString::rstrip)

src/runtime/PyString.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ class PyString
106106
PyResult<PyObject *> join(PyTuple *args, PyDict *kwargs) const;
107107
PyResult<PyObject *> lower() const;
108108
PyResult<PyObject *> upper() const;
109+
PyResult<PyObject *> partition(PyObject *sep) const;
109110
PyResult<PyObject *> rpartition(PyTuple *args, PyDict *kwargs) const;
110111
PyResult<PyObject *> replace(PyTuple *args, PyDict *kwargs) const;
111112
PyResult<PyObject *> translate(PyObject *table) const;

0 commit comments

Comments
 (0)