mirror of
https://codeberg.org/unspeaker/tengri.git
synced 2026-01-31 10:56:41 +01:00
53 lines
1.5 KiB
Rust
53 lines
1.5 KiB
Rust
use crate::*;
|
|
|
|
/// Lazily-evaluated [Draw]able.
|
|
pub struct Lazy<E, T, F>(PhantomData<(E, T)>, F);
|
|
impl<E: Out, T: Draw<E> + Layout<E>, F: Fn()->T> Lazy<E, T, F> {
|
|
pub const fn new (thunk: F) -> Self {
|
|
Self(PhantomData, thunk)
|
|
}
|
|
}
|
|
impl<E: Out, T: Draw<E> + Layout<E>, F: Fn()->T> Content<E> for Lazy<E, T, F> {
|
|
fn content (&self) -> impl Draw<E> + Layout<E> + '_ {
|
|
(self.1)()
|
|
}
|
|
}
|
|
|
|
pub struct Thunk<E: Out, F: Fn(&mut E)>(PhantomData<E>, F);
|
|
impl<E: Out, F: Fn(&mut E)> Thunk<E, F> {
|
|
pub const fn new (draw: F) -> Self { Self(PhantomData, draw) }
|
|
}
|
|
impl<E: Out, F: Fn(&mut E)> Draw<E> for Thunk<E, F> {
|
|
fn draw (&self, to: &mut E) { (self.1)(to) }
|
|
}
|
|
impl<E: Out, F: Fn(&mut E)> Layout<E> for Thunk<E, F> {
|
|
fn layout (&self, to: E::Area) -> E::Area { to }
|
|
}
|
|
|
|
#[derive(Debug, Default)] pub struct Memo<T, U> {
|
|
pub value: T,
|
|
pub view: Arc<RwLock<U>>
|
|
}
|
|
|
|
impl<T: PartialEq, U> Memo<T, U> {
|
|
pub fn new (value: T, view: U) -> Self {
|
|
Self { value, view: Arc::new(view.into()) }
|
|
}
|
|
pub fn update <R> (
|
|
&mut self,
|
|
newval: T,
|
|
draw: impl Fn(&mut U, &T, &T)->R
|
|
) -> Option<R> {
|
|
if newval != self.value {
|
|
let result = draw(&mut*self.view.write().unwrap(), &newval, &self.value);
|
|
self.value = newval;
|
|
return Some(result);
|
|
}
|
|
None
|
|
}
|
|
}
|
|
|
|
/// Clear a pre-allocated buffer, then write into it.
|
|
#[macro_export] macro_rules! rewrite {
|
|
($buf:ident, $($rest:tt)*) => { |$buf,_,_|{ $buf.clear(); write!($buf, $($rest)*) } }
|
|
}
|