v923z / micropython-ulab

a numpy-like fast vector module for micropython, circuitpython, and their derivatives
https://micropython-ulab.readthedocs.io/en/latest
MIT License
403 stars 111 forks source link

[BUG] Weird behavior with invalid `dtype=` #585

Open jepler opened 1 year ago

jepler commented 1 year ago

Describe the bug A clear and concise description of what the bug is. Give the ulab version

MicroPython v1.19.1-837-g67fac4ebc on 2023-01-24; linux [GCC 4.2.1] version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import ulab
>>> ulab.__version__
'6.0.5-2D-c'
>>> ulab.numpy.array([range(2000)], dtype=1)
array([[0, 1, 2, ..., 205, 206, 207]], dtype=float64)

Expected behavior Probably an exception as the dtype= argument is not valid (numpy says TypeError: Cannot interpret '1' as a data type)

Additional context discovered during fuzzing, but was not a crash

v923z commented 1 year ago

This is indeed an ugly bug, and it's got to be fixed. What makes a problem a bit difficult is the fact that dtypes are stored as uint8s internally. So,

np.array([1, 2, 3], dtype=np.float)
np.array([1, 2, 3], dtype=100)

both work, while you want the second one to fail. The easiest solution is to simply set the ULAB_HAS_DTYPE_OBJECT constant https://github.com/v923z/micropython-ulab/blob/f2dd2230c4fdf1aa5c7a160782efdde18e8204bb/code/ulab.h#L79-L81, but that adds some kB to the code. That's why I opted for the cheap solution, but I see that that causes issues.