January 2018
Beginner to intermediate
454 pages
10h 8m
English
Let's first write the decoder:
use std::io; use bytes::BytesMut; use cmd::Command; use error::Error; impl Decoder for FtpCodec { type Item = Command; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Command>> { if let Some(index) = find_crlf(buf) { let line = buf.split_to(index); buf.split_to(2); // Remove \r\n. Command::new(line.to_vec()) .map(|command| Some(command)) .map_err(Error::to_io_error) } else { Ok(None) } } }
The Decoder trait has two associated types, Item and Error. The former is the type produced when we're able to decode a sequence of bytes. The latter is the type of the error. We first check if there the bytes CR and LF. If we don't find them, we return Ok(None)
Read now
Unlock full access