Skip to content

Commit 5ccd5dc

Browse files
committed
Fix struct.pack with padding bytes
It used to validate the following arg could fit in a single byte. Now, it always uses zero to pad.
1 parent 15f8b80 commit 5ccd5dc

File tree

3 files changed

+7
-7
lines changed

3 files changed

+7
-7
lines changed

py/binary.c

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -371,11 +371,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte **
371371
}
372372
}
373373

374-
if (val_type == 'x') {
375-
memset(p, 0, 1);
376-
} else {
377-
mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val);
378-
}
374+
mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val);
379375
}
380376

381377
void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in) {

shared-module/struct/__init__.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,11 @@ void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte *end_p, size
153153
p += sz;
154154
} else {
155155
while (sz--) {
156-
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
157156
// Pad bytes don't have a corresponding argument.
158-
if (*fmt != 'x') {
157+
if (*fmt == 'x') {
158+
mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p);
159+
} else {
160+
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
159161
i++;
160162
}
161163
}

tests/basics/struct1.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,5 @@
121121

122122
# check padding bytes
123123
print(struct.pack("xb", 3))
124+
# Make sure pack doesn't reuse a larger value and error
125+
print(struct.pack("xH", 0x100))

0 commit comments

Comments
 (0)