mirror of
https://github.com/callumio/suck.git
synced 2025-12-17 03:29:21 +00:00
Use separate .set and .set_mut methods
This commit is contained in:
parent
3a3cfa8a3b
commit
47b3bd5015
2 changed files with 21 additions and 3 deletions
|
|
@ -73,13 +73,23 @@ where
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Set a closure
|
||||
/// Set a closure that implements [Fn]
|
||||
pub fn set<F>(&self, closure: F) -> Result<(), Error>
|
||||
where
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
self.state
|
||||
.swap(Arc::new(ValueSource::Dynamic(Mutex::new(Box::new(
|
||||
.swap(Arc::new(ValueSource::Dynamic(Box::new(closure))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set a closure that implements [FnMut]
|
||||
pub fn set_mut<F>(&self, closure: F) -> Result<(), Error>
|
||||
where
|
||||
F: FnMut() -> T + Send + Sync + 'static,
|
||||
{
|
||||
self.state
|
||||
.swap(Arc::new(ValueSource::DynamicMut(Mutex::new(Box::new(
|
||||
closure,
|
||||
)))));
|
||||
Ok(())
|
||||
|
|
@ -122,6 +132,13 @@ where
|
|||
match &**state {
|
||||
ValueSource::Static(value) => Ok(Response::Value(value.clone())),
|
||||
ValueSource::Dynamic(closure) => {
|
||||
let value = self.execute_closure_safely(&mut || closure());
|
||||
match value {
|
||||
Ok(v) => Ok(Response::Value(v)),
|
||||
Err(_) => Ok(Response::NoSource), // Closure execution failed
|
||||
}
|
||||
}
|
||||
ValueSource::DynamicMut(closure) => {
|
||||
let mut closure = closure.lock().unwrap();
|
||||
let value = self.execute_closure_safely(&mut *closure);
|
||||
match value {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ pub enum Response<T> {
|
|||
/// Represents the source of values: either static or dynamic
|
||||
pub(crate) enum ValueSource<T> {
|
||||
Static(T),
|
||||
Dynamic(Mutex<Box<dyn FnMut() -> T + Send + Sync + 'static>>),
|
||||
DynamicMut(Mutex<Box<dyn FnMut() -> T + Send + Sync + 'static>>),
|
||||
Dynamic(Box<dyn Fn() -> T + Send + Sync + 'static>),
|
||||
None, // Never set
|
||||
Cleared, // Was set but cleared (closed)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue