Skip to main content

SerializeRecordFields

Write a struct as a map from each field's name to its value, asking the context to write each value.

Overview​

In cgp-serde, a serialization library built with Context-Generic Programming (CGP), SerializeRecordFields serializes a struct that derives nothing from Serde. It reads the struct's field list through CGP's field traits, which #[derive(CgpData)] provides, and asks the context, the type whose wiring holds the application's choices, to write each field's value. So one generic provider serves every struct, and each field is encoded however the context encodes its type.

Definition​

pub struct SerializeRecordFields;

#[cgp_impl(SerializeRecordFields)]
impl<Value> ValueSerializer<Value>
where
Value: HasFields,
Value::Fields: FieldsSerializer<Self, Value>,
{ ... }

HasFields gives the struct's field list as a type. FieldsSerializer is a private trait that walks that list, and it requires, for each field, that the struct exposes it through HasField and that the context can serialize the field's type.

Usage​

Import it from cgp_serde::providers. Derive the field traits on the struct, and wire it beside an entry for each field's type, as in the basic example:

#[derive(Debug, Eq, PartialEq, CgpData)]
pub struct Payload {
pub quantity: u64,
pub message: String,
pub data: Vec<u8>,
}

// in the context's table:
@ValueSerializerComponent.u64: UseSerde,
@ValueSerializerComponent.String: SerializeString,
@ValueSerializerComponent.Vec<u8>: SerializeHex,
@ValueSerializerComponent.Payload: SerializeRecordFields,

That context writes a Payload as {"quantity":42,"message":"hello","data":"010203"}.

Behavior​

The provider starts a map and writes one entry per field, in declaration order. Each key is the Rust field name exactly as written, and each value is the field wrapped with the context in SerializeWithContext. The provider writes a map, with serialize_map, where a derived Serialize impl writes a struct, and starts it without a declared length. JSON shows no difference; see using a format for formats that do.

Only structs with named fields work, since a field's name is its key.

Context dependencies​

CanSerializeValue<F> for the type F of every field: an entry in the context's table for each field type the struct uses.

Pairing​

DeserializeRecordFields reads the map back. The two agree on the shape: a map keyed by Rust field names.

When to use it​

Reach for SerializeRecordFields for a struct whose fields should follow the context's choices, and for any struct whose crate should not depend on serde. For a struct that already derives Serde's Serialize and needs no per-application choice, UseSerde uses that derive.

The ideas behind it​

Source​


An AI agent wrote this page using the CGP knowledge base. Its content was verified against the project's source. See How AI is used in this project.