@@ -45,15 +45,26 @@ STATIC void check_stringio_is_open(const mp_obj_stringio_t *o) {
4545#define check_stringio_is_open (o )
4646#endif
4747
48+ STATIC mp_obj_stringio_t * native_obj (mp_obj_t o_in ) {
49+ mp_obj_stringio_t * native = mp_obj_cast_to_native_base (o_in , & mp_type_stringio );
50+
51+ #if MICROPY_PY_IO_BYTESIO
52+ if (native == MP_OBJ_NULL ) {
53+ native = mp_obj_cast_to_native_base (o_in , & mp_type_bytesio );
54+ }
55+ #endif
56+ return native ;
57+ }
58+
4859STATIC void stringio_print (const mp_print_t * print , mp_obj_t self_in , mp_print_kind_t kind ) {
4960 (void )kind ;
50- mp_obj_stringio_t * self = MP_OBJ_TO_PTR (self_in );
61+ mp_obj_stringio_t * self = native_obj (self_in );
5162 mp_printf (print , self -> base .type == & mp_type_stringio ? "<io.StringIO 0x%x>" : "<io.BytesIO 0x%x>" , self );
5263}
5364
5465STATIC mp_uint_t stringio_read (mp_obj_t o_in , void * buf , mp_uint_t size , int * errcode ) {
5566 (void )errcode ;
56- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
67+ mp_obj_stringio_t * o = native_obj (o_in );
5768 check_stringio_is_open (o );
5869 if (o -> vstr -> len <= o -> pos ) { // read to EOF, or seeked to EOF or beyond
5970 return 0 ;
@@ -77,7 +88,7 @@ STATIC void stringio_copy_on_write(mp_obj_stringio_t *o) {
7788
7889STATIC mp_uint_t stringio_write (mp_obj_t o_in , const void * buf , mp_uint_t size , int * errcode ) {
7990 (void )errcode ;
80- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
91+ mp_obj_stringio_t * o = native_obj (o_in );
8192 check_stringio_is_open (o );
8293
8394 if (o -> vstr -> fixed_buf ) {
@@ -111,7 +122,7 @@ STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size,
111122
112123STATIC mp_uint_t stringio_ioctl (mp_obj_t o_in , mp_uint_t request , uintptr_t arg , int * errcode ) {
113124 (void )errcode ;
114- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
125+ mp_obj_stringio_t * o = native_obj (o_in );
115126 switch (request ) {
116127 case MP_STREAM_SEEK : {
117128 struct mp_stream_seek_t * s = (struct mp_stream_seek_t * )arg ;
@@ -163,7 +174,7 @@ STATIC mp_uint_t stringio_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
163174#define STREAM_TO_CONTENT_TYPE (o ) (((o)->base.type == &mp_type_stringio) ? &mp_type_str : &mp_type_bytes)
164175
165176STATIC mp_obj_t stringio_getvalue (mp_obj_t self_in ) {
166- mp_obj_stringio_t * self = MP_OBJ_TO_PTR (self_in );
177+ mp_obj_stringio_t * self = native_obj (self_in );
167178 check_stringio_is_open (self );
168179 // TODO: Try to avoid copying string
169180 return mp_obj_new_str_of_type (STREAM_TO_CONTENT_TYPE (self ), (byte * )self -> vstr -> buf , self -> vstr -> len );
0 commit comments