pub fn validate_schema<T: OwnedStruct>() -> Result<()>Expand description
Check that a schema can be represented as JSON at all.
At present this means checking that $Json.flatten terminates. A flattened
field splices its members into the parent’s JSON object instead of nesting
them, so a struct that flattens a field of its own type — directly, or
through a chain of other flattened fields and groups — describes an object
of infinite width. The C++ codec rejects such a schema outright with
“cyclic JSON flattening detected”; this function is how you ask for the
same verdict.
T is the generated Owned type of the struct you encode or decode as the
root. Every struct reachable from it is checked too — including through
plain fields and list element types — so validating the root type covers
the whole message.
§When to call this
Once, at startup or from a test — not per message. A schema is compile-time
data: capnpc generates it and nothing can change it at runtime, so a
cyclic flatten is a mistake in your .capnp file rather than a property of
any particular input. Encoding and decoding therefore do not run this
check, and paying for it on every call would be a permanent tax to
re-discover a build-time bug.
#[test]
fn schema_is_json_encodable() {
capnp_json::validate_schema::<my_schema_capnp::my_struct::Owned>()
.expect("schema must be JSON-encodable");
}Skipping it is not dangerous, only less informative: a cyclic schema still
gets rejected when decoded, by the recursion limit
(CodecOptions::recursion_limit), just with a message that points at the
depth rather than at the cycle.