miniconf/
leaf.rs

1use core::{
2    any::Any,
3    fmt::Display,
4    num::NonZero,
5    ops::{Deref, DerefMut},
6};
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::{Error, Keys, Traversal, TreeAny, TreeDeserialize, TreeKey, TreeSerialize, Walk};
11
12/// `Serialize`/`Deserialize`/`Any` leaf
13///
14/// This wraps [`Serialize`], [`Deserialize`], and [`Any`] into `Tree` a leaf node.
15///
16/// ```
17/// use miniconf::{json, Leaf, Tree};
18/// let mut s = Leaf(0);
19/// json::set(&mut s, "", b"7").unwrap();
20/// assert!(matches!(*s, 7));
21/// ```
22#[derive(
23    Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize,
24)]
25#[serde(transparent)]
26#[repr(transparent)]
27pub struct Leaf<T: ?Sized>(pub T);
28
29impl<T: ?Sized> Deref for Leaf<T> {
30    type Target = T;
31    #[inline]
32    fn deref(&self) -> &Self::Target {
33        &self.0
34    }
35}
36
37impl<T: ?Sized> DerefMut for Leaf<T> {
38    #[inline]
39    fn deref_mut(&mut self) -> &mut Self::Target {
40        &mut self.0
41    }
42}
43
44impl<T> Leaf<T> {
45    /// Extract just the inner
46    #[inline]
47    pub fn into_inner(self) -> T {
48        self.0
49    }
50}
51
52impl<T> From<T> for Leaf<T> {
53    #[inline]
54    fn from(value: T) -> Self {
55        Self(value)
56    }
57}
58
59impl<T: Display> Display for Leaf<T> {
60    #[inline]
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        self.0.fmt(f)
63    }
64}
65
66impl<T: ?Sized> TreeKey for Leaf<T> {
67    #[inline]
68    fn traverse_all<W: Walk>() -> W {
69        W::leaf()
70    }
71
72    #[inline]
73    fn traverse_by_key<K, F, E>(mut keys: K, _func: F) -> Result<usize, Error<E>>
74    where
75        K: Keys,
76        F: FnMut(usize, Option<&'static str>, NonZero<usize>) -> Result<(), E>,
77    {
78        keys.finalize()?;
79        Ok(0)
80    }
81}
82
83impl<T: Serialize + ?Sized> TreeSerialize for Leaf<T> {
84    #[inline]
85    fn serialize_by_key<K, S>(&self, mut keys: K, ser: S) -> Result<S::Ok, Error<S::Error>>
86    where
87        K: Keys,
88        S: Serializer,
89    {
90        keys.finalize()?;
91        self.0.serialize(ser).map_err(|err| Error::Inner(0, err))
92    }
93}
94
95impl<'de, T: Deserialize<'de>> TreeDeserialize<'de> for Leaf<T> {
96    #[inline]
97    fn deserialize_by_key<K, D>(&mut self, mut keys: K, de: D) -> Result<(), Error<D::Error>>
98    where
99        K: Keys,
100        D: Deserializer<'de>,
101    {
102        keys.finalize()?;
103        self.0 = T::deserialize(de).map_err(|err| Error::Inner(0, err))?;
104        Ok(())
105    }
106
107    #[inline]
108    fn probe_by_key<K, D>(mut keys: K, de: D) -> Result<(), Error<D::Error>>
109    where
110        K: Keys,
111        D: Deserializer<'de>,
112    {
113        keys.finalize()?;
114        T::deserialize(de).map_err(|err| Error::Inner(0, err))?;
115        Ok(())
116    }
117}
118
119impl<T: Any> TreeAny for Leaf<T> {
120    #[inline]
121    fn ref_any_by_key<K>(&self, mut keys: K) -> Result<&dyn Any, Traversal>
122    where
123        K: Keys,
124    {
125        keys.finalize()?;
126        Ok(&self.0)
127    }
128
129    #[inline]
130    fn mut_any_by_key<K>(&mut self, mut keys: K) -> Result<&mut dyn Any, Traversal>
131    where
132        K: Keys,
133    {
134        keys.finalize()?;
135        Ok(&mut self.0)
136    }
137}
138
139/////////////////////////////////////////////////////////////////////////////////////////
140
141/// `TryFrom<&str>`/`AsRef<str>` leaf
142///
143/// This wraps [`TryFrom<&str>`] and [`AsRef<str>`] into a `Tree*` leaf.
144/// [`TreeAny`] is implemented but denied access at runtime.
145/// It is especially useful to support enum variant switching using `strum`.
146/// Inner enum variant field access can be implemented using `defer`.
147///
148/// ```
149/// use miniconf::{json, Leaf, StrLeaf, Tree};
150/// #[derive(Tree, strum::AsRefStr, strum::EnumString)]
151/// enum En {
152///     A(Leaf<i32>),
153///     B(Leaf<f32>),
154/// }
155/// #[derive(Tree)]
156/// struct S {
157///     e: StrLeaf<En>,
158///     #[tree(typ="En", defer=(*self.e))]
159///     t: (),
160/// }
161/// let mut s = S {
162///     e: StrLeaf(En::A(9.into())),
163///     t: (),
164/// };
165/// json::set(&mut s, "/e", b"\"B\"").unwrap();
166/// json::set(&mut s, "/t/B", b"1.2").unwrap();
167/// assert!(matches!(*s.e, En::B(Leaf(1.2))));
168/// ```
169#[derive(
170    Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize,
171)]
172#[serde(transparent)]
173#[repr(transparent)]
174pub struct StrLeaf<T: ?Sized>(pub T);
175
176impl<T: ?Sized> Deref for StrLeaf<T> {
177    type Target = T;
178    #[inline]
179    fn deref(&self) -> &Self::Target {
180        &self.0
181    }
182}
183
184impl<T: ?Sized> DerefMut for StrLeaf<T> {
185    #[inline]
186    fn deref_mut(&mut self) -> &mut Self::Target {
187        &mut self.0
188    }
189}
190
191impl<T> StrLeaf<T> {
192    /// Extract just the inner
193    #[inline]
194    pub fn into_inner(self) -> T {
195        self.0
196    }
197}
198
199impl<T> From<T> for StrLeaf<T> {
200    #[inline]
201    fn from(value: T) -> Self {
202        Self(value)
203    }
204}
205
206impl<T: ?Sized> TreeKey for StrLeaf<T> {
207    #[inline]
208    fn traverse_all<W: Walk>() -> W {
209        W::leaf()
210    }
211
212    #[inline]
213    fn traverse_by_key<K, F, E>(mut keys: K, _func: F) -> Result<usize, Error<E>>
214    where
215        K: Keys,
216        F: FnMut(usize, Option<&'static str>, NonZero<usize>) -> Result<(), E>,
217    {
218        keys.finalize()?;
219        Ok(0)
220    }
221}
222
223impl<T: AsRef<str> + ?Sized> TreeSerialize for StrLeaf<T> {
224    #[inline]
225    fn serialize_by_key<K, S>(&self, mut keys: K, ser: S) -> Result<S::Ok, Error<S::Error>>
226    where
227        K: Keys,
228        S: Serializer,
229    {
230        keys.finalize()?;
231        let name = self.0.as_ref();
232        name.serialize(ser).map_err(|err| Error::Inner(0, err))
233    }
234}
235
236impl<'de, T: TryFrom<&'de str>> TreeDeserialize<'de> for StrLeaf<T> {
237    #[inline]
238    fn deserialize_by_key<K, D>(&mut self, mut keys: K, de: D) -> Result<(), Error<D::Error>>
239    where
240        K: Keys,
241        D: Deserializer<'de>,
242    {
243        keys.finalize()?;
244        let name = Deserialize::deserialize(de).map_err(|err| Error::Inner(0, err))?;
245        self.0 = T::try_from(name).or(Err(Traversal::Access(0, "Could not convert from str")))?;
246        Ok(())
247    }
248
249    #[inline]
250    fn probe_by_key<K, D>(mut keys: K, de: D) -> Result<(), Error<D::Error>>
251    where
252        K: Keys,
253        D: Deserializer<'de>,
254    {
255        keys.finalize()?;
256        let name = Deserialize::deserialize(de).map_err(|err| Error::Inner(0, err))?;
257        T::try_from(name).or(Err(Traversal::Access(0, "Could not convert from str")))?;
258        Ok(())
259    }
260}
261
262impl<T> TreeAny for StrLeaf<T> {
263    #[inline]
264    fn ref_any_by_key<K>(&self, mut keys: K) -> Result<&dyn Any, Traversal>
265    where
266        K: Keys,
267    {
268        keys.finalize()?;
269        Err(Traversal::Access(0, "No Any access for StrLeaf"))
270    }
271
272    #[inline]
273    fn mut_any_by_key<K>(&mut self, mut keys: K) -> Result<&mut dyn Any, Traversal>
274    where
275        K: Keys,
276    {
277        keys.finalize()?;
278        Err(Traversal::Access(0, "No Any access for StrLeaf"))
279    }
280}
281
282impl<T: Display> Display for StrLeaf<T> {
283    #[inline]
284    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
285        self.0.fmt(f)
286    }
287}
288
289/// Deny any value access
290#[derive(
291    Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize,
292)]
293#[serde(transparent)]
294#[repr(transparent)]
295pub struct Deny<T: ?Sized>(pub T);
296
297impl<T: ?Sized> Deref for Deny<T> {
298    type Target = T;
299    #[inline]
300    fn deref(&self) -> &Self::Target {
301        &self.0
302    }
303}
304
305impl<T: ?Sized> DerefMut for Deny<T> {
306    #[inline]
307    fn deref_mut(&mut self) -> &mut Self::Target {
308        &mut self.0
309    }
310}
311
312impl<T> Deny<T> {
313    /// Extract just the inner
314    #[inline]
315    pub fn into_inner(self) -> T {
316        self.0
317    }
318}
319
320impl<T> From<T> for Deny<T> {
321    #[inline]
322    fn from(value: T) -> Self {
323        Self(value)
324    }
325}
326
327impl<T: ?Sized> TreeKey for Deny<T> {
328    #[inline]
329    fn traverse_all<W: Walk>() -> W {
330        W::leaf()
331    }
332
333    #[inline]
334    fn traverse_by_key<K, F, E>(mut keys: K, _func: F) -> Result<usize, Error<E>>
335    where
336        K: Keys,
337        F: FnMut(usize, Option<&'static str>, NonZero<usize>) -> Result<(), E>,
338    {
339        keys.finalize()?;
340        Ok(0)
341    }
342}
343
344impl<T: ?Sized> TreeSerialize for Deny<T> {
345    #[inline]
346    fn serialize_by_key<K, S>(&self, mut keys: K, _ser: S) -> Result<S::Ok, Error<S::Error>>
347    where
348        K: Keys,
349        S: Serializer,
350    {
351        keys.finalize()?;
352        Err(Traversal::Access(0, "Denied").into())
353    }
354}
355
356impl<'de, T: ?Sized> TreeDeserialize<'de> for Deny<T> {
357    #[inline]
358    fn deserialize_by_key<K, D>(&mut self, mut keys: K, _de: D) -> Result<(), Error<D::Error>>
359    where
360        K: Keys,
361        D: Deserializer<'de>,
362    {
363        keys.finalize()?;
364        Err(Traversal::Access(0, "Denied").into())
365    }
366
367    #[inline]
368    fn probe_by_key<K, D>(mut keys: K, _de: D) -> Result<(), Error<D::Error>>
369    where
370        K: Keys,
371        D: Deserializer<'de>,
372    {
373        keys.finalize()?;
374        Err(Traversal::Access(0, "Denied").into())
375    }
376}
377
378impl<T> TreeAny for Deny<T> {
379    #[inline]
380    fn ref_any_by_key<K>(&self, mut keys: K) -> Result<&dyn Any, Traversal>
381    where
382        K: Keys,
383    {
384        keys.finalize()?;
385        Err(Traversal::Access(0, "Denied"))
386    }
387
388    #[inline]
389    fn mut_any_by_key<K>(&mut self, mut keys: K) -> Result<&mut dyn Any, Traversal>
390    where
391        K: Keys,
392    {
393        keys.finalize()?;
394        Err(Traversal::Access(0, "Denied"))
395    }
396}