miniconf/
json_core.rs

1//! `TreeSerialize`/`TreeDeserialize` with "JSON and `/`".
2//!
3//! Access items with `'/'` as path separator and JSON (from `serde-json-core`)
4//! as serialization/deserialization payload format.
5//!
6//! Paths used here are reciprocal to `TreeSchema::lookup::<Path<_, '/'>, _>(...)`/
7//! `TreeSchema::SCHEMA.nodes::<Path<_, '/'>>()`.
8//!
9//! ```
10//! use miniconf::{json_core, Tree};
11//! #[derive(Tree, Default)]
12//! struct S {
13//!     foo: u32,
14//!     bar: [u16; 2],
15//! };
16//! let mut s = S::default();
17//! json_core::set(&mut s, "/bar/1", b"9").unwrap();
18//! assert_eq!(s.bar[1], 9);
19//! let mut buf = [0u8; 10];
20//! let len = json_core::get(&mut s, "/bar/1", &mut buf[..]).unwrap();
21//! assert_eq!(&buf[..len], b"9");
22//! ```
23
24use serde_json_core::{de, ser};
25
26use crate::{IntoKeys, Path, SerdeError, TreeDeserialize, TreeSerialize};
27
28/// Update a node by path.
29///
30/// # Args
31/// * `tree` - The `TreeDeserialize` to operate on.
32/// * `path` - The path to the node. Everything before the first `'/'` is ignored.
33/// * `data` - The serialized data making up the content.
34///
35/// # Returns
36/// The number of bytes consumed from `data` or an [SerdeError].
37pub fn set<'de>(
38    tree: &mut (impl TreeDeserialize<'de> + ?Sized),
39    path: &str,
40    data: &'de [u8],
41) -> Result<usize, SerdeError<de::Error>> {
42    set_by_key(tree, Path::<_, '/'>(path), data)
43}
44
45/// Retrieve a serialized value by path.
46///
47/// # Args
48/// * `tree` - The `TreeDeserialize` to operate on.
49/// * `path` - The path to the node. Everything before the first `'/'` is ignored.
50/// * `data` - The buffer to serialize the data into.
51///
52/// # Returns
53/// The number of bytes used in the `data` buffer or an [SerdeError].
54pub fn get(
55    tree: &(impl TreeSerialize + ?Sized),
56    path: &str,
57    data: &mut [u8],
58) -> Result<usize, SerdeError<ser::Error>> {
59    get_by_key(tree, Path::<_, '/'>(path), data)
60}
61
62/// Update a node by key.
63///
64/// # Returns
65/// The number of bytes consumed from `data` or an [SerdeError].
66pub fn set_by_key<'de>(
67    tree: &mut (impl TreeDeserialize<'de> + ?Sized),
68    keys: impl IntoKeys,
69    data: &'de [u8],
70) -> Result<usize, SerdeError<de::Error>> {
71    let mut de = de::Deserializer::new(data, None);
72    tree.deserialize_by_key(keys.into_keys(), &mut de)?;
73    de.end().map_err(SerdeError::Finalization)
74}
75
76/// Retrieve a serialized value by key.
77///
78/// # Returns
79/// The number of bytes used in the `data` buffer or an [SerdeError].
80pub fn get_by_key(
81    tree: &(impl TreeSerialize + ?Sized),
82    keys: impl IntoKeys,
83    data: &mut [u8],
84) -> Result<usize, SerdeError<ser::Error>> {
85    let mut ser = ser::Serializer::new(data);
86    tree.serialize_by_key(keys.into_keys(), &mut ser)?;
87    Ok(ser.end())
88}