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
//! Utility functions for cpu efficent `wait` commands.
//! Uses the `libc::epoll_wait` that only works on linux systems.

use libc;
use std::os::unix::io::RawFd;
use std::time::{Duration, Instant};

/// Wait for until a condition `cond` is `true` or the `timeout` is reached.
/// If the `timeout` is `None` it will wait an infinite time.
/// The condition is checked when the `file` has changed.
///
/// # Arguments
/// * `file` - Listen to changes in this file
/// * `cond` - Condition that should become true
/// * `timeout` - Maximal timeout to wait for the condition or file changes
///
/// # Example
/// ```
/// use std::fs::File;
/// use std::os::unix::io::AsRawFd;
/// use std::time::Duration;
///
/// use ev3dev_lang_rust::wait;
///
/// if let Ok(file) = File::open("...") {
///     let cond = || {
///         // ...
///         true
///     };
///     let timeout = Duration::from_millis(2000);
///
///     wait::wait(file.as_raw_fd(), cond, Some(timeout));
/// }
/// ```
pub fn wait<F>(fd: RawFd, cond: F, timeout: Option<Duration>) -> bool
where
    F: Fn() -> bool,
{
    if cond() {
        return true;
    }

    let start = Instant::now();

    let mut t = timeout;

    loop {
        let wait_timeout = match t {
            Some(duration) => duration.as_millis() as i32,
            None => -1,
        };
        wait_file_changes(fd, wait_timeout);

        if let Some(duration) = timeout {
            let elapsed = start.elapsed();
            if elapsed >= duration {
                return false;
            }
            t = Some(duration - elapsed);
        }

        if cond() {
            return true;
        }
    }
}

/// Wrapper for `libc::epoll_wait`
fn wait_file_changes(fd: RawFd, timeout: i32) -> bool {
    let mut buf: [libc::epoll_event; 10] = [libc::epoll_event { events: 0, u64: 0 }; 10];

    let result = unsafe {
        libc::epoll_wait(
            fd,
            buf.as_mut_ptr() as *mut libc::epoll_event,
            buf.len() as i32,
            timeout,
        ) as i32
    };

    result > 0
}