Message

Trait Message 

Source
pub trait Message:
    Debug
    + Sized
    + Send
    + Sync
    + 'static {
    const MAX_SIZE: usize;

    // Required methods
    fn encode(&self, sink: &mut impl Write) -> usize;
    fn decode(buffer: &[u8]) -> Result<(Self, usize), DecodeError>;

    // Provided method
    fn size_hint(&self) -> Option<usize> { ... }
}
Expand description

A trait that network messages processed by the reactor must implement.

Required Associated Constants§

Source

const MAX_SIZE: usize

The size of the largest expected message. It is important to set this correctly because an incorrect value will interfere with inbound backpressure control and the ability to decode large messages. This is also crucial for DoS protection (resource exhaustion attacks).

Required Methods§

Source

fn encode(&self, sink: &mut impl Write) -> usize

Encodes a message into a writer. This is an in-memory sink that never panics so there is no need to handle the error path.

Returns the number of encoded bytes.

Source

fn decode(buffer: &[u8]) -> Result<(Self, usize), DecodeError>

Provides access to the underlying read buffer. The buffer may contain any number of messages, including no messages at all or only a partial message. If there are enough bytes available to decode a message, the function must return an Ok with the decoded message and the number of bytes it consumed.

If there is not enough data to decode a message (i.e. it is available only partially), Err(DecodeError::NotEnoughData) must be returned. That signals that decoding should be retried when more data comes in. If the message cannot be decoded at all, or exceeds size limits or otherwise represents junk data, Err(DecodeError::MalformedMessage) must be returned. Such peers are disconnected as protocol violators.

Provided Methods§

Source

fn size_hint(&self) -> Option<usize>

If a message has a known size ahead of encoding, that value can be set here. This is useful for outbound backpressure control, so that a message is not preemptively encoded and placed into the send buffer only to be realized that the size of the send buffer will be exceeding its maximum. Getting this wrong can interfere with outbound backpressure control, so if the value is not certain, it is better not to override the method.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§