Skip to main content

Builder

Struct Builder 

Source
pub struct Builder<D, F = (), P = ()> { /* private fields */ }
Expand description

Configures optional callbacks before deserializing a value.

Created by DeserializerExt::track. Callbacks retain their concrete types and need no boxing. filter and peek (with the peek feature) can be configured in either order. Call .deserialize() to execute.

CallbacksBehavior
NeitherConsume unknown values without calling user code.
Filter onlyRun the filter and consume values directly.
Peek onlyInspect every unknown value with context None::<()>.
BothInspect selected values with the filter’s Some(context).

Filter and peek errors reject the input. The first callback error is returned unchanged, even if nested code catches the intermediate error.

Implementations§

Source§

impl<D, F, P> Builder<D, F, P>

Source

pub fn filter<'de, C, Filter>(self, filter: Filter) -> Builder<D, Filter, P>
where D: Deserializer<'de>, Filter: FnMut(&Path<'_>) -> Result<Option<C>, D::Error>,

Sets a callback that runs before an unknown value is consumed.

Return Some(context) to select the value for peek, None to consume it directly, or D::Error to reject the input. The context type C is chosen by the caller; peek receives Some(context) for selected values. Without a peek callback, both successful results consume values directly. Calling this method again replaces the previous filter.

use serde::{Deserialize, de::Error};
use serde_unknown::DeserializerExt;

#[derive(Deserialize)]
struct Config { port: u16 }

let mut deserializer = serde_json::Deserializer::from_str(
    r#"{"port":8080,"forbidden":true}"#,
);
let result: Result<Config, _> = (&mut deserializer)
    .track()
    .filter(|path| {
        if path.matches(&["<root>", "forbidden"]) {
            return Err(Error::custom("forbidden field"));
        }
        Ok(None::<()>)
    })
    .deserialize();
assert_eq!(result.err().unwrap().to_string(), "forbidden field");
Source

pub fn peek<'de, C, Peek>(self, peek: Peek) -> Builder<D, F, Peek>
where D: Deserializer<'de>, Peek: FnMut(&Path<'_>, Option<C>, Value) -> Result<(), D::Error>,

Sets a callback that receives an owned JSON value for selected fields.

Requires the peek feature. A filter supplies Some(context); returning None from the filter skips this callback. Without a filter, every unknown value is selected and the context is None with type Option<()>.

The callback runs after the complete subtree is parsed. It is not called if parsing fails. Return Ok(()) to continue or D::Error to reject the input. Calling this method again replaces the previous peek callback.

Inspection can allocate and requires deserialize_any support and values representable by serde_json::Value. Duplicate object keys and some format-specific representations are not preserved.

use serde::Deserialize;
use serde_unknown::DeserializerExt;

#[derive(Deserialize)]
struct Config { port: u16 }

let mut deserializer = serde_json::Deserializer::from_str(
    r#"{"port":8080,"future":{"enabled":true},"other":false}"#,
);
let config: Config = (&mut deserializer)
    .track()
    .filter(|path| Ok(path.matches(&["<root>", "future"]).then_some("future")))
    .peek(|_, context, value| {
        assert_eq!(context, Some("future"));
        assert_eq!(value, serde_json::json!({"enabled": true}));
        Ok(())
    })
    .deserialize()?;
deserializer.end()?;
assert_eq!(config.port, 8080);
Source§

impl<'de, D: Deserializer<'de>> Builder<D>

Source

pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, D::Error>

Deserializes T using the configured callbacks.

Returns the first callback error unchanged, or the underlying deserializer’s result when no callback rejects the input.

Source§

impl<'de, D: Deserializer<'de>, F, C> Builder<D, F>
where F: FnMut(&Path<'_>) -> Result<Option<C>, D::Error>,

Source

pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, D::Error>

Deserializes T using the configured callbacks.

Returns the first callback error unchanged, or the underlying deserializer’s result when no callback rejects the input.

Source§

impl<'de, D: Deserializer<'de>, P> Builder<D, (), P>
where P: FnMut(&Path<'_>, Option<()>, Value) -> Result<(), D::Error>,

Source

pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, D::Error>

Deserializes T using the configured callbacks.

Returns the first callback error unchanged, or the underlying deserializer’s result when no callback rejects the input.

Source§

impl<'de, D: Deserializer<'de>, F, P, C> Builder<D, F, P>
where F: FnMut(&Path<'_>) -> Result<Option<C>, D::Error>, P: FnMut(&Path<'_>, Option<C>, Value) -> Result<(), D::Error>,

Source

pub fn deserialize<T: Deserialize<'de>>(self) -> Result<T, D::Error>

Deserializes T using the configured callbacks.

Returns the first callback error unchanged, or the underlying deserializer’s result when no callback rejects the input.

Auto Trait Implementations§

§

impl<D, F, P> Freeze for Builder<D, F, P>
where D: Freeze, Option<F>: Freeze, Option<P>: Freeze,

§

impl<D, F, P> RefUnwindSafe for Builder<D, F, P>

§

impl<D, F, P> Send for Builder<D, F, P>
where D: Send, Option<F>: Send, Option<P>: Send,

§

impl<D, F, P> Sync for Builder<D, F, P>
where D: Sync, Option<F>: Sync, Option<P>: Sync,

§

impl<D, F, P> Unpin for Builder<D, F, P>
where D: Unpin, Option<F>: Unpin, Option<P>: Unpin,

§

impl<D, F, P> UnsafeUnpin for Builder<D, F, P>

§

impl<D, F, P> UnwindSafe for Builder<D, F, P>

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> 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, 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.