Commit 4504ea80 authored by xbe's avatar xbe
Browse files

Implement str.rpartition and add tests for it.

parent 613a8e3e
......@@ -545,6 +545,40 @@ STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
return mp_obj_new_tuple(3, items);
}
STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
assert(MP_OBJ_IS_STR(self_in));
if (!MP_OBJ_IS_STR(arg)) {
nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
"Can't convert '%s' object to str implicitly", mp_obj_get_type_str(arg)));
}
GET_STR_DATA_LEN(self_in, str, str_len);
GET_STR_DATA_LEN(arg, sep, sep_len);
if (sep_len == 0) {
nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
}
if (sep_len > str_len) {
goto not_found;
}
for (machine_uint_t str_index = str_len; ; str_index--) {
if (memcmp(&str[str_index - sep_len], sep, sep_len) == 0) {
mp_obj_t items[] = {mp_obj_new_str(str, str_index - sep_len, false), arg,
mp_obj_new_str(str + str_index, str_len - str_index, false)};
return mp_obj_new_tuple(3, items);
}
if (str_index - sep_len == 0) {
break;
}
}
not_found: ;
mp_obj_t items[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), mp_obj_new_str(str, str_len, false)};
return mp_obj_new_tuple(3, items);
}
STATIC machine_int_t str_get_buffer(mp_obj_t self_in, buffer_info_t *bufinfo, int flags) {
if (flags == BUFFER_READ) {
GET_STR_DATA_LEN(self_in, str_data, str_len);
......@@ -568,6 +602,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
STATIC const mp_method_t str_type_methods[] = {
{ "find", &str_find_obj },
......@@ -579,6 +614,7 @@ STATIC const mp_method_t str_type_methods[] = {
{ "replace", &str_replace_obj },
{ "count", &str_count_obj },
{ "partition", &str_partition_obj },
{ "rpartition", &str_rpartition_obj },
{ NULL, NULL }, // end-of-list sentinel
};
......
print("asdf".rpartition('g'))
print("asdf".rpartition('a'))
print("asdf".rpartition('s'))
print("asdf".rpartition('f'))
print("asdf".rpartition('d'))
print("asdf".rpartition('asd'))
print("asdf".rpartition('sdf'))
print("asdf".rpartition('as'))
print("asdf".rpartition('df'))
print("asdf".rpartition('asdf'))
print("asdf".rpartition('asdfa'))
print("asdf".rpartition('fasdf'))
print("asdf".rpartition('fasdfa'))
print("abba".rpartition('a'))
print("abba".rpartition('b'))
try:
print("asdf".rpartition(1))
except TypeError:
print("Raised TypeError")
else:
print("Did not raise TypeError")
try:
print("asdf".rpartition(''))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment