Skip to main content

ctl_input/
de.rs

1//! Reads a typed value from the located tree a [format](crate::format::Format)
2//! read.
3//!
4//! One serde Deserializer serves every format: it walks the [tree](crate::tree)
5//! and asks the format to resolve each scalar for the type the field needs, so
6//! each format keeps its own scalar rules. A problem comes back as a
7//! [`Refusal`] with a [`Fault`](crate::format::Fault)
8//! and the bytes it sits at; [`Messages`](crate::Messages) words the fault.
9//!
10//! [`Tagged`] reads a node's tag beside its value.
11//!
12//! [`Input`](crate::Input) reads every typed value through this module.
13
14mod access;
15mod error;
16mod node;
17mod tagged;
18
19use std::marker::PhantomData;
20
21use node::{NodeDe, Parent};
22use serde::de::DeserializeOwned;
23pub use tagged::Tagged;
24
25use crate::format::{Format, Refusal};
26use crate::tree::Node;
27
28/// Reads a `T` from `node`, a tree `format` read, resolving each scalar by
29/// `format`'s rules.
30///
31/// The mapping and sequence rules are the same for every format. A struct or
32/// a map needs a mapping, and a sequence, a tuple or a tuple struct needs a
33/// sequence. An enum is a scalar naming a unit variant, or a mapping of one
34/// entry from the variant to its content. An `Option` is `None` for a scalar
35/// that resolves as null and `Some` for any other node.
36///
37/// # Errors
38///
39/// A [`Refusal`] naming the fault and the bytes it sits at: the node the
40/// fault arose in, or the alias that replayed it with
41/// [`Refusal::defined_at`] naming where its value is written. A missing field
42/// sits on the key whose value is the mapping that lacks it, or at the start
43/// of the text for the root mapping.
44///
45/// ```
46/// # #[cfg(feature = "yaml")]
47/// # {
48/// use ctl_input::Limits;
49/// use ctl_input::de::deserialize;
50/// use ctl_input::format::{Format, Reading, YAML};
51/// use serde::Deserialize;
52///
53/// #[derive(Debug, Deserialize, PartialEq)]
54/// struct Config {
55///     port: u16,
56/// }
57///
58/// let tree = YAML.read("port: '8080'\n", &Limits::NONE, Reading::Strict)?;
59/// let config: Config = deserialize(&tree, &YAML)?;
60/// assert_eq!(config, Config { port: 8080 });
61/// # }
62/// # Ok::<(), Box<dyn std::error::Error>>(())
63/// ```
64pub fn deserialize<T: DeserializeOwned>(
65    node: &Node,
66    format: &'static dyn Format,
67) -> Result<T, Refusal> {
68    NodeDe::new(node, format, Parent::Root)
69        .seeded(PhantomData::<T>)
70        .map_err(error::Error::into_refusal)
71}