Skip to content

Commit ccb6251

Browse files
committed
pybricks.common.System.storage: use buffer protocol
This updates the storage method to allow any object with the buffer protocol instead of just bytes. Also change the missing arg error to a TypeError while we are touching this. Issue: #121
1 parent 246ebea commit ccb6251

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

pybricks/common/pb_type_system.c

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,21 +115,24 @@ STATIC mp_obj_t pb_type_System_storage(size_t n_args, const mp_obj_t *pos_args,
115115
mp_int_t offset = mp_obj_get_int(offset_in);
116116

117117
// Handle read.
118-
if (write_in == mp_const_none) {
118+
if (read_in != mp_const_none) {
119119
byte *data;
120120
mp_uint_t size = mp_obj_get_int(read_in);
121121
pb_assert(pbsys_program_load_get_user_data(offset, &data, size));
122122
return mp_obj_new_bytes(data, size);
123123
}
124124

125125
// Handle write.
126-
if (read_in == mp_const_none && !mp_obj_is_str(write_in) && mp_obj_is_str_or_bytes(write_in)) {
127-
mp_obj_str_t *obj = ((mp_obj_str_t *)MP_OBJ_TO_PTR(write_in));
128-
pbsys_program_load_set_user_data(offset, obj->data, obj->len);
126+
if (write_in != mp_const_none) {
127+
mp_buffer_info_t bufinfo;
128+
mp_get_buffer_raise(write_in, &bufinfo, MP_BUFFER_READ);
129+
130+
pb_assert(pbsys_program_load_set_user_data(offset, bufinfo.buf, bufinfo.len));
131+
129132
return mp_const_none;
130133
}
131134

132-
mp_raise_ValueError(MP_ERROR_TEXT("Must set either read (int) or write (bytes)."));
135+
mp_raise_TypeError(MP_ERROR_TEXT("Must set either read (int) or write (bytes)."));
133136
}
134137
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pb_type_System_storage_obj, 0, pb_type_System_storage);
135138

0 commit comments

Comments
 (0)