Skip to content

Commit d4c8e62

Browse files
committed
py/stream: Add mp_stream_writeall() helper function.
Spools entire output buffer to a blocking stream (chunk by chunk if needed).
1 parent a5d48b1 commit d4c8e62

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

py/stream.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,21 @@ void mp_stream_write_adaptor(void *self, const char *buf, size_t len) {
208208
mp_stream_write(MP_OBJ_FROM_PTR(self), buf, len);
209209
}
210210

211+
// Works only with blocking streams
212+
mp_uint_t mp_stream_writeall(mp_obj_t stream, const byte *buf, mp_uint_t size, int *errcode) {
213+
mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(stream);
214+
mp_uint_t sz = size;
215+
while (sz > 0) {
216+
mp_uint_t out_sz = s->type->stream_p->write(s, buf, size, errcode);
217+
if (out_sz == MP_STREAM_ERROR) {
218+
return MP_STREAM_ERROR;
219+
}
220+
buf += out_sz;
221+
sz -= out_sz;
222+
}
223+
return size;
224+
}
225+
211226
STATIC mp_obj_t stream_write_method(mp_obj_t self_in, mp_obj_t arg) {
212227
mp_buffer_info_t bufinfo;
213228
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);

py/stream.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ mp_obj_t mp_stream_unbuffered_iter(mp_obj_t self);
4949

5050
mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len);
5151

52+
// Helper function to write entire buf to *blocking* stream
53+
mp_uint_t mp_stream_writeall(mp_obj_t stream, const byte *buf, mp_uint_t size, int *errcode);
54+
5255
#if MICROPY_STREAMS_NON_BLOCK
5356
// TODO: This is POSIX-specific (but then POSIX is the only real thing,
5457
// and anything else just emulates it, right?)

0 commit comments

Comments
 (0)