Skip to main content

Serializer

Trait Serializer 

Source
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 ?Sized bounds to accept both owned and borrowed forms (e.g., Serializer<str> accepts &str).

Required Methods§

Source

fn serialize( &self, topic: &str, data: Option<&T>, ) -> Result<Option<Vec<u8>>, Error>

Convert data into a byte array.

It is recommended to serialize None data to None byte array.

§Arguments
  • topic - topic associated with data
  • data - typed data; may be None
§Returns

Serialized bytes; may be None.

Provided Methods§

Source

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 data
  • headers - record headers
  • data - typed data; may be None
§Returns

Serialized bytes; may be None.

Source

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.

Implementors§