pub struct Context { /* private fields */ }Expand description
Configuration for serializations and deserializations.
A context holds typed values which are given to a serialization or
deserialization from the outside: policies like how unknown fields are
handled (UnknownFields), how bytes are
decoded from strings (BytesFormat), limits for
untrusted input (Limits), whether formats
provide source locations (TrackLocations) or
data that types need, such as the variants of open enums. It’s created
once and given to every serialization or deserialization that uses it,
usually with the deserializer and serializer configurations of the
formats (for instance deser_json::DeserializerConfig::builder().context(context)):
use deser::de::DuplicateKeys;
use deser::Context;
use std::collections::BTreeMap;
let context = Context::with(DuplicateKeys::Last);
let config = deser_json::DeserializerConfig::builder()
.context(context.clone())
.build();
let map: BTreeMap<String, u32> = config.from_str(r#"{"a": 1, "a": 2}"#).unwrap();
assert_eq!(map["a"], 2);A single deserialization can be given a context of its own in the setup
callback of Deserializer::deserialize_with
(and serializations in the one of serialize_with). Its values take
precedence, the values of the format’s context are added for the types
it has no value for:
use deser::de::{Deserializer, DuplicateKeys, Limits};
use deser::Context;
use std::collections::BTreeMap;
let config = deser_json::DeserializerConfig::builder()
.context(Context::with(DuplicateKeys::Last))
.build();
let limits = Context::with(Limits::builder().max_items(2).build());
let input = r#"{"a": 1, "a": 2, "b": 3}"#;
let err = deser_json::Deserializer::from_str_with_config(input, config)
.deserialize_with::<BTreeMap<String, u32>, _>(|driver| {
driver.set_context(limits.clone())
})
.unwrap_err();
assert_eq!(err.to_string(), "LimitExceeded: too many items at line 1 column 18");The readers and writers of the io module have
set_context methods too.
The values of the context are the defaults of the extension values of
the State: State::get returns
the value of the state if there is one and the value of the context
otherwise. The values that the state holds change during a
serialization or deserialization (for instance a format or a type sets
a value for a part of the data), the context does not change.
Cloning a context is cheap, the values are shared. Values are
Debug, Send and Sync like the extension values of the state
so that contexts can be shared between threads. Values that collect
results (like UnknownFields::Collect)
are shared too: everything that uses the context reports to them, so
they belong into the state of a single deserialization instead.
§Values
These are the values that deser itself reads from a context. Unless
noted otherwise, a value in the State takes
precedence over the one of the context.
Deserialization:
UnknownFields: what happens with keys of structs that no field takes. Ignored by default.DuplicateKeys: what happens if a key is given more than once. Rejected by default (query strings and environment variables use the last value).LexicalRules: how lexical atoms are interpreted. Strict by default (query strings, environment variables and CSV are lenient).Limits: limits of the nesting depth, the number of events and items and the length of strings and bytes. Unlimited by default. Only read from the context and enforced by theDeserializeDriver.CollectErrors: collects the errors of the whole deserialization instead of failing on the first one, optionally up to a limit. Off by default. Only read from the context.TrackLocations: asks the formats to provide theSourceto resolve input ranges into lines and columns. Off by default.
Serialization and deserialization:
BytesFormat: how bytes are represented in formats without native bytes. Base64 by default.OpenEnums(with theopen-enumsfeature): the registered variants of open enums. Required to deserialize open enums, only the registered variants can be deserialized.
Any other type that is Debug, Send, Sync and 'static can
be a value too. Types and formats read their own values with
State::get (which falls back to the context) or
State::context:
use deser::{Context, State};
#[derive(Debug)]
struct Greeting(&'static str);
let mut state = State::new();
state.set_context(Context::with(Greeting("hello")));
assert_eq!(state.get::<Greeting>().unwrap().0, "hello");Implementations§
Source§impl Context
impl Context
Sourcepub fn with<T: Debug + Send + Sync + 'static>(value: T) -> Context
pub fn with<T: Debug + Send + Sync + 'static>(value: T) -> Context
Creates a context with a value.
Trait Implementations§
impl Eq for Context
Source§impl PartialEq for Context
Contexts are equal if they share their values (one is a clone of the
other and neither was changed since) or if both are empty. The values
themselves are not compared, they do not need to implement PartialEq.
impl PartialEq for Context
Contexts are equal if they share their values (one is a clone of the
other and neither was changed since) or if both are empty. The values
themselves are not compared, they do not need to implement PartialEq.
impl RefUnwindSafe for Context
impl UnwindSafe for Context
Auto Trait Implementations§
impl Freeze for Context
impl Send for Context
impl Sync for Context
impl Unpin for Context
impl UnsafeUnpin for Context
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.