Skip to content

Commit 5225450

Browse files
committed
Add generic impl of stream .readall() method. Use one for unix io.FileIO.
1 parent 5d2499c commit 5225450

3 files changed

Lines changed: 44 additions & 0 deletions

File tree

py/stream.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,47 @@ static mp_obj_t stream_write(mp_obj_t self_in, mp_obj_t arg) {
5151
}
5252
}
5353

54+
// TODO: should be in mpconfig.h
55+
#define READ_SIZE 256
56+
static mp_obj_t stream_readall(mp_obj_t self_in) {
57+
struct _mp_obj_base_t *o = (struct _mp_obj_base_t *)self_in;
58+
if (o->type->stream_p.read == NULL) {
59+
// CPython: io.UnsupportedOperation, OSError subclass
60+
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_OSError, "Operation not supported"));
61+
}
62+
63+
int total_size = 0;
64+
vstr_t *vstr = vstr_new_size(READ_SIZE);
65+
char *buf = vstr_str(vstr);
66+
char *p = buf;
67+
int error;
68+
int current_read = READ_SIZE;
69+
while (true) {
70+
machine_int_t out_sz = o->type->stream_p.read(self_in, p, current_read, &error);
71+
if (out_sz == -1) {
72+
nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_OSError, "[Errno %d]", error));
73+
}
74+
if (out_sz == 0) {
75+
break;
76+
}
77+
total_size += out_sz;
78+
if (out_sz < current_read) {
79+
current_read -= out_sz;
80+
p += out_sz;
81+
} else {
82+
current_read = READ_SIZE;
83+
p = vstr_extend(vstr, current_read);
84+
if (p == NULL) {
85+
// TODO
86+
nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_OSError/*MP_QSTR_RuntimeError*/, "Out of memory"));
87+
}
88+
}
89+
}
90+
vstr_set_size(vstr, total_size + 1); // TODO: for \0
91+
buf[total_size] = 0;
92+
return mp_obj_new_str(qstr_from_str_take(buf, total_size + 1));
93+
}
94+
5495
MP_DEFINE_CONST_FUN_OBJ_2(mp_stream_read_obj, stream_read);
96+
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_readall_obj, stream_readall);
5597
MP_DEFINE_CONST_FUN_OBJ_2(mp_stream_write_obj, stream_write);

py/stream.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
extern const mp_obj_fun_native_t mp_stream_read_obj;
2+
extern const mp_obj_fun_native_t mp_stream_readall_obj;
23
extern const mp_obj_fun_native_t mp_stream_write_obj;

unix/file.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ static mp_obj_t fdfile_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *ar
9090

9191
static const mp_method_t rawfile_type_methods[] = {
9292
{ "read", &mp_stream_read_obj },
93+
{ "readall", &mp_stream_readall_obj },
9394
{ "write", &mp_stream_write_obj },
9495
{ "close", &fdfile_close_obj },
9596
{ NULL, NULL },

0 commit comments

Comments
 (0)