Skip to main content

libusb_wishbone_tool/
device_list.rs

1use std::marker::PhantomData;
2use std::slice;
3
4use libusb::*;
5
6use context::Context;
7use device::{self, Device};
8
9/// A list of detected USB devices.
10pub struct DeviceList<'a> {
11    context: PhantomData<&'a Context>,
12    list: *const *mut libusb_device,
13    len: usize,
14}
15
16impl<'a> Drop for DeviceList<'a> {
17    /// Frees the device list.
18    fn drop(&mut self) {
19        unsafe {
20            libusb_free_device_list(self.list, 1);
21        }
22    }
23}
24
25impl<'a> DeviceList<'a> {
26    /// Returns the number of devices in the list.
27    pub fn len(&self) -> usize {
28        self.len
29    }
30
31    /// Returns the number of devices in the list.
32    pub fn is_empty(&self) -> bool {
33        self.len == 0
34    }
35
36    /// Returns an iterator over the devices in the list.
37    ///
38    /// The iterator yields a sequence of `Device` objects.
39    pub fn iter<'b>(&'b self) -> Devices<'a, 'b> {
40        Devices {
41            context: self.context,
42            devices: unsafe { slice::from_raw_parts(self.list, self.len) },
43            index: 0,
44        }
45    }
46}
47
48/// Iterator over detected USB devices.
49pub struct Devices<'a, 'b> {
50    context: PhantomData<&'a Context>,
51    devices: &'b [*mut libusb_device],
52    index: usize,
53}
54
55impl<'a, 'b> Iterator for Devices<'a, 'b> {
56    type Item = Device<'a>;
57
58    fn next(&mut self) -> Option<Device<'a>> {
59        if self.index < self.devices.len() {
60            let device = self.devices[self.index];
61
62            self.index += 1;
63            Some(unsafe { device::from_libusb(self.context, device) })
64        }
65        else {
66            None
67        }
68    }
69
70    fn size_hint(&self) -> (usize, Option<usize>) {
71        let remaining = self.devices.len() - self.index;
72        (remaining, Some(remaining))
73    }
74}
75
76
77#[doc(hidden)]
78pub unsafe fn from_libusb(_context: &Context, list: *const *mut libusb_device, len: usize,) -> DeviceList {
79    DeviceList {
80        context: PhantomData,
81        list,
82        len,
83    }
84}