Skip to content

Commit 9307e21

Browse files
smurfixdpgeorge
authored andcommitted
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>
1 parent 05a56c3 commit 9307e21

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

Diff for: micropython/usb/usb-device-cdc/manifest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
metadata(version="0.1.1")
1+
metadata(version="0.1.2")
22
require("usb-device")
33
package("usb")

Diff for: micropython/usb/usb-device-cdc/usb/device/cdc.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -350,10 +350,9 @@ def _rd_cb(self, ep, res, num_bytes):
350350
###
351351

352352
def write(self, buf):
353-
# use a memoryview to track how much of 'buf' we've written so far
354-
# (unfortunately, this means a 1 block allocation for each write, but it's otherwise allocation free.)
355353
start = time.ticks_ms()
356-
mv = memoryview(buf)
354+
mv = buf
355+
357356
while True:
358357
# Keep pushing buf into _wb into it's all gone
359358
nbytes = self._wb.write(mv)
@@ -362,6 +361,10 @@ def write(self, buf):
362361
if nbytes == len(mv):
363362
return len(buf) # Success
364363

364+
# if buf couldn't be fully written on the first attempt
365+
# convert it to a memoryview to track partial writes
366+
if mv is buf:
367+
mv = memoryview(buf)
365368
mv = mv[nbytes:]
366369

367370
# check for timeout

0 commit comments

Comments
 (0)