@@ -545,6 +545,40 @@ STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
545545 return mp_obj_new_tuple (3 , items );
546546}
547547
548+ STATIC mp_obj_t str_rpartition (mp_obj_t self_in , mp_obj_t arg ) {
549+ assert (MP_OBJ_IS_STR (self_in ));
550+ if (!MP_OBJ_IS_STR (arg )) {
551+ nlr_jump (mp_obj_new_exception_msg_varg (& mp_type_TypeError ,
552+ "Can't convert '%s' object to str implicitly" , mp_obj_get_type_str (arg )));
553+ }
554+
555+ GET_STR_DATA_LEN (self_in , str , str_len );
556+ GET_STR_DATA_LEN (arg , sep , sep_len );
557+
558+ if (sep_len == 0 ) {
559+ nlr_jump (mp_obj_new_exception_msg (& mp_type_ValueError , "empty separator" ));
560+ }
561+
562+ if (sep_len > str_len ) {
563+ goto not_found ;
564+ }
565+
566+ for (machine_uint_t str_index = str_len ; ; str_index -- ) {
567+ if (memcmp (& str [str_index - sep_len ], sep , sep_len ) == 0 ) {
568+ mp_obj_t items [] = {mp_obj_new_str (str , str_index - sep_len , false), arg ,
569+ mp_obj_new_str (str + str_index , str_len - str_index , false)};
570+ return mp_obj_new_tuple (3 , items );
571+ }
572+ if (str_index - sep_len == 0 ) {
573+ break ;
574+ }
575+ }
576+
577+ not_found : ;
578+ mp_obj_t items [] = {MP_OBJ_NEW_QSTR (MP_QSTR_ ), MP_OBJ_NEW_QSTR (MP_QSTR_ ), mp_obj_new_str (str , str_len , false)};
579+ return mp_obj_new_tuple (3 , items );
580+ }
581+
548582STATIC machine_int_t str_get_buffer (mp_obj_t self_in , buffer_info_t * bufinfo , int flags ) {
549583 if (flags == BUFFER_READ ) {
550584 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);
568602STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_replace_obj , 3 , 4 , str_replace );
569603STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_count_obj , 2 , 4 , str_count );
570604STATIC MP_DEFINE_CONST_FUN_OBJ_2 (str_partition_obj , str_partition );
605+ STATIC MP_DEFINE_CONST_FUN_OBJ_2 (str_rpartition_obj , str_rpartition );
571606
572607STATIC const mp_method_t str_type_methods [] = {
573608 { "find" , & str_find_obj },
@@ -579,6 +614,7 @@ STATIC const mp_method_t str_type_methods[] = {
579614 { "replace" , & str_replace_obj },
580615 { "count" , & str_count_obj },
581616 { "partition" , & str_partition_obj },
617+ { "rpartition" , & str_rpartition_obj },
582618 { NULL , NULL }, // end-of-list sentinel
583619};
584620
0 commit comments