nuit_core/utils/
binding.rs

1use std::{rc::Rc, fmt};
2
3/// A pair of a getter and a setter, encapsulating a reference to some value.
4#[derive(Clone)]
5pub struct Binding<T> {
6    get: Rc<dyn Fn() -> T>,
7    set: Rc<dyn Fn(T)>,
8}
9
10impl<T> Binding<T> where T: 'static {
11    pub fn new(get: impl Fn() -> T + 'static, set: impl Fn(T) + 'static) -> Self {
12        Self { get: Rc::new(get), set: Rc::new(set) }
13    }
14
15    pub fn get(&self) -> T {
16        (self.get)()
17    }
18
19    pub fn set(&self, value: T) {
20        (self.set)(value)
21    }
22}
23
24impl<T> Binding<T> where T: Clone + 'static {
25    pub fn constant(value: T) -> Self {
26        Self::new(move || value.clone(), |_| {})
27    }
28}
29
30impl<T> fmt::Debug for Binding<T> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "Binding")
33    }
34}