mpremote: Fixbyte length calculation in wr_bytes and read methods.#19113
mpremote: Fixbyte length calculation in wr_bytes and read methods.#19113Josverl wants to merge 2 commits intomicropython:masterfrom
wr_bytes and read methods.#19113Conversation
wr_bytes and read methodswr_bytes and read methods.
598dcb0 to
f7b590c
Compare
|
Code size report: |
f7b590c to
3a2233b
Compare
|
|
|
||
| SEEK_SET = 0 | ||
|
|
||
| def buffer_nbytes(obj): |
There was a problem hiding this comment.
I just realised that this function is visible to the user (eg at the REPL, tab completion) when using mpremote mount, which is a bit messy.
So I suggest moving it into RemoteCommand as a method there. That's the logical place for it.
There was a problem hiding this comment.
Note it is also used from RemoteFile.readinto(), so would need to be a now @staticmethod@classmethod
I have also moved __MPR_HAS_MV_IS into a class variable RemoteCommand.HAS_MV_IS
to avoid
>>> __
__class__ __name__ __dict__ __file__
__MPR_HAS_MV_IS __mount
>>> __MPR_HAS_MV_IS
False
Signed-off-by: Jos Verlinde <Jos_Verlinde@hotmail.com>
3a2233b to
011b5be
Compare
Co-authored-by: Copilot <copilot@github.com> Signed-off-by: Jos Verlinde <Jos_Verlinde@hotmail.com>
a4a584c to
2fe5494
Compare
| wr_str = wr_bytes | ||
|
|
||
| @classmethod | ||
| def buffer_nbytes(cls, obj): |
There was a problem hiding this comment.
This function somehow reverted to an earlier version. Please change it back 😄
There was a problem hiding this comment.
This can be c.buffer_nbytes(buf), and then the buffer_nbytes can be a normal method.
That's slightly more efficient because c is a local variable here (while RemoteCommand is global, which is slower to lookup).

Summary
Refactor the byte length calculation in the
wr_bytesandreadmethods to use a newbuffer_nbytesfunction. This change corrects the accuracy of byte length determination for various buffer types.I have addedd a helper function
buffer_nbytesthat :memoryview. itemsize()struct.calcsize()len(bytes(obj))( which causes a memory allocation )Before this fix mpremote used len(buf) to determine how many bytes to send or receive.
For buffer‑protocol objects like array('h') or array('H'), len() returns number of items, not number of bytes.
This caused:
Closes : #17665
Testing
Tested on relevant MicroPython boards to ensure functionality remains intact.
Trade-offs and Alternatives
The cleanest solution would be for moare ports/boards to actually enable
MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZEas currenltlymemoryview.itemsizeis only enabled on the unix coverage variant, leaving this useful feature unused.Generative AI
I did use generative AI tools when creating this PR, And I personally checked and verified the results.