Skip to content

Commit d9ad10f

Browse files
committed
pybricks.tools.AppData: Sort modes.
This is far easier than maintaining sort states in the app. We could require the input to be sorted, but calling MicroPython's sort on this short list is simple enough.
1 parent 2515d41 commit d9ad10f

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

pybricks/tools/pb_type_app_data.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,12 @@ static mp_obj_t pb_type_app_data_make_new(const mp_obj_type_t *type, size_t n_ar
155155
mp_obj_t *mode_items;
156156
mp_obj_get_array(modes_in, &num_modes, &mode_items);
157157

158+
// Sort by mode number. Tuples compare lexicographically, so this sorts by the first element.
159+
pb_assert_type(modes_in, &mp_type_list);
160+
mp_obj_t sorted = mp_obj_new_list(num_modes, mode_items);
161+
mp_obj_list_sort(1, &sorted, (mp_map_t *)&mp_const_empty_map);
162+
mp_obj_get_array(sorted, &num_modes, &mode_items);
163+
158164
// Prepare mode setup command.
159165
vstr_t mode_vstr;
160166
vstr_init_len(&mode_vstr, 1 + num_modes);
@@ -179,6 +185,13 @@ static mp_obj_t pb_type_app_data_make_new(const mp_obj_type_t *type, size_t n_ar
179185
mode_info->offset = alloc_size;
180186
mode_info->size = mp_obj_get_int(pair_items[1]);
181187

188+
// Mode must be unique
189+
for (size_t j = 0; j < i; j++) {
190+
if (mode_info->mode == modes[j].mode) {
191+
mp_raise_ValueError(MP_ERROR_TEXT("mode numbers must be unique"));
192+
}
193+
}
194+
182195
// Mode command is just a concatenation of mode numbers.
183196
mode_vstr.buf[i + 1] = mode_info->mode;
184197

0 commit comments

Comments
 (0)