pub trait Serializer<T: ?Sized> {
// Required method
fn serialize(
&self,
topic: &str,
data: Option<&T>,
) -> Result<Option<Vec<u8>>, Error>;
// Provided methods
fn serialize_headers(
&self,
topic: &str,
_headers: &RecordHeaders,
data: Option<&T>,
) -> Result<Option<Vec<u8>>, Error> { ... }
fn serialize_owned_headers(
&self,
topic: &str,
headers: &RecordHeaders,
data: Option<T>,
) -> Result<Option<Vec<u8>>, Error>
where T: Sized { ... }
}Expand description
An interface for converting objects to bytes.
Corresponds to Java’s org.apache.kafka.common.serialization.Serializer<T>.
§Type Parameters
T- Type to be serialized from. Use?Sizedbounds to accept both owned and borrowed forms (e.g.,Serializer<str>accepts&str).
Required Methods§
Provided Methods§
Sourcefn serialize_headers(
&self,
topic: &str,
_headers: &RecordHeaders,
data: Option<&T>,
) -> Result<Option<Vec<u8>>, Error>
fn serialize_headers( &self, topic: &str, _headers: &RecordHeaders, data: Option<&T>, ) -> Result<Option<Vec<u8>>, Error>
Convert data into a byte array, with access to the record headers.
The default implementation ignores the headers and delegates to
serialize. Override this method in custom
serializer implementations that need to inspect or modify headers during
serialization (e.g., for schema registry integration).
Corresponds to Java’s Serializer.serialize(String topic, Headers headers, T data)
(Serializer.java:82). The two Java overloads intersect on
{topic, data}, which is exactly serialize(String, T) (:62) — so that
one keeps the plain name and this one is suffixed with the parameter that
distinguishes it (CLAUDE.md §2).
§Arguments
topic- topic associated with dataheaders- record headersdata- typed data; may beNone
§Returns
Serialized bytes; may be None.
Sourcefn serialize_owned_headers(
&self,
topic: &str,
headers: &RecordHeaders,
data: Option<T>,
) -> Result<Option<Vec<u8>>, Error>where
T: Sized,
fn serialize_owned_headers(
&self,
topic: &str,
headers: &RecordHeaders,
data: Option<T>,
) -> Result<Option<Vec<u8>>, Error>where
T: Sized,
Serialize owned data, avoiding a clone when the input is already bytes.
The default implementation borrows data and delegates to
serialize_headers.
Implementations for types that are already byte buffers (e.g. Vec<u8>)
can override this to pass ownership through without copying.