aboutsummaryrefslogtreecommitdiff
path: root/incria/src/thunk.rs
blob: 2fe7873b44eb75cc1672277b367a70548d6b5641 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//! A mapper based on a function from keys to values.
use std::pin::Pin;

use crate::lazy_mapping::{LazyMapper, LazyMappingBackend};

/// A function from keys to values.
///
/// Should be pure, except for use of other mappings. This ensures recomputation is done when needed.
pub trait Thunk<K, V>: Send + 'static {
    fn compute(&self, key: K) -> Pin<Box<dyn std::future::Future<Output = V> + Send + '_>>;
}

#[derive(Debug, Default)]
pub struct ThunkBackend<T> {
    thunk: T,
}

impl<T> ThunkBackend<T> {
    pub fn new(thunk: T) -> Self {
        Self { thunk }
    }

    pub fn thunk(&self) -> &T {
        &self.thunk
    }
}

impl<K, V: 'static, T> LazyMappingBackend<K, V> for ThunkBackend<T>
where
    T: Thunk<K, V>,
{
    async fn is_dirty(&self, _: &K) -> bool {
        false // only dirty if marked dirty by someting else
    }

    fn compute(&self, key: K) -> impl std::future::Future<Output = V> + Send + '_ {
        self.thunk.compute(key)
    }
}

pub type ThunkMapper<K, V, T> = LazyMapper<K, V, ThunkBackend<T>>;