Struct popol::Source

source ·
#[repr(C)]
pub struct Source { /* private fields */ }
Expand description

A source of readiness events, eg. a net::TcpStream.

Implementations§

source§

impl Source

source

pub unsafe fn raw<T: FromRawFd>(&self) -> T

Return the source from the underlying raw file descriptor.

Safety

Calls FromRawFd::from_raw_fd. The returned object will cause the file to close when dropped.

source

pub fn set(&mut self, events: Interest)

Set events to wait for on this source.

source

pub fn unset(&mut self, events: Interest)

Unset events to wait for on this source.

source

pub fn raw_events(&self) -> Events

Returns raw representation of events which fired during poll.

source

pub fn is_writable(self) -> bool

The source is writable.

Examples found in repository?
examples/tcp-listener.rs (line 39)
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
fn main() -> io::Result<()> {
    let listener = net::TcpListener::bind("0.0.0.0:8888")?;
    let mut sources = Sources::new();
    let mut events = Vec::new();
    let mut peers = HashMap::new();

    // It's important to set the socket in non-blocking mode. This allows
    // us to know when to stop accepting connections.
    listener.set_nonblocking(true)?;

    // Register the listener socket, using the corresponding identifier.
    sources.register(Source::Listener, &listener, popol::interest::READ);

    loop {
        sources.poll(&mut events, Timeout::Never)?;

        for event in events.iter() {
            match event.key {
                Source::Peer(addr) if event.is_readable() => {
                    // Peer socket has data to be read.
                    println!("{} is readable", addr);
                }
                Source::Peer(addr) if event.is_writable() => {
                    // Peer socket is ready to be written.
                    println!("{} is writable", addr);
                }
                Source::Peer(_addr) => {
                    // Peer socket had an error or hangup.
                }
                Source::Listener => loop {
                    let (conn, addr) = match listener.accept() {
                        Ok((conn, addr)) => (conn, addr),

                        Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                        Err(e) => return Err(e),
                    };
                    conn.set_nonblocking(true)?;

                    // Register the new peer using the `Peer` variant of `Source`.
                    sources.register(Source::Peer(addr), &conn, popol::interest::ALL);
                    // Save the connection to make sure it isn't dropped.
                    peers.insert(addr, conn);
                },
            }
        }
    }
}
source

pub fn is_readable(self) -> bool

The source is readable.

Examples found in repository?
examples/tcp.rs (line 19)
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
fn main() -> io::Result<()> {
    let mut stream = net::TcpStream::connect("localhost:8888").unwrap();
    let mut events = Vec::new();
    let mut sources = Sources::new();

    stream.set_nonblocking(true)?;
    sources.register(stream.peer_addr()?, &stream, popol::interest::READ);

    loop {
        sources.poll(&mut events, Timeout::Never)?;

        for event in events.drain(..) {
            if event.is_readable() {
                let mut buf = [0; 32];

                match stream.read(&mut buf[..]) {
                    Ok(n) if n > 0 => {
                        let msg = std::str::from_utf8(&buf[..n]).unwrap();
                        println!("{}: {}", event.key, msg.trim());
                    }
                    Ok(_) => {
                        // Connection closed.
                        return stream.shutdown(net::Shutdown::Both);
                    }
                    Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
                        // Nothing left to read.
                        break;
                    }
                    Err(err) => {
                        panic!("{}", err);
                    }
                }
            }
        }
    }
}
More examples
Hide additional examples
examples/stdin.rs (line 28)
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
fn main() -> io::Result<()> {
    // Create a registry to hold I/O sources.
    let mut sources = popol::Sources::with_capacity(1);
    // Create an events buffer to hold readiness events.
    let mut events = Vec::with_capacity(1);

    // Register the program's standard input as a source of "read" readiness events.
    sources.register((), &io::stdin(), popol::interest::READ);

    // Wait on our event sources for at most 6 seconds. If an event source is
    // ready before then, process its events. Otherwise, timeout.
    match sources.poll(&mut events, popol::Timeout::from_secs(6)) {
        Ok(_) => {}
        Err(err) if err.kind() == io::ErrorKind::TimedOut => process::exit(1),
        Err(err) => return Err(err),
    }

    // Iterate over source events. Since we only have one source
    // registered, this will only iterate once.
    for event in events.drain(..) {
        // An error occured with the standard input.
        if event.is_error() {
            panic!("error on {:?}", io::stdin());
        }
        // The standard input has data ready to be read.
        if event.is_readable() || event.is_hangup() {
            let mut buf = [0; 1024];

            // Read what we can from standard input and echo it.
            match io::stdin().read(&mut buf[..]) {
                Ok(n) => io::stdout().write_all(&buf[..n])?,
                Err(err) => panic!("{}", err),
            }
        }
    }

    Ok(())
}
examples/tcp-listener.rs (line 35)
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
fn main() -> io::Result<()> {
    let listener = net::TcpListener::bind("0.0.0.0:8888")?;
    let mut sources = Sources::new();
    let mut events = Vec::new();
    let mut peers = HashMap::new();

    // It's important to set the socket in non-blocking mode. This allows
    // us to know when to stop accepting connections.
    listener.set_nonblocking(true)?;

    // Register the listener socket, using the corresponding identifier.
    sources.register(Source::Listener, &listener, popol::interest::READ);

    loop {
        sources.poll(&mut events, Timeout::Never)?;

        for event in events.iter() {
            match event.key {
                Source::Peer(addr) if event.is_readable() => {
                    // Peer socket has data to be read.
                    println!("{} is readable", addr);
                }
                Source::Peer(addr) if event.is_writable() => {
                    // Peer socket is ready to be written.
                    println!("{} is writable", addr);
                }
                Source::Peer(_addr) => {
                    // Peer socket had an error or hangup.
                }
                Source::Listener => loop {
                    let (conn, addr) = match listener.accept() {
                        Ok((conn, addr)) => (conn, addr),

                        Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                        Err(e) => return Err(e),
                    };
                    conn.set_nonblocking(true)?;

                    // Register the new peer using the `Peer` variant of `Source`.
                    sources.register(Source::Peer(addr), &conn, popol::interest::ALL);
                    // Save the connection to make sure it isn't dropped.
                    peers.insert(addr, conn);
                },
            }
        }
    }
}
source

pub fn is_hangup(self) -> bool

The source has been disconnected.

Examples found in repository?
examples/stdin.rs (line 28)
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
fn main() -> io::Result<()> {
    // Create a registry to hold I/O sources.
    let mut sources = popol::Sources::with_capacity(1);
    // Create an events buffer to hold readiness events.
    let mut events = Vec::with_capacity(1);

    // Register the program's standard input as a source of "read" readiness events.
    sources.register((), &io::stdin(), popol::interest::READ);

    // Wait on our event sources for at most 6 seconds. If an event source is
    // ready before then, process its events. Otherwise, timeout.
    match sources.poll(&mut events, popol::Timeout::from_secs(6)) {
        Ok(_) => {}
        Err(err) if err.kind() == io::ErrorKind::TimedOut => process::exit(1),
        Err(err) => return Err(err),
    }

    // Iterate over source events. Since we only have one source
    // registered, this will only iterate once.
    for event in events.drain(..) {
        // An error occured with the standard input.
        if event.is_error() {
            panic!("error on {:?}", io::stdin());
        }
        // The standard input has data ready to be read.
        if event.is_readable() || event.is_hangup() {
            let mut buf = [0; 1024];

            // Read what we can from standard input and echo it.
            match io::stdin().read(&mut buf[..]) {
                Ok(n) => io::stdout().write_all(&buf[..n])?,
                Err(err) => panic!("{}", err),
            }
        }
    }

    Ok(())
}
source

pub fn is_error(self) -> bool

An error has occurred on the source.

Note that this function is best used in combination with Self::is_invalid, to detect all error cases.

Examples found in repository?
examples/stdin.rs (line 24)
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
fn main() -> io::Result<()> {
    // Create a registry to hold I/O sources.
    let mut sources = popol::Sources::with_capacity(1);
    // Create an events buffer to hold readiness events.
    let mut events = Vec::with_capacity(1);

    // Register the program's standard input as a source of "read" readiness events.
    sources.register((), &io::stdin(), popol::interest::READ);

    // Wait on our event sources for at most 6 seconds. If an event source is
    // ready before then, process its events. Otherwise, timeout.
    match sources.poll(&mut events, popol::Timeout::from_secs(6)) {
        Ok(_) => {}
        Err(err) if err.kind() == io::ErrorKind::TimedOut => process::exit(1),
        Err(err) => return Err(err),
    }

    // Iterate over source events. Since we only have one source
    // registered, this will only iterate once.
    for event in events.drain(..) {
        // An error occured with the standard input.
        if event.is_error() {
            panic!("error on {:?}", io::stdin());
        }
        // The standard input has data ready to be read.
        if event.is_readable() || event.is_hangup() {
            let mut buf = [0; 1024];

            // Read what we can from standard input and echo it.
            match io::stdin().read(&mut buf[..]) {
                Ok(n) => io::stdout().write_all(&buf[..n])?,
                Err(err) => panic!("{}", err),
            }
        }
    }

    Ok(())
}
source

pub fn is_invalid(self) -> bool

The source is not valid.

Trait Implementations§

source§

impl AsRawFd for &Source

source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
source§

impl AsRawFd for Source

source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
source§

impl Clone for Source

source§

fn clone(&self) -> Source

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Source

source§

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

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

impl Default for Source

source§

fn default() -> Source

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

impl Copy for Source

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

§

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 Twhere U: TryFrom<T>,

§

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.