← index #5427PR #2690
Related · high · value 1.758
QUERY · ISSUE

struct.pack doesn't check for value bounds

openby dimpoloopened 2019-12-16updated 2019-12-19
py-core

Setup: MicroPython v1.11-555-g80df377e9 on 2019-11-04; PYBv1.1 with STM32F405RG

struct.pack('B', 256)  # returns b'\x00'

CPython errors out with struct.error: ubyte format requires 0 <= number <= 255

CANDIDATE · PULL REQUEST

modstruct: add support for 'c' format code

closedby tomlogicopened 2016-12-16updated 2017-03-29

A colleague wanted to use the 'c' format code in the struct module. I think I've implemented it correctly, and tested both pack() and unpack(). Under Windows, Python 3.5.2 throws an exception when passing a one-byte string as a parameter to struct.pack(), but in MicroPython, the mp_buffer_info_t looks the same for both b'C' and 'C'.

Also, I should be throwing a struct.error exception, but that hasn't been implemented elsewhere in the module yet, so I just fell back on a ValueError.

>>> struct.unpack('<HBB5c', b'\x01\x00\x02\x03ABCD')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: buffer too small
>>> struct.unpack('<HBB5c', b'\x01\x00\x02\x03ABCDE')
(1, 2, 3, b'A', b'B', b'C', b'D', b'E')
>>> struct.unpack('<HBB5c', b'\x01\x00\x02\x03ABCDEF')
(1, 2, 3, b'A', b'B', b'C', b'D', b'E')
>>> struct.pack('<HBB5c', 1, 2, 3, b'A', b'B', b'C', b'D', b'E')
b'\x01\x00\x02\x03ABCDE'
>>> struct.pack('<HBB5c', 1, 2, 3, b'A', b'B', 'C', b'D', b'E')
b'\x01\x00\x02\x03ABCDE'
>>> struct.pack('<HBB5c', 1, 2, 3, b'A', b'BX', b'C', b'D', b'E')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: char format requires a bytes object of length 1

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied