static_lifetime_bound/
static_lifetime_bound.rs

1/****************************************************************************
2Copyright (c) 2015 Osspial All Rights Reserved.
3
4This file is part of hidapi-rs, based on hidapi_rust by Roland Ruckerbauer.
5****************************************************************************/
6
7//! This example shows the added possibility (after version 0.4.1),
8//! to move devices into a function / or closure with static lifetime bounds.
9
10#[cfg(all(feature = "linux-static-rusb", not(target_os = "macos")))]
11extern crate rusb;
12
13extern crate hidapi_rusb;
14
15use hidapi_rusb::{HidApi, HidDevice};
16use std::rc::Rc;
17
18fn main() {
19    let _dev = test_lt();
20}
21
22fn requires_static_lt_bound<F: Fn() + 'static>(f: F) {
23    f();
24}
25
26fn test_lt() -> Rc<HidDevice> {
27    let api = HidApi::new().expect("Hidapi init failed");
28
29    let mut devices = api.device_list();
30
31    let dev_info = devices
32        .nth(0)
33        .expect("There is not a single hid device available");
34
35    let dev = Rc::new(
36        api.open(dev_info.vendor_id(), dev_info.product_id())
37            .expect("Can not open device"),
38    );
39
40    let dev_1 = dev.clone();
41    requires_static_lt_bound(move || {
42        println!("{}", dev_1.check_error().unwrap()); //<! Can be captured by closure with static lt
43    });
44
45    dev //<! Can be returned from a function, which exceeds the lifetime of the API context
46}