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].
37#[inline]
38pub fn set<'de>(
39 tree: &mut (impl TreeDeserialize<'de> + ?Sized),
40 path: &str,
41 data: &'de [u8],
42) -> Result<usize, SerdeError<de::Error>> {
43 set_by_key(tree, Path::<_, '/'>(path), data)
44}
45
46/// Retrieve a serialized value by path.
47///
48/// # Args
49/// * `tree` - The `TreeDeserialize` to operate on.
50/// * `path` - The path to the node. Everything before the first `'/'` is ignored.
51/// * `data` - The buffer to serialize the data into.
52///
53/// # Returns
54/// The number of bytes used in the `data` buffer or an [SerdeError].
55#[inline]
56pub fn get(
57 tree: &(impl TreeSerialize + ?Sized),
58 path: &str,
59 data: &mut [u8],
60) -> Result<usize, SerdeError<ser::Error>> {
61 get_by_key(tree, Path::<_, '/'>(path), data)
62}
63
64/// Update a node by key.
65///
66/// # Returns
67/// The number of bytes consumed from `data` or an [SerdeError].
68pub fn set_by_key<'de>(
69 tree: &mut (impl TreeDeserialize<'de> + ?Sized),
70 keys: impl IntoKeys,
71 data: &'de [u8],
72) -> Result<usize, SerdeError<de::Error>> {
73 let mut de = de::Deserializer::new(data, None);
74 tree.deserialize_by_key(keys.into_keys(), &mut de)?;
75 de.end().map_err(SerdeError::Finalization)
76}
77
78/// Retrieve a serialized value by key.
79///
80/// # Returns
81/// The number of bytes used in the `data` buffer or an [SerdeError].
82pub fn get_by_key(
83 tree: &(impl TreeSerialize + ?Sized),
84 keys: impl IntoKeys,
85 data: &mut [u8],
86) -> Result<usize, SerdeError<ser::Error>> {
87 let mut ser = ser::Serializer::new(data);
88 tree.serialize_by_key(keys.into_keys(), &mut ser)?;
89 Ok(ser.end())
90}