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
#![warn(missing_docs)]
include!(concat!(env!("OUT_DIR"), "/usb_ids.cg.rs"));
pub struct Vendors;
impl Vendors {
pub fn iter() -> impl Iterator<Item = &'static Vendor> {
USB_IDS.values()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vendor {
id: u16,
name: &'static str,
devices: &'static [Device],
}
impl Vendor {
pub fn id(&self) -> u16 {
self.id
}
pub fn name(&self) -> &'static str {
self.name
}
pub fn devices(&self) -> impl Iterator<Item = &'static Device> {
self.devices.iter()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Device {
vendor_id: u16,
id: u16,
name: &'static str,
interfaces: &'static [Interface],
}
impl Device {
pub fn from_vid_pid(vid: u16, pid: u16) -> Option<&'static Device> {
let vendor = Vendor::from_id(vid);
vendor.and_then(|v| v.devices().find(|d| d.id == pid))
}
pub fn vendor(&self) -> &'static Vendor {
USB_IDS.get(&self.vendor_id).unwrap()
}
pub fn as_vid_pid(&self) -> (u16, u16) {
(self.vendor_id, self.id)
}
pub fn id(&self) -> u16 {
self.id
}
pub fn name(&self) -> &'static str {
self.name
}
pub fn interfaces(&self) -> impl Iterator<Item = &'static Interface> {
self.interfaces.iter()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Interface {
id: u8,
name: &'static str,
}
impl Interface {
pub fn id(&self) -> u8 {
self.id
}
pub fn name(&self) -> &'static str {
self.name
}
}
pub trait FromId<T> {
fn from_id(id: T) -> Option<&'static Self>;
}
impl FromId<u16> for Vendor {
fn from_id(id: u16) -> Option<&'static Self> {
USB_IDS.get(&id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_id() {
let vendor = Vendor::from_id(0x1d6b).unwrap();
assert_eq!(vendor.name(), "Linux Foundation");
assert_eq!(vendor.id(), 0x1d6b);
}
#[test]
fn test_vendor_devices() {
let vendor = Vendor::from_id(0x1d6b).unwrap();
for device in vendor.devices() {
assert_eq!(device.vendor(), vendor);
assert!(!device.name().is_empty());
}
}
#[test]
fn test_from_vid_pid() {
let device = Device::from_vid_pid(0x1d6b, 0x0003).unwrap();
assert_eq!(device.name(), "3.0 root hub");
let (vid, pid) = device.as_vid_pid();
assert_eq!(vid, device.vendor().id());
assert_eq!(pid, device.id());
let device2 = Device::from_vid_pid(vid, pid).unwrap();
assert_eq!(device, device2);
}
}