1 use std::{ffi::CStr, fmt, str};
2 
3 use libusb1_sys::{libusb_get_version, libusb_version};
4 
5 /// A structure that describes the version of the underlying `libusb` library.
6 pub struct LibraryVersion {
7     inner: &'static libusb_version,
8 }
9 
10 impl LibraryVersion {
11     /// Library major version.
major(&self) -> u1612     pub fn major(&self) -> u16 {
13         self.inner.major
14     }
15 
16     /// Library minor version.
minor(&self) -> u1617     pub fn minor(&self) -> u16 {
18         self.inner.minor
19     }
20 
21     /// Library micro version.
micro(&self) -> u1622     pub fn micro(&self) -> u16 {
23         self.inner.micro
24     }
25 
26     /// Library nano version.
nano(&self) -> u1627     pub fn nano(&self) -> u16 {
28         self.inner.nano
29     }
30 
31     /// Library release candidate suffix string, e.g., `"-rc4"`.
rc(&self) -> Option<&'static str>32     pub fn rc(&self) -> Option<&'static str> {
33         let cstr = unsafe { CStr::from_ptr(self.inner.rc) };
34 
35         match str::from_utf8(cstr.to_bytes()) {
36             Ok(s) => {
37                 if s.is_empty() {
38                     None
39                 } else {
40                     Some(s)
41                 }
42             }
43             Err(_) => None,
44         }
45     }
46 }
47 
48 impl fmt::Debug for LibraryVersion {
fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error>49     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
50         let mut debug = fmt.debug_struct("LibraryVersion");
51 
52         debug.field("major", &self.major());
53         debug.field("minor", &self.minor());
54         debug.field("micro", &self.micro());
55         debug.field("nano", &self.nano());
56         debug.field("rc", &self.rc());
57 
58         debug.finish()
59     }
60 }
61 
62 /// Returns a structure with the version of the running libusb library.
version() -> LibraryVersion63 pub fn version() -> LibraryVersion {
64     let version: &'static libusb_version = unsafe { &*libusb_get_version() };
65 
66     LibraryVersion { inner: version }
67 }
68