nusb 0.2.3

Cross-platform low-level access to USB devices in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use std::{
    error::Error,
    io::{BufRead, Read},
    time::Duration,
};

#[cfg(any(feature = "tokio", feature = "smol"))]
use std::{
    pin::Pin,
    task::{ready, Context, Poll},
};

use crate::{
    transfer::{Buffer, BulkOrInterrupt, In, TransferError},
    Endpoint,
};

/// Wrapper for a Bulk or Interrupt IN [`Endpoint`](crate::Endpoint) that
/// manages transfers to provide a higher-level buffered API.
///
/// Most of the functionality of this type is provided through standard IO
/// traits; you'll want to use one of the following:
///
/// * [`std::io::Read`](std::io::Read) and [`BufRead`](std::io::BufRead) for
///   blocking IO.
/// * With the `tokio` cargo feature,
///   [`tokio::io::AsyncRead`](tokio::io::AsyncRead) and
///   [`AsyncBufRead`](tokio::io::AsyncBufRead) for async IO. Tokio also
///   provides `AsyncReadExt` and `AsyncBufReadExt` with additional methods.
/// * With the `smol` cargo feature,
///   [`futures_io::AsyncRead`](futures_io::AsyncRead) and
///   [`AsyncBufRead`](futures_io::AsyncBufRead) for async IO.
///   `futures_lite` provides `AsyncReadExt` and `AsyncBufReadExt` with
///   additional methods.
///
/// By default, this type ignores USB packet lengths and boundaries. For protocols
/// that use short or zero-length packets as delimiters, you can use the
/// [`until_short_packet()`](Self::until_short_packet) method to get an
/// [`EndpointReadUntilShortPacket`](EndpointReadUntilShortPacket) adapter
/// that observes these delimiters.
pub struct EndpointRead<EpType: BulkOrInterrupt> {
    endpoint: Endpoint<EpType, In>,
    reading: Option<ReadBuffer>,
    num_transfers: usize,
    transfer_size: usize,
    read_timeout: Duration,
}

struct ReadBuffer {
    pos: usize,
    buf: Buffer,
    status: Result<(), TransferError>,
}

impl ReadBuffer {
    #[inline]
    fn error(&self) -> Option<TransferError> {
        self.status.err().filter(|e| *e != TransferError::Cancelled)
    }

    #[inline]
    fn has_remaining(&self) -> bool {
        self.pos < self.buf.len() || self.error().is_some()
    }

    #[inline]
    fn has_remaining_or_short_end(&self) -> bool {
        self.pos < self.buf.requested_len() || self.error().is_some()
    }

    #[inline]
    fn clear_short_packet(&mut self) {
        self.pos = usize::MAX
    }

    #[inline]
    fn remaining(&self) -> Result<&[u8], std::io::Error> {
        let remaining = &self.buf[self.pos..];
        match (remaining.len(), self.error()) {
            (0, Some(e)) => Err(e.into()),
            _ => Ok(remaining),
        }
    }

    #[inline]
    fn consume(&mut self, len: usize) {
        let remaining = self.buf.len().saturating_sub(self.pos);
        assert!(len <= remaining, "consumed more than available");
        self.pos += len;
    }
}

fn copy_min(dest: &mut [u8], src: &[u8]) -> usize {
    let len = dest.len().min(src.len());
    dest[..len].copy_from_slice(&src[..len]);
    len
}

impl<EpType: BulkOrInterrupt> EndpointRead<EpType> {
    /// Create a new `EndpointRead` wrapping the given endpoint.
    ///
    /// The `transfer_size` parameter is the size of the buffer passed to the OS
    /// for each transfer. It will be rounded up to the next multiple of the
    /// endpoint's max packet size.
    pub fn new(endpoint: Endpoint<EpType, In>, transfer_size: usize) -> Self {
        let packet_size = endpoint.max_packet_size();
        let transfer_size = (transfer_size.div_ceil(packet_size)).max(1) * packet_size;

        Self {
            endpoint,
            reading: None,
            num_transfers: 1,
            transfer_size,
            read_timeout: Duration::MAX,
        }
    }

    /// Set the number of concurrent transfers.
    ///
    /// A value of 1 (default) means that transfers will only be submitted when
    /// calling `read()` or `fill_buf()` and the buffer is empty. To maximize
    /// throughput, a value of 2 or more is recommended for applications that
    /// stream data continuously so that the host controller can continue to
    /// receive data while the application processes the data from a completed
    /// transfer.
    ///
    /// A value of 0 means no further transfers will be submitted. Existing
    /// transfers will complete normally, and subsequent calls to `read()` and
    /// `fill_buf()` will return zero bytes (EOF).
    ///
    /// This submits more transfers when increasing the number, but does not
    /// [cancel transfers](Self::cancel_all) when decreasing it.
    pub fn set_num_transfers(&mut self, num_transfers: usize) {
        self.num_transfers = num_transfers;

        // Leave the last transfer to be submitted by `read` such that
        // a value of `1` only has transfers pending within `read` calls.
        while self.endpoint.pending() < num_transfers.saturating_sub(1) {
            let buf = self.endpoint.allocate(self.transfer_size);
            self.endpoint.submit(buf);
        }
    }

    /// Set the number of concurrent transfers.
    ///
    /// See [Self::set_num_transfers] (this version is for method chaining).
    pub fn with_num_transfers(mut self, num_transfers: usize) -> Self {
        self.set_num_transfers(num_transfers);
        self
    }

    /// Set the timeout for waiting for a transfer in the blocking `read` APIs.
    ///
    /// This affects the `std::io::Read` and `std::io::BufRead` implementations
    /// only, and not the async trait implementations.
    ///
    /// When a timeout occurs, the call fails but the transfer is not cancelled
    /// and may complete later if the read is retried.
    pub fn set_read_timeout(&mut self, timeout: Duration) {
        self.read_timeout = timeout;
    }

    /// Set the timeout for an individual transfer for the blocking `read` APIs.
    ///
    /// See [Self::set_read_timeout] -- this is for method chaining with `EndpointWrite::new()`.
    pub fn with_read_timeout(mut self, timeout: Duration) -> Self {
        self.set_read_timeout(timeout);
        self
    }

    /// Cancel all pending transfers.
    ///
    /// This sets [`num_transfers`](Self::set_num_transfers) to 0, so no further
    /// transfers will be submitted. Any data buffered before the transfers are cancelled
    /// can be read, and then the read methods will return 0 bytes (EOF).
    ///
    /// Call [`num_transfers`](Self::set_num_transfers) with a non-zero value
    /// to resume receiving data.
    pub fn cancel_all(&mut self) {
        self.num_transfers = 0;
        self.endpoint.cancel_all();
    }

    /// Destroy this `EndpointRead` and return the underlying [`Endpoint`].
    ///
    /// Any pending transfers are not cancelled.
    pub fn into_inner(self) -> Endpoint<EpType, In> {
        self.endpoint
    }

    /// Get an [`EndpointReadUntilShortPacket`] adapter that will read only until
    /// the end of a short or zero-length packet.
    ///
    /// Some USB protocols use packets shorter than the endpoint's max packet size
    /// as a delimiter marking the end of a message. By default, [`EndpointRead`]
    /// ignores packet boundaries, but this adapter allows you to observe these
    /// delimiters.
    pub fn until_short_packet(&mut self) -> EndpointReadUntilShortPacket<'_, EpType> {
        EndpointReadUntilShortPacket { reader: self }
    }

    #[inline]
    fn has_data(&self) -> bool {
        self.reading.as_ref().is_some_and(|r| r.has_remaining())
    }

    #[inline]
    fn has_data_or_short_end(&self) -> bool {
        self.reading
            .as_ref()
            .is_some_and(|r| r.has_remaining_or_short_end())
    }

    fn resubmit(&mut self) {
        if let Some(c) = self.reading.take() {
            debug_assert!(!c.has_remaining());
            self.endpoint.submit(c.buf);
        }
    }

    fn start_read(&mut self) -> bool {
        if self.endpoint.pending() < self.num_transfers {
            // Re-use the last completed buffer if available
            self.resubmit();
            while self.endpoint.pending() < self.num_transfers {
                // Allocate more buffers for any remaining transfers
                let buf = self.endpoint.allocate(self.transfer_size);
                self.endpoint.submit(buf);
            }
        }

        // If num_transfers is 0 and all transfers are complete
        self.endpoint.pending() > 0
    }

    #[inline]
    fn remaining(&self) -> Result<&[u8], std::io::Error> {
        self.reading.as_ref().unwrap().remaining()
    }

    #[inline]
    fn consume(&mut self, len: usize) {
        if let Some(ref mut c) = self.reading {
            c.consume(len);
        } else {
            assert!(len == 0, "consumed more than available");
        }
    }

    fn wait(&mut self) -> Result<bool, std::io::Error> {
        if self.start_read() {
            let c = self.endpoint.wait_next_complete(self.read_timeout);
            let c = c.ok_or(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "timeout waiting for read",
            ))?;
            self.reading = Some(ReadBuffer {
                pos: 0,
                buf: c.buffer,
                status: c.status,
            });
            Ok(true)
        } else {
            Ok(false)
        }
    }

    #[cfg(any(feature = "tokio", feature = "smol"))]
    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<bool> {
        if self.start_read() {
            let c = ready!(self.endpoint.poll_next_complete(cx));
            self.reading = Some(ReadBuffer {
                pos: 0,
                buf: c.buffer,
                status: c.status,
            });
            Poll::Ready(true)
        } else {
            Poll::Ready(false)
        }
    }

    #[cfg(any(feature = "tokio", feature = "smol"))]
    #[inline]
    fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8], std::io::Error>> {
        while !self.has_data() {
            if !ready!(self.poll(cx)) {
                return Poll::Ready(Ok(&[]));
            }
        }
        Poll::Ready(self.remaining())
    }

    #[cfg(any(feature = "tokio", feature = "smol"))]
    #[inline]
    fn poll_fill_buf_until_short(
        &mut self,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8], std::io::Error>> {
        while !self.has_data_or_short_end() {
            if !ready!(self.poll(cx)) {
                return Poll::Ready(Err(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "ended without short packet",
                )));
            }
        }
        Poll::Ready(self.remaining())
    }
}

impl<EpType: BulkOrInterrupt> Read for EndpointRead<EpType> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        let remaining = self.fill_buf()?;
        let len = copy_min(buf, remaining);
        self.consume(len);
        Ok(len)
    }
}

impl<EpType: BulkOrInterrupt> BufRead for EndpointRead<EpType> {
    #[inline]
    fn fill_buf(&mut self) -> Result<&[u8], std::io::Error> {
        while !self.has_data() {
            if !self.wait()? {
                return Ok(&[]);
            }
        }
        self.remaining()
    }

    #[inline]
    fn consume(&mut self, len: usize) {
        self.consume(len);
    }
}

#[cfg(feature = "tokio")]
impl<EpType: BulkOrInterrupt> tokio::io::AsyncRead for EndpointRead<EpType> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        let this = Pin::into_inner(self);
        let remaining = ready!(this.poll_fill_buf(cx))?;
        let len = remaining.len().min(buf.remaining());
        buf.put_slice(&remaining[..len]);
        this.consume(len);
        Poll::Ready(Ok(()))
    }
}

#[cfg(feature = "tokio")]
impl<EpType: BulkOrInterrupt> tokio::io::AsyncBufRead for EndpointRead<EpType> {
    fn poll_fill_buf(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8], std::io::Error>> {
        Pin::into_inner(self).poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        Pin::into_inner(self).consume(amt);
    }
}

#[cfg(feature = "smol")]
impl<EpType: BulkOrInterrupt> futures_io::AsyncRead for EndpointRead<EpType> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        let this = Pin::into_inner(self);
        let remaining = ready!(this.poll_fill_buf(cx))?;
        let len = copy_min(buf, remaining);
        this.consume(len);
        Poll::Ready(Ok(len))
    }
}

#[cfg(feature = "smol")]
impl<EpType: BulkOrInterrupt> futures_io::AsyncBufRead for EndpointRead<EpType> {
    fn poll_fill_buf(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8], std::io::Error>> {
        Pin::into_inner(self).poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        Pin::into_inner(self).consume(amt);
    }
}

/// Adapter for [`EndpointRead`] that ends after a short or zero-length packet.
///
/// This can be obtained from [`EndpointRead::until_short_packet()`]. It does
/// have any state other than that of the underlying [`EndpointRead`], so
/// dropping and re-creating with another call to
/// [`EndpointRead::until_short_packet()`] has no effect.
///
/// This implements the same traits as `EndpointRead` but observes packet
/// boundaries instead of ignoring them.
pub struct EndpointReadUntilShortPacket<'a, EpType: BulkOrInterrupt> {
    reader: &'a mut EndpointRead<EpType>,
}

/// Error returned by [`EndpointReadUntilShortPacket::consume_end()`]
/// when the reader is not at the end of a short packet.
#[derive(Debug)]
pub struct ExpectedShortPacket;

impl std::fmt::Display for ExpectedShortPacket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "expected short packet")
    }
}

impl Error for ExpectedShortPacket {}

impl<EpType: BulkOrInterrupt> EndpointReadUntilShortPacket<'_, EpType> {
    /// Check if the endpoint has reached the end of a short packet.
    ///
    /// Upon reading the end of a short packet, the next `read()` or
    /// `fill_buf()` will return 0 bytes (EOF) and this method will return
    /// `true`. To begin reading the next message, call `consume_end()`.
    pub fn is_end(&self) -> bool {
        self.reader
            .reading
            .as_ref()
            .is_some_and(|r| !r.has_remaining() && r.has_remaining_or_short_end())
    }

    /// Consume the end of a short packet.
    ///
    /// Use this after `read()` or `fill_buf()` have returned EOF to reset the reader
    /// to read the next message.
    ///
    /// Returns an error and does nothing if the reader [is not at the end of a short packet](Self::is_end).
    pub fn consume_end(&mut self) -> Result<(), ExpectedShortPacket> {
        if self.is_end() {
            self.reader.reading.as_mut().unwrap().clear_short_packet();
            Ok(())
        } else {
            Err(ExpectedShortPacket)
        }
    }
}

impl<EpType: BulkOrInterrupt> Read for EndpointReadUntilShortPacket<'_, EpType> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        let remaining = self.fill_buf()?;
        let len = copy_min(buf, remaining);
        self.reader.consume(len);
        Ok(len)
    }
}

impl<EpType: BulkOrInterrupt> BufRead for EndpointReadUntilShortPacket<'_, EpType> {
    #[inline]
    fn fill_buf(&mut self) -> Result<&[u8], std::io::Error> {
        while !self.reader.has_data_or_short_end() {
            if !self.reader.wait()? {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "ended without short packet",
                ));
            }
        }
        self.reader.remaining()
    }

    #[inline]
    fn consume(&mut self, len: usize) {
        if self.reader.has_data_or_short_end() {
            assert!(len == 0, "consumed more than available");
        } else {
            self.reader.consume(len);
        }
    }
}

#[cfg(feature = "tokio")]
impl<EpType: BulkOrInterrupt> tokio::io::AsyncRead for EndpointReadUntilShortPacket<'_, EpType> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        let this = Pin::into_inner(self);
        let remaining = ready!(this.reader.poll_fill_buf_until_short(cx))?;
        let len = remaining.len().min(buf.remaining());
        buf.put_slice(&remaining[..len]);
        this.reader.consume(len);
        Poll::Ready(Ok(()))
    }
}

#[cfg(feature = "tokio")]
impl<EpType: BulkOrInterrupt> tokio::io::AsyncBufRead for EndpointReadUntilShortPacket<'_, EpType> {
    fn poll_fill_buf(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8], std::io::Error>> {
        Pin::into_inner(self).reader.poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        Pin::into_inner(self).reader.consume(amt);
    }
}

#[cfg(feature = "smol")]
impl<EpType: BulkOrInterrupt> futures_io::AsyncRead for EndpointReadUntilShortPacket<'_, EpType> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        let this = Pin::into_inner(self);
        let remaining = ready!(this.reader.poll_fill_buf_until_short(cx))?;
        let len = copy_min(buf, remaining);
        this.reader.consume(len);
        Poll::Ready(Ok(len))
    }
}

#[cfg(feature = "smol")]
impl<EpType: BulkOrInterrupt> futures_io::AsyncBufRead
    for EndpointReadUntilShortPacket<'_, EpType>
{
    fn poll_fill_buf(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8], std::io::Error>> {
        Pin::into_inner(self).reader.poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        Pin::into_inner(self).reader.consume(amt);
    }
}