pub trait Encode {
type Item;
// Required methods
fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize>;
fn start_encoding(&mut self, item: Self::Item) -> Result<()>;
fn requiring_bytes(&self) -> ByteCount;
// Provided method
fn is_idle(&self) -> bool { ... }
}Expand description
This trait allows for encoding items into a byte sequence incrementally.
Required Associated Types§
Required Methods§
Sourcefn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize>
fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize>
Encodes the items in the encoder and writes the encoded bytes to the given buffer.
It returns the number of bytes written to the given buffer.
If the encoded bytes are larger than the length of buf,
the encoder must consume as many bytes in the buffer as possible.
The completion of the encoding can be detected by using is_idle method.
If self.is_idle() returns false but the number of written bytes in the last encode invocation
is smaller than the length of buf, it means the encoder has been suspended its work in any reasons.
In that case the encoder may require some instructions from clients to resume the work,
but its concrete method is beyond the scope of this trait.
The encoded bytes that could not be written to the given buffer is held by
the encoder until the next invocation of the encode method.
§Errors
Encoders return the following kinds of errors as necessary:
ErrorKind::InvalidInput:- An item that the encoder could not encode was passed
ErrorKind::UnexpectedEos:- The output byte stream has reached the end in the middle of an encoding process
ErrorKind::InconsistentState:- The state of the encoder bocame inconsistent
- This means the implementation contains a bug
ErrorKind::Other:- Other errors has occurred
Sourcefn start_encoding(&mut self, item: Self::Item) -> Result<()>
fn start_encoding(&mut self, item: Self::Item) -> Result<()>
Tries to start encoding the given item.
If the encoder has no items to be encoded and the passed item is valid, it must accept the item.
§Errors
ErrorKind::EncoderFull:- The encoder currently cannot accept any more items
ErrorKind::InvalidInput:- An invalid item was passed
ErrorKind::InconsistentState:- The state of the encoder bocame inconsistent
- This means the implementation contains a bug
ErrorKind::Other:- Other errors has occurred
Sourcefn requiring_bytes(&self) -> ByteCount
fn requiring_bytes(&self) -> ByteCount
Returns the number of bytes required to encode all the items in the encoder.
If there are no items to be encoded, the encoder must return ByteCount::Finite(0).