echo/
echo.rs

1extern crate futures;
2extern crate tokio_core;
3extern crate async_readline;
4
5use futures::stream::Stream;
6use tokio_core::io::{Io};
7use tokio_core::reactor::Core;
8
9use std::io::{self, Write};
10
11use tokio_core::io::{Codec, EasyBuf};
12
13struct CharCodec;
14
15impl Codec for CharCodec {
16    type In = u8;
17    type Out = String;
18
19    fn decode(&mut self, buf: &mut EasyBuf) -> Result<Option<Self::In>, io::Error> {
20        if buf.len() == 0 {
21            return Ok(None)
22        }
23
24        let ret = buf.as_ref()[0];
25        buf.drain_to(1);
26        Ok(Some(ret))
27    }
28
29    fn encode(&mut self, msg: Self::Out, buf: &mut Vec<u8>) -> io::Result<()> {
30        write!(buf, "{}", msg)?;
31        Ok(())
32    }
33}
34
35fn main() {
36    // Create the event loop that will drive this server
37    let mut l = Core::new().unwrap();
38    let handle = l.handle();
39
40    let stdio = async_readline::RawStdio::new(&handle).unwrap();
41    let (stdin, stdout, _) = stdio.split();
42
43    let framed_in = stdin.framed(CharCodec);
44    let framed_out = stdout.framed(CharCodec);
45
46    let done = framed_in
47        .map(move |ch| {
48            format!("got: {}\n", ch)
49        })
50        .forward(framed_out);
51
52    l.run(done).unwrap();
53}