usb-device-cdc: Optimise writing small data so it doesn't require alloc.

Only allocate a memoryview when the (first) write was partial.

Signed-off-by: Matthias Urlichs <matthias@urlichs.de>
pull/991/head
Matthias Urlichs 2025-03-26 12:00:40 +01:00 zatwierdzone przez Damien George
rodzic 05a56c3cad
commit 9307e21dfb
2 zmienionych plików z 7 dodań i 4 usunięć

Wyświetl plik

@ -1,3 +1,3 @@
metadata(version="0.1.1") metadata(version="0.1.2")
require("usb-device") require("usb-device")
package("usb") package("usb")

Wyświetl plik

@ -350,10 +350,9 @@ class CDCInterface(io.IOBase, Interface):
### ###
def write(self, buf): def write(self, buf):
# use a memoryview to track how much of 'buf' we've written so far
# (unfortunately, this means a 1 block allocation for each write, but it's otherwise allocation free.)
start = time.ticks_ms() start = time.ticks_ms()
mv = memoryview(buf) mv = buf
while True: while True:
# Keep pushing buf into _wb into it's all gone # Keep pushing buf into _wb into it's all gone
nbytes = self._wb.write(mv) nbytes = self._wb.write(mv)
@ -362,6 +361,10 @@ class CDCInterface(io.IOBase, Interface):
if nbytes == len(mv): if nbytes == len(mv):
return len(buf) # Success return len(buf) # Success
# if buf couldn't be fully written on the first attempt
# convert it to a memoryview to track partial writes
if mv is buf:
mv = memoryview(buf)
mv = mv[nbytes:] mv = mv[nbytes:]
# check for timeout # check for timeout