@@ -45,15 +45,26 @@ STATIC void check_stringio_is_open(const mp_obj_stringio_t *o) {
45
45
#define check_stringio_is_open (o )
46
46
#endif
47
47
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
+
48
59
STATIC void stringio_print (const mp_print_t * print , mp_obj_t self_in , mp_print_kind_t kind ) {
49
60
(void )kind ;
50
- mp_obj_stringio_t * self = MP_OBJ_TO_PTR (self_in );
61
+ mp_obj_stringio_t * self = native_obj (self_in );
51
62
mp_printf (print , self -> base .type == & mp_type_stringio ? "<io.StringIO 0x%x>" : "<io.BytesIO 0x%x>" , self );
52
63
}
53
64
54
65
STATIC mp_uint_t stringio_read (mp_obj_t o_in , void * buf , mp_uint_t size , int * errcode ) {
55
66
(void )errcode ;
56
- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
67
+ mp_obj_stringio_t * o = native_obj (o_in );
57
68
check_stringio_is_open (o );
58
69
if (o -> vstr -> len <= o -> pos ) { // read to EOF, or seeked to EOF or beyond
59
70
return 0 ;
@@ -77,7 +88,7 @@ STATIC void stringio_copy_on_write(mp_obj_stringio_t *o) {
77
88
78
89
STATIC mp_uint_t stringio_write (mp_obj_t o_in , const void * buf , mp_uint_t size , int * errcode ) {
79
90
(void )errcode ;
80
- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
91
+ mp_obj_stringio_t * o = native_obj (o_in );
81
92
check_stringio_is_open (o );
82
93
83
94
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,
111
122
112
123
STATIC mp_uint_t stringio_ioctl (mp_obj_t o_in , mp_uint_t request , uintptr_t arg , int * errcode ) {
113
124
(void )errcode ;
114
- mp_obj_stringio_t * o = MP_OBJ_TO_PTR (o_in );
125
+ mp_obj_stringio_t * o = native_obj (o_in );
115
126
switch (request ) {
116
127
case MP_STREAM_SEEK : {
117
128
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,
163
174
#define STREAM_TO_CONTENT_TYPE (o ) (((o)->base.type == &mp_type_stringio) ? &mp_type_str : &mp_type_bytes)
164
175
165
176
STATIC 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 );
167
178
check_stringio_is_open (self );
168
179
// TODO: Try to avoid copying string
169
180
return mp_obj_new_str_of_type (STREAM_TO_CONTENT_TYPE (self ), (byte * )self -> vstr -> buf , self -> vstr -> len );
0 commit comments