pub fn make_field_codec<'env>(
encode_fn: impl Fn(Reader<'_>) -> Result<JsonValue> + 'env,
decode_fn: impl Fn(&JsonValue, Builder<'_>) -> Result<()> + 'env,
) -> impl FieldCodec + 'envExpand description
Build a FieldCodec from an encoder and a decoder closure.
A shorthand for the cases that do not need a named type — the two closures
correspond to FieldCodec::encode_value and
FieldCodec::decode_value. The resulting codec uses the default
decode_member, so it is only suitable for
struct, list and AnyPointer fields; for a primitive, text, data or enum
field, implement FieldCodec directly and override decode_member.
use capnp_json::{make_field_codec, JsonValue};
// Represent a struct's `text` field as the whole JSON value.
let codec = make_field_codec(
|source: capnp::dynamic_value::Reader<'_>| {
let source: capnp::dynamic_struct::Reader<'_> = source.downcast();
let text: capnp::text::Reader<'_> = source.get_named("text")?.downcast();
Ok(JsonValue::String(text.to_str()?.to_owned()))
},
|source: &JsonValue, target: capnp::dynamic_value::Builder<'_>| {
let JsonValue::String(text) = source else {
return Err(capnp::Error::failed("expected a string".into()));
};
let mut target: capnp::dynamic_struct::Builder<'_> = target.downcast();
target.set_named("text", text.as_str().into())
},
);