Module gj::io [] [src]

Asynchronous input and output.

Example

use gj::{EventLoop, Promise};
use gj::io::{AsyncRead, AsyncWrite, Slice, unix};

fn echo(stream: unix::Stream, buf: Vec<u8>) -> Promise<(), ::std::io::Error> {
    stream.try_read(buf, 1).lift().then(move |(stream, buf, n)| {
        if n == 0 { // EOF
            Promise::ok(())
        } else {
            stream.write(Slice::new(buf, n)).lift().then(move |(stream, slice)| {
                echo(stream, slice.buf)
            })
        }
    })
}

EventLoop::top_level(|wait_scope| {
    let (stream1, stream2) = try!(unix::Stream::new_pair());
    let promise1 = echo(stream1, vec![0; 5]); // Tiny buffer just to be difficult.
    let promise2 = stream2.write(b"hello world").lift().then(|(stream, _)| {
        stream.read(vec![0; 11], 11).map(|(_, buf, _)| {
            assert_eq!(buf, b"hello world");
            Ok(())
        }).lift()
    });
    try!(Promise::all(vec![promise1, promise2].into_iter()).wait(wait_scope));
    Ok(())
}).expect("top level");

Modules

tcp

TCP sockets.

Structs

Error

A ::std::io::Error that also carries along some state. Useful for tasks from which you want to return the state in both the error and the success cases, like Promise<S, Error<S>>.

Slice
Timer

Traits

AsyncRead

A nonblocking input bytestream.

AsyncWrite

A nonblocking output bytestream.