8000 py/objstringio: Implement MP_STREAM_SEEK ioctl and add seek() method. · sparkfun/circuitpython@3990b17 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3990b17

Browse files
committed
py/objstringio: Implement MP_STREAM_SEEK ioctl and add seek() method.
1 parent f039ac5 commit 3990b17

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

py/objstringio.c

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,18 @@ STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size,
7575
(void)errcode;
7676
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
7777
check_stringio_is_open(o);
78-
mp_uint_t remaining = o->vstr->alloc - o->pos;
79-
if (size > remaining) {
78+
mp_int_t remaining = o->vstr->alloc - o->pos;
79+
mp_uint_t org_len = o->vstr->len;
80+
if ((mp_int_t)size > remaining) {
8081
// Take all what's already allocated...
8182
o->vstr->len = o->vstr->alloc;
8283
// ... and add more
8384
vstr_add_len(o->vstr, size - remaining);
8485
}
86+
// If there was a seek past EOF, clear the hole
87+
if (o->pos > org_len) {
88+
8000 memset(o->vstr->buf + org_len, 0, o->pos - org_len);
89+
}
8590
memcpy(o->vstr->buf + o->pos, buf, size);
8691
o->pos += size;
8792
if (o->pos > o->vstr->len) {
@@ -92,8 +97,23 @@ STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size,
9297

9398
STATIC mp_uint_t stringio_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
9499
(void)errcode;
95-
// mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
100+
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
96101
switch (request) {
102+
case MP_STREAM_SEEK: {
103+
struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
104+
mp_uint_t ref = 0;
105+
switch (s->whence) {
106+
case 1: // SEEK_CUR
107+
ref = o->pos;
108+
break;
109+
case 2: // SEEK_END
110+
ref = o->vstr->len;
111+
break;
112+
}
113+
o->pos = ref + s->offset;
114+
s->offset = o->pos;
115+
return 0;
116+
}
97117
case MP_STREAM_FLUSH:
98118
return 0;
99119
default:
@@ -160,6 +180,7 @@ STATIC const mp_rom_map_elem_t stringio_locals_dict_table[] = {
160180
{ MP_ROM_QSTR(MP_QSTR_readall), MP_ROM_PTR(&mp_stream_readall_obj) },
161181
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
162182
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
183+
{ MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) },
163184
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
164185
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&stringio_close_obj) },
165186
{ MP_ROM_QSTR(MP_QSTR_getvalue), MP_ROM_PTR(&stringio_getvalue_obj) },

0 commit comments

Comments
 (0)
0