Poller

Struct Poller 

Source
pub struct Poller { /* private fields */ }
Expand description

定义文件 I/O 事件通知器。

每个实例可以管理多个 fd 的 I/O 事件。

Implementations§

Source§

impl Poller

Source

pub fn new() -> Result<Self, SysError>

创建一个新的 I/O 事件通知器。

Examples found in repository?
examples/callback.rs (line 9)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Create the Poller.
9    let mut poller = Poller::new()?;
10
11    // Callback for handle raised event.
12    let cb: Arc<Callback> = Arc::new(|| -> bool {
13        let mut input = String::new();
14        match stdin().read_line(&mut input) {
15            Ok(n) => {
16                let trimmed = input.trim_end();
17                println!("{} bytes readed: \"{}\"", n, trimmed);
18                // Return false if input 'q'.
19                trimmed != "q"
20            }
21            Err(e) => {
22                println!("error: {}", e);
23                false
24            }
25        }
26    });
27
28    // Add stdin to the watching list of the Poller.
29    poller.add(
30        0,
31        Events::new().read(),
32        Some(Arc::clone(&cb) as EventContext),
33    )?;
34
35    println!("Press ctrl+c or 'q' to exit ...");
36
37    'outer: loop {
38        // Pull all events with 1 seconds timeout.
39        let events = poller.pull_events(1000)?;
40        for (_fd, _events, _ctx) in events.iter() {
41            // Use EventContext to processing the event.
42            if let Some(x) = _ctx {
43                if let Some(cb) = x.downcast_ref::<Callback>() {
44                    if cb() == false {
45                        break 'outer;
46                    }
47                }
48            }
49        }
50    }
51
52    Ok(())
53}
More examples
Hide additional examples
examples/evdev.rs (line 92)
88fn main() -> Result<(), Box<dyn std::error::Error>> {
89    // Open the linux evdev.
90    let evdev = Arc::new(File::open("/dev/input/event0")?);
91    // Create the Poller.
92    let mut poller = Poller::new()?;
93    // Add stdin to the watching list of the Poller.
94    poller.add(0, Events::new().read(), None)?;
95    // Add evdev to the watching list of the Poller.
96    poller.add(
97        evdev.as_raw_fd(),
98        Events::new().read(),
99        Some(Arc::clone(&evdev) as EventContext),
100    )?;
101    // Buffer to read one InputEvent data from evdev.
102    const N: usize = std::mem::size_of::<input_event>();
103    let mut buf: [u8; N] = [0; N];
104
105    println!("Press any key to exit ...");
106
107    'outer: loop {
108        // Pull all events with 1 seconds timeout.
109        let events = poller.pull_events(1000)?;
110        for (_fd, _events, _ctx) in events.iter() {
111            // Exit loop if press any key.
112            if _fd == &0 {
113                break 'outer;
114            }
115            // Use EventContext to processing the event.
116            if let Some(x) = _ctx {
117                if let Some(mut f) = x.downcast_ref::<File>() {
118                    f.read_exact(&mut buf)?;
119                }
120            }
121            // Cast the buffer to &InputEvent.
122            let a = unsafe { std::mem::transmute::<&[u8; N], &InputEvent>(&buf) };
123            // Display the InputEvent.
124            println!("{}", a);
125        }
126    }
127
128    Ok(())
129}
Source

pub fn add( &mut self, fd: i32, events: Events, ctx: Option<EventContext>, ) -> Result<(), SysError>

添加一个文件描述符到监视列表中。

注意: 此函数不会把 fd 的所有权转移到 Poller 内,请确保在 Poller 活动期内 fd 都是可用的。

Examples found in repository?
examples/callback.rs (lines 29-33)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Create the Poller.
9    let mut poller = Poller::new()?;
10
11    // Callback for handle raised event.
12    let cb: Arc<Callback> = Arc::new(|| -> bool {
13        let mut input = String::new();
14        match stdin().read_line(&mut input) {
15            Ok(n) => {
16                let trimmed = input.trim_end();
17                println!("{} bytes readed: \"{}\"", n, trimmed);
18                // Return false if input 'q'.
19                trimmed != "q"
20            }
21            Err(e) => {
22                println!("error: {}", e);
23                false
24            }
25        }
26    });
27
28    // Add stdin to the watching list of the Poller.
29    poller.add(
30        0,
31        Events::new().read(),
32        Some(Arc::clone(&cb) as EventContext),
33    )?;
34
35    println!("Press ctrl+c or 'q' to exit ...");
36
37    'outer: loop {
38        // Pull all events with 1 seconds timeout.
39        let events = poller.pull_events(1000)?;
40        for (_fd, _events, _ctx) in events.iter() {
41            // Use EventContext to processing the event.
42            if let Some(x) = _ctx {
43                if let Some(cb) = x.downcast_ref::<Callback>() {
44                    if cb() == false {
45                        break 'outer;
46                    }
47                }
48            }
49        }
50    }
51
52    Ok(())
53}
More examples
Hide additional examples
examples/evdev.rs (line 94)
88fn main() -> Result<(), Box<dyn std::error::Error>> {
89    // Open the linux evdev.
90    let evdev = Arc::new(File::open("/dev/input/event0")?);
91    // Create the Poller.
92    let mut poller = Poller::new()?;
93    // Add stdin to the watching list of the Poller.
94    poller.add(0, Events::new().read(), None)?;
95    // Add evdev to the watching list of the Poller.
96    poller.add(
97        evdev.as_raw_fd(),
98        Events::new().read(),
99        Some(Arc::clone(&evdev) as EventContext),
100    )?;
101    // Buffer to read one InputEvent data from evdev.
102    const N: usize = std::mem::size_of::<input_event>();
103    let mut buf: [u8; N] = [0; N];
104
105    println!("Press any key to exit ...");
106
107    'outer: loop {
108        // Pull all events with 1 seconds timeout.
109        let events = poller.pull_events(1000)?;
110        for (_fd, _events, _ctx) in events.iter() {
111            // Exit loop if press any key.
112            if _fd == &0 {
113                break 'outer;
114            }
115            // Use EventContext to processing the event.
116            if let Some(x) = _ctx {
117                if let Some(mut f) = x.downcast_ref::<File>() {
118                    f.read_exact(&mut buf)?;
119                }
120            }
121            // Cast the buffer to &InputEvent.
122            let a = unsafe { std::mem::transmute::<&[u8; N], &InputEvent>(&buf) };
123            // Display the InputEvent.
124            println!("{}", a);
125        }
126    }
127
128    Ok(())
129}
Source

pub fn remove(&mut self, fd: i32) -> Result<(), SysError>

将一个文件描述符从监视列表中移除。

Source

pub fn pull_events( &self, timeout_ms: i32, ) -> Result<Vec<EventData<'_>>, SysError>

拉取所有被监测到的 I/O 事件。

§Examples
use poller::{Events, Poller};
let mut poller = Poller::new().unwrap();
poller.add(1, Events::new().with_write(), None).unwrap();
for (fd, events, ctx) in poller.pull_events(1000).unwrap().iter() {
    println!("Fd={}, Events={}, Context={:?}", fd, events, ctx);
}
Examples found in repository?
examples/callback.rs (line 39)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Create the Poller.
9    let mut poller = Poller::new()?;
10
11    // Callback for handle raised event.
12    let cb: Arc<Callback> = Arc::new(|| -> bool {
13        let mut input = String::new();
14        match stdin().read_line(&mut input) {
15            Ok(n) => {
16                let trimmed = input.trim_end();
17                println!("{} bytes readed: \"{}\"", n, trimmed);
18                // Return false if input 'q'.
19                trimmed != "q"
20            }
21            Err(e) => {
22                println!("error: {}", e);
23                false
24            }
25        }
26    });
27
28    // Add stdin to the watching list of the Poller.
29    poller.add(
30        0,
31        Events::new().read(),
32        Some(Arc::clone(&cb) as EventContext),
33    )?;
34
35    println!("Press ctrl+c or 'q' to exit ...");
36
37    'outer: loop {
38        // Pull all events with 1 seconds timeout.
39        let events = poller.pull_events(1000)?;
40        for (_fd, _events, _ctx) in events.iter() {
41            // Use EventContext to processing the event.
42            if let Some(x) = _ctx {
43                if let Some(cb) = x.downcast_ref::<Callback>() {
44                    if cb() == false {
45                        break 'outer;
46                    }
47                }
48            }
49        }
50    }
51
52    Ok(())
53}
More examples
Hide additional examples
examples/evdev.rs (line 109)
88fn main() -> Result<(), Box<dyn std::error::Error>> {
89    // Open the linux evdev.
90    let evdev = Arc::new(File::open("/dev/input/event0")?);
91    // Create the Poller.
92    let mut poller = Poller::new()?;
93    // Add stdin to the watching list of the Poller.
94    poller.add(0, Events::new().read(), None)?;
95    // Add evdev to the watching list of the Poller.
96    poller.add(
97        evdev.as_raw_fd(),
98        Events::new().read(),
99        Some(Arc::clone(&evdev) as EventContext),
100    )?;
101    // Buffer to read one InputEvent data from evdev.
102    const N: usize = std::mem::size_of::<input_event>();
103    let mut buf: [u8; N] = [0; N];
104
105    println!("Press any key to exit ...");
106
107    'outer: loop {
108        // Pull all events with 1 seconds timeout.
109        let events = poller.pull_events(1000)?;
110        for (_fd, _events, _ctx) in events.iter() {
111            // Exit loop if press any key.
112            if _fd == &0 {
113                break 'outer;
114            }
115            // Use EventContext to processing the event.
116            if let Some(x) = _ctx {
117                if let Some(mut f) = x.downcast_ref::<File>() {
118                    f.read_exact(&mut buf)?;
119                }
120            }
121            // Cast the buffer to &InputEvent.
122            let a = unsafe { std::mem::transmute::<&[u8; N], &InputEvent>(&buf) };
123            // Display the InputEvent.
124            println!("{}", a);
125        }
126    }
127
128    Ok(())
129}

Trait Implementations§

Source§

impl Debug for Poller

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Poller

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for Poller

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Poller

§

impl !RefUnwindSafe for Poller

§

impl Send for Poller

§

impl Sync for Poller

§

impl Unpin for Poller

§

impl !UnwindSafe for Poller

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.