miniconf/json.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 `TreeKey::lookup::<Path<_, '/'>, _>(...)`/
7//! `TreeKey::nodes::<Path<_, '/'>>()`.
8//!
9//! ```
10//! use miniconf::{json, Leaf, Tree};
11//! #[derive(Tree, Default)]
12//! struct S {
13//! foo: Leaf<u32>,
14//! bar: [Leaf<u16>; 2],
15//! };
16//! let mut s = S::default();
17//! json::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::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::{Error, IntoKeys, Path, 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 [Error].
37#[inline]
38pub fn set<'de, T: TreeDeserialize<'de> + ?Sized>(
39 tree: &mut T,
40 path: &str,
41 data: &'de [u8],
42) -> Result<usize, Error<de::Error>> {
43 set_by_key(tree, Path::<_, '/'>::from(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 [Error].
55#[inline]
56pub fn get<T: TreeSerialize + ?Sized>(
57 tree: &T,
58 path: &str,
59 data: &mut [u8],
60) -> Result<usize, Error<ser::Error>> {
61 get_by_key(tree, Path::<_, '/'>::from(path), data)
62}
63
64/// Update a node by key.
65///
66/// # Returns
67/// The number of bytes consumed from `data` or an [Error].
68#[inline]
69pub fn set_by_key<'de, T: TreeDeserialize<'de> + ?Sized, K: IntoKeys>(
70 tree: &mut T,
71 keys: K,
72 data: &'de [u8],
73) -> Result<usize, Error<de::Error>> {
74 let mut de = de::Deserializer::new(data, None);
75 tree.deserialize_by_key(keys.into_keys(), &mut de)?;
76 de.end().map_err(Error::Finalization)
77}
78
79/// Retrieve a serialized value by key.
80///
81/// # Returns
82/// The number of bytes used in the `data` buffer or an [Error].
83#[inline]
84pub fn get_by_key<T: TreeSerialize + ?Sized, K: IntoKeys>(
85 tree: &T,
86 keys: K,
87 data: &mut [u8],
88) -> Result<usize, Error<ser::Error>> {
89 let mut ser = ser::Serializer::new(data);
90 tree.serialize_by_key(keys.into_keys(), &mut ser)?;
91 Ok(ser.end())
92}