From 591534a3c3fcabd2c5b879a9bcd7085c06c0f713 Mon Sep 17 00:00:00 2001 From: Alexander Pevzner Date: Mon, 2 Dec 2024 14:04:24 +0300 Subject: [PATCH] Don't start USB low-level I/O operation, if context.Context already expired This is a king of small optimization. There is no reason to start I/O operation at this case, because it will be canceled immediately after start. --- usbio_libusb.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/usbio_libusb.go b/usbio_libusb.go index 721ae81..229909d 100644 --- a/usbio_libusb.go +++ b/usbio_libusb.go @@ -762,6 +762,11 @@ func (iface *UsbInterface) SoftReset() error { func (iface *UsbInterface) Send(ctx context.Context, data []byte) (n int, err error) { + // Don't even bother to send, if context already expired + if ctx.Err() != nil { + return 0, ctx.Err() + } + // Allocate a libusb_transfer. xfer, doneChan, err := libusbTransferAlloc() if err != nil { @@ -806,6 +811,11 @@ func (iface *UsbInterface) Send(ctx context.Context, func (iface *UsbInterface) Recv(ctx context.Context, data []byte) (n int, err error) { + // Don't even bother to recv, if context already expired + if ctx.Err() != nil { + return 0, ctx.Err() + } + // Some versions of Linux kernel don't allow bulk transfers to // be larger that 16kb per URB, and libusb uses some smart-ass // mechanism to avoid this limitation.