Last active
May 19, 2017 23:42
-
-
Save mark-i-m/7045422098699044ddc87deb7be6fe7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate bytes; | |
extern crate serde; | |
extern crate serde_json; | |
extern crate tokio_io; | |
extern crate tokio_proto; | |
use tokio_io::{AsyncRead, AsyncWrite}; | |
use tokio_io::codec::{Decoder, Encoder, Framed}; | |
use tokio_proto::pipeline::ServerProto; | |
use bytes::BytesMut; | |
use errors::*; | |
use tile::TileState; | |
#[derive(Debug, Deserialize, Serialize)] | |
pub enum Msg { | |
GetState, | |
State(TileState), | |
} | |
#[derive(Default)] | |
pub struct PaintCodec; | |
impl Decoder for PaintCodec { | |
type Item = Msg; | |
type Error = Error; | |
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> { | |
if let Some(i) = (&String::from_utf8_lossy(src.as_ref())).find("END") { | |
let msg_str = src.split_to(i); | |
serde_json::from_slice(msg_str.as_ref()) | |
.map(|v| Some(v)) | |
.chain_err(|| "Unable to deserialize message") | |
} else { | |
Ok(None) | |
} | |
} | |
} | |
impl Encoder for PaintCodec { | |
type Item = Msg; | |
type Error = Error; | |
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<()> { | |
let msg = serde_json::to_string(&item) | |
.chain_err(|| "Unable to serialize message")?; | |
dst.extend(msg.as_bytes()); | |
dst.extend(b"END"); | |
Ok(()) | |
} | |
} | |
pub struct PaintProto; | |
impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for PaintProto { | |
type Request = Msg; | |
type Response = Msg; | |
type Transport = Framed<T, PaintCodec>; | |
type BindTransport = Result<Self::Transport>; | |
fn bind_transport(&self, io: T) -> Self::BindTransport { | |
Ok(io.framed(PaintCodec)) | |
} | |
} |
Author
mark-i-m
commented
May 19, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment