Trait tokio_core::io::Codec [] [src]

pub trait Codec {
    type In;
    type Out;
    fn decode(&mut self, buf: &mut EasyBuf) -> Result<Option<Self::In>, Error>;
    fn encode(&mut self, msg: Self::Out, buf: &mut Vec<u8>) -> Result<()>;

    fn decode_eof(&mut self, buf: &mut EasyBuf) -> Result<Self::In> { ... }
}

Encoding and decoding of frames via buffers.

This trait is used when constructing an instance of Framed. It provides two types: In, for decoded input frames, and Out, for outgoing frames that need to be encoded. It also provides methods to actually perform the encoding and decoding, which work with corresponding buffer types.

The trait itself is implemented on a type that can track state for decoding or encoding, which is particularly useful for streaming parsers. In many cases, though, this type will simply be a unit struct (e.g. struct HttpCodec).

Associated Types

The type of decoded frames.

The type of frames to be encoded.

Required Methods

Attempts to decode a frame from the provided buffer of bytes.

This method is called by Framed whenever bytes are ready to be parsed. The provided buffer of bytes is what's been read so far, and this instance of Decode can determine whether an entire frame is in the buffer and is ready to be returned.

If an entire frame is available, then this instance will remove those bytes from the buffer provided and return them as a decoded frame. Note that removing bytes from the provided buffer doesn't always necessarily copy the bytes, so this should be an efficient operation in most circumstances.

If the bytes look valid, but a frame isn't fully available yet, then Ok(None) is returned. This indicates to the Framed instance that it needs to read some more bytes before calling this method again.

Finally, if the bytes in the buffer are malformed then an error is returned indicating why. This informs Framed that the stream is now corrupt and should be terminated.

Encodes a frame into the buffer provided.

This method will encode msg into the byte buffer provided by buf. The buf provided is an internal buffer of the Framed instance and will be written out when possible.

Provided Methods

A default method available to be called when there are no more bytes available to be read from the underlying I/O.

This method defaults to calling decode and returns an error if Ok(None) is returned. Typically this doesn't need to be implemented unless the framing protocol differs near the end of the stream.

Implementors