aopt_core/value/
initializer.rs1use std::fmt::Debug;
2
3use crate::map::ErasedTy;
4use crate::Error;
5
6use super::AnyValue;
7
8#[cfg(feature = "sync")]
9mod __initializer {
10
11 use super::*;
12
13 pub trait InitializeValue<T: ErasedTy>: Send + Sync {
14 type Error: Into<Error>;
15
16 fn prepare_value(&mut self) -> Result<T, Self::Error>;
17 }
18
19 impl<Func, Err, T: ErasedTy> InitializeValue<T> for Func
20 where
21 Err: Into<Error>,
22 Func: FnMut() -> Result<T, Err> + Send + Sync,
23 {
24 type Error = Err;
25
26 fn prepare_value(&mut self) -> Result<T, Self::Error> {
27 (self)()
28 }
29 }
30
31 pub type InitHandler<T> = Box<dyn FnMut(&mut T) -> Result<(), Error> + Send + Sync>;
32}
33
34#[cfg(not(feature = "sync"))]
35mod __initializer {
36
37 use super::*;
38
39 pub trait InitializeValue<T: ErasedTy> {
40 type Error: Into<Error>;
41
42 fn prepare_value(&mut self) -> Result<T, Self::Error>;
43 }
44
45 impl<Func, Err, T: ErasedTy> InitializeValue<T> for Func
46 where
47 Err: Into<Error>,
48 Func: FnMut() -> Result<T, Err>,
49 {
50 type Error = Err;
51
52 fn prepare_value(&mut self) -> Result<T, Self::Error> {
53 (self)()
54 }
55 }
56
57 pub type InitHandler<T> = Box<dyn FnMut(&mut T) -> Result<(), Error>>;
58}
59
60pub use __initializer::InitHandler;
61pub use __initializer::InitializeValue;
62
63pub struct ValInitializer(InitHandler<AnyValue>);
65
66impl Debug for ValInitializer {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_tuple("ValInitializer").field(&"{...}").finish()
69 }
70}
71
72impl ValInitializer {
73 pub fn new<U: ErasedTy>(mut init: impl InitializeValue<Vec<U>> + 'static) -> Self {
74 Self(Box::new(move |erased_val| {
75 erased_val.set(init.prepare_value().map_err(Into::into)?);
76 Ok(())
77 }))
78 }
79
80 pub fn new_value<U: Clone + ErasedTy>(val: U) -> Self {
81 Self(Box::new(move |erased_val| {
82 erased_val.set(vec![val.clone()]);
83 Ok(())
84 }))
85 }
86
87 pub fn new_values<U: Clone + ErasedTy>(vals: Vec<U>) -> Self {
88 Self(Box::new(move |erased_val| {
89 erased_val.set(vals.clone());
90 Ok(())
91 }))
92 }
93
94 pub fn fallback() -> Self {
96 Self(Box::new(|_| Ok(())))
97 }
98
99 pub fn invoke(&mut self, arg: &mut AnyValue) -> Result<(), Error> {
100 (self.0)(arg)
101 }
102
103 pub fn values<T: ErasedTy>(&mut self) -> Result<Option<Vec<T>>, Error> {
105 let mut any_value = AnyValue::new();
106 self.invoke(&mut any_value)?;
107 Ok(any_value.remove())
108 }
109}
110
111#[cfg(not(feature = "sync"))]
112impl<T: FnMut(&mut AnyValue) -> Result<(), Error> + 'static> From<T> for ValInitializer {
113 fn from(value: T) -> Self {
114 Self(Box::new(value))
115 }
116}
117
118#[cfg(feature = "sync")]
119impl<T: FnMut(&mut AnyValue) -> Result<(), Error> + Send + Sync + 'static> From<T>
120 for ValInitializer
121{
122 fn from(value: T) -> Self {
123 Self(Box::new(value))
124 }
125}