Skip to main content

encode

Function encode 

Source
pub fn encode<T>(value: &T, buf: &mut BytesMut) -> Result<(), KafkaError>
where T: AvroSchema + Serialize + Send + Sync + 'static,
Expand description

Writes value as an Avro datum under the schema its own type declares.

The schema drives the encoding, so the value’s Rust types reach the wire as the numeric and string types the schema names, with no JSON document in between. No registry is involved and no envelope is written: on a registry-backed topic the datum travels inside one, which AvroCodec::registry adds. A service publishes through a codec; this is for a tool that works on datum bytes outside an app’s dispatch.

The buffer is written into rather than returned, so a caller that already holds one (a publish path, a batch) pays no intermediate allocation.

§Errors

Returns KafkaError::WireFormat when the type’s schema cannot be built, or when the value does not fit the schema it declares.

§Examples

An export tool writing one bare datum per file, reusing one buffer for all of them:

use std::error::Error;
use std::fs;
use std::path::Path;

use apache_avro::AvroSchema;
use ruststream::BytesMut;
use ruststream_rdkafka::avro;
use serde::Serialize;

#[derive(Serialize, AvroSchema)]
struct Order {
    id: i64,
}

fn export(orders: &[Order], dir: &Path) -> Result<(), Box<dyn Error>> {
    let mut buf = BytesMut::new();
    for order in orders {
        buf.clear();
        avro::encode(order, &mut buf)?;
        fs::write(dir.join(format!("{}.avro", order.id)), &buf)?;
    }
    Ok(())
}