Skip to main content

Module json

Module json 

Source
Available on crate feature json only.
Expand description

JSON parse options for protobuf JSON deserialization.

The protobuf JSON spec says parsers should reject unknown fields by default but may provide an option to ignore them. This module exposes that option, matching the per-call semantics of C++ and Java reference implementations.

§Two mutually exclusive APIs: scoped (std) vs global (no_std)

Serde’s Deserialize trait has no context parameter, so runtime options must be passed through ambient state. The available mechanism differs between std and no_std builds — each build exposes exactly one:

BuildMechanismAPIScoping
stdThread-localwith_json_parse_optionsPer-closure, nestable, per-thread
no_stdAtomicPtr to leaked Boxset_global_json_parse_optionsProcess-wide, set-once

The two APIs do not interact. set_global_json_parse_options is only compiled in no_std builds; with_json_parse_options only in std.

§std: scoped per-closure options

use buffa::json::{JsonParseOptions, with_json_parse_options};

let opts = JsonParseOptions::new().ignore_unknown_enum_values(true);
let msg = with_json_parse_options(&opts, || {
    serde_json::from_str::<MyMessage>(json_str)
});
// Options revert to defaults here. Concurrent threads are independent.

§no_std: global set-once options

use buffa::json::{JsonParseOptions, set_global_json_parse_options};

// Call ONCE during startup (e.g. in your init function).
set_global_json_parse_options(
    &JsonParseOptions::new().ignore_unknown_enum_values(true)
);

// All subsequent JSON deserialization uses these options.
let msg: MyMessage = serde_json::from_str(json_str)?;

The global setter is idempotent for identical options — calling it multiple times with the same configuration is a no-op, so initialization from multiple modules is safe as long as they agree. Calling it with different options after the first call triggers a debug_assert! (panic in debug builds; the second call is silently ignored in release). Treat the first successful call as locking in behaviour for the process lifetime.

§no_std caveat: no container filtering

In std, ignore_unknown_enum_values supports filtering: unknown entries in repeated enum or map<_, enum> fields are dropped from the container. This requires temporarily forcing strict mode to get a distinguishable error, which needs the scoped thread-local.

In no_std, only accept-with-default works: unknown singular enum values become the default (0) variant. Unknown entries in containers still produce an error — the filtering behaviour is unavailable.

Structs§

JsonParseOptions
Options controlling protobuf JSON parsing behavior.

Functions§

with_json_parse_optionsstd
Run a closure with the given parse options active.