SerializeWithContext
Pair a context with a value as an ordinary Serde Serialize value.
Overview
In cgp-serde, a serialization library built with
Context-Generic Programming (CGP), SerializeWithContext is the way into Serde's formats.
Serde's functions, such as serde_json::to_string, accept a value that implements Serialize and
have no place for a context, the type whose wiring holds an application's choices. The adapter
carries both, and its Serialize impl writes the value through the context's wiring. Providers use
the same adapter to hand each nested value back to the context from inside Serde's compound writers.
Definition
pub struct SerializeWithContext<'a, Context, T> {
pub context: &'a Context,
pub value: &'a T,
}
impl<'a, Context, T> SerializeWithContext<'a, Context, T> {
pub fn new(context: &'a Context, value: &'a T) -> Self { ... }
}
impl<'a, Context, T> serde::Serialize for SerializeWithContext<'a, Context, T>
where
Context: CanSerializeValue<T>,
{ ... }
It lives in cgp_serde::types.
Usage
Build it with new and pass it to any Serde format. From the
messages example:
let serialized =
serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap();
Both fields are public, so a provider can build it with a struct literal, as the library's own providers do.
Behavior
Serializing the adapter calls the context's serializer for T, so the context's wiring decides the
output, and every nested value goes back through the same wiring. The format's own error comes back
unchanged, since the adapter involves none of CGP's error handling. T must be a sized type.
Context dependencies
Context: CanSerializeValue<T>, which needs whatever the provider wired for T needs.
Pairing
DeserializeWithContext is the adapter for reading.
When to use it
Reach for SerializeWithContext to write with any Serde format, and to hand a nested value to
one of Serde's compound writers inside a provider. For a JSON string in the context's own error
type, SerializeToJsonString wraps it.
Related constructs
SerializeIteratorandSerializeRecordFieldsuse it for each item and field.
The ideas behind it
- The bridge to Serde: how a context reaches a Serde API.
- Re-entrant providers: the adapter inside a provider.
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.