@@ -28,6 +28,7 @@ typedef struct _mp_obj_str_t {
2828
2929STATIC mp_obj_t mp_obj_new_str_iterator (mp_obj_t str );
3030STATIC mp_obj_t mp_obj_new_bytes_iterator (mp_obj_t str );
31+ STATIC mp_obj_t str_new (const mp_obj_type_t * type , const byte * data , uint len );
3132
3233/******************************************************************************/
3334/* str */
@@ -78,6 +79,40 @@ STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env,
7879 }
7980}
8081
82+ STATIC mp_obj_t str_make_new (mp_obj_t type_in , uint n_args , uint n_kw , const mp_obj_t * args ) {
83+ switch (n_args ) {
84+ case 0 :
85+ return MP_OBJ_NEW_QSTR (MP_QSTR_ );
86+
87+ case 1 :
88+ {
89+ vstr_t * vstr = vstr_new ();
90+ mp_obj_print_helper ((void (* )(void * , const char * , ...))vstr_printf , vstr , args [0 ], PRINT_STR );
91+ mp_obj_t s = mp_obj_new_str ((byte * )vstr -> buf , vstr -> len , false);
92+ vstr_free (vstr );
93+ return s ;
94+ }
95+
96+ case 2 :
97+ case 3 :
98+ {
99+ // TODO: validate 2nd/3rd args
100+ if (!MP_OBJ_IS_TYPE (args [0 ], & bytes_type )) {
101+ nlr_jump (mp_obj_new_exception_msg (& mp_type_TypeError , "bytes expected" ));
102+ }
103+ GET_STR_DATA_LEN (args [0 ], str_data , str_len );
104+ GET_STR_HASH (args [0 ], str_hash );
105+ mp_obj_str_t * o = str_new (& str_type , NULL , str_len );
106+ o -> data = str_data ;
107+ o -> hash = str_hash ;
108+ return o ;
109+ }
110+
111+ default :
112+ nlr_jump (mp_obj_new_exception_msg (& mp_type_TypeError , "str takes at most 3 arguments" ));
113+ }
114+ }
115+
81116// like strstr but with specified length and allows \0 bytes
82117// TODO replace with something more efficient/standard
83118STATIC const byte * find_subbytes (const byte * haystack , uint hlen , const byte * needle , uint nlen ) {
@@ -619,6 +654,7 @@ const mp_obj_type_t str_type = {
619654 { & mp_type_type },
620655 .name = MP_QSTR_str ,
621656 .print = str_print ,
657+ .make_new = str_make_new ,
622658 .binary_op = str_binary_op ,
623659 .getiter = mp_obj_new_str_iterator ,
624660 .methods = str_type_methods ,
0 commit comments