pub trait Encodable {
// Required method
fn to_bytes(self, dst: &mut [u8]) -> Result<usize, Error>;
}
Expand description
The Encodable
trait defines the interface for encoding a type into bytes.
The trait provides methods for serializing an instance of a type into a byte array or writing it directly into an output writer. The trait is flexible, allowing various types, including primitives, structures, and collections, to implement custom serialization logic.
The trait offers two key methods for encoding:
- The first,
to_bytes
, takes a mutable byte slice as a destination buffer. This method encodes the object directly into the provided buffer, returning the number of bytes written or an error if the encoding process fails. - The second,
to_writer
, (only available when not compiling forno-std
) accepts a writer as a destination for the encoded bytes, allowing the serialized data to be written to any implementor of theWrite
trait.
Implementing types can define custom encoding logic, and this trait is especially useful when dealing with different data structures that need to be serialized for transmission.