From 8af8dd4a0c47aca78a6eac8b4afe53ec9df2c6be Mon Sep 17 00:00:00 2001 From: Yuval Adam <_@yuv.al> Date: Thu, 26 Jul 2018 18:13:45 +0300 Subject: Extract libusb context to a longer living lifetime This is due to a limitation where we can't hold a struct that has both the context and a device handle (that internally references back to it). The libusb context has to outlive the device handle. Github issue: https://github.com/dcuddeback/libusb-rs/issues/3 Example solution via IRC: https://play.rust-lang.org/?gist=c68bda27266249c781e6335c4127f301&version=stable&mode=debug&edition=2015 --- src/lib.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs index 9468997..b13d7be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,32 +5,26 @@ const KNOWN_DEVICES: [(u16, u16, &str); 2] = [ (0x0bda, 0x2838, "Generic RTL2832U OEM") ]; -struct Usb<'a> { - ctx: libusb::Context, - dev: Option> -} - pub struct RtlSdr<'a> { - usb: Usb<'a> + ctx: &'a libusb::Context, + dev: Option> } impl<'a> RtlSdr<'a> { - pub fn new() -> RtlSdr<'a> { + pub fn new(ctx: &'a libusb::Context) -> RtlSdr<'a> { RtlSdr { - usb: Usb { - ctx: libusb::Context::new().unwrap(), - dev: None - } + ctx, + dev: None } } pub fn init(&mut self) { - self.usb.dev = self.find_device(); + self.dev = self.find_device(); } pub fn find_device(&self) -> Option> { - for mut dev in self.usb.ctx.devices().unwrap().iter() { + for mut dev in self.ctx.devices().unwrap().iter() { let desc = dev.device_descriptor().unwrap(); let vid = desc.vendor_id(); let pid = desc.product_id(); @@ -51,9 +45,10 @@ mod tests { #[test] fn test_init() { - let mut rtlsdr = RtlSdr::new(); - assert!(rtlsdr.usb.dev.is_none()); + let ctx = libusb::Context::new().unwrap(); + let mut rtlsdr = RtlSdr::new(&ctx); + assert!(rtlsdr.dev.is_none()); rtlsdr.init(); - assert!(rtlsdr.usb.dev.is_some()); + assert!(rtlsdr.dev.is_some()); } } -- cgit v1.3.1