pub trait Encodable<E>where
E: BaseEncoder,{
type Error: From<E::Error>;
// Required method
fn encode(&self, encoder: &mut E) -> Result<(), Self::Error>;
}
Expand description
A trait for types that can be encoded into a specific encoder.
Defines a generic interface for encoding data structures into an encoder.
§A note about purity
Implementations of Encodable
must be pure. That means:
- No side effects: Implementations must not modify global or external state.
- Deterministic: Given the same input and encoder, the output must always be the same.
- No panics: Panicking inside an
encode
implementation is considered a bug.
Ignoring these rules may lead to logic errors.
§Encoder Specialization
On nightly Rust, you can use trait specialization
to implement optimized encodings for specific encoders, such as
SizeEncoder
. For example, you may want to use
this if your encoder runs computationally expensive operations for obtaining
the size of the encoded form.
§Errors
Implementations must return an appropriate error if encoding fails. Errors can occur if:
- The encoder encounters an internal error (e.g., out of space).
- The encoded output would be invalid.
Control flow may depend on these errors (unlike core::fmt::Write
).