Skip to main content

Context

Struct Context 

Source
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 the DeserializeDriver.
  • 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 the Source to 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 the open-enums feature): 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

Source

pub const fn new() -> Context

Creates an empty context.

Source

pub fn with<T: Debug + Send + Sync + 'static>(value: T) -> Context

Creates a context with a value.

Source

pub fn set<T: Debug + Send + Sync + 'static>(&mut self, value: T)

Sets a value, replacing a value of the same type.

If the values are shared with clones of the context, they are copied (the values themselves are shared).

Source

pub fn get<T: Debug + Send + Sync + 'static>(&self) -> Option<&T>

Returns the value of a type.

Source

pub fn is_empty(&self) -> bool

Returns true if the context holds no values.

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Context

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

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.

Source§

fn eq(&self, other: &Context) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl RefUnwindSafe for Context

Source§

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.