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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use async_trait::async_trait;
use std::fmt::Debug;

pub trait Cacheable {
    fn identity(&self) -> Vec<u8>;
}

impl<H> Cacheable for H
where
    H: Hash,
{
    fn identity(&self) -> Vec<u8> {
        let mut hasher = DefaultHasher::new();
        self.hash(&mut hasher);
        let hash = hasher.finish();
        hash.to_le_bytes().to_vec()
    }
}

#[derive(Clone)]
pub enum CacheResponse {
    Hit,
    Miss,
}

#[async_trait]
pub trait Cache<E>
where
    E: Debug + Clone + Send + Sync + 'static,
{
    async fn get<CA: Cacheable + Send + Sync + 'static>(
        &mut self,
        cacheable: CA,
    ) -> Result<CacheResponse, crate::error::Error<E>>;
    async fn store(&mut self, identity: Vec<u8>) -> Result<(), crate::error::Error<E>>;
}

#[async_trait]
pub trait ReadableCache<E>
where
    E: Debug + Clone + Send + Sync + 'static,
{
    async fn get<CA: Cacheable + Send + Sync + 'static>(
        &mut self,
        cacheable: CA,
    ) -> Result<CacheResponse, crate::error::Error<E>>;
}

#[async_trait]
impl<C, E> ReadableCache<E> for C
where
    C: Cache<E> + Send + Sync + 'static,
    E: Debug + Clone + Send + Sync + 'static,
{
    async fn get<CA>(&mut self, cacheable: CA) -> Result<CacheResponse, crate::error::Error<E>>
    where
        CA: Cacheable + Send + Sync + 'static,
    {
        Cache::get(self, cacheable).await
    }
}

#[derive(Clone)]
pub struct NopCache {}

#[async_trait]
impl<E> Cache<E> for NopCache
where
    E: Debug + Clone + Send + Sync + 'static,
{
    async fn get<CA: Cacheable + Send + Sync + 'static>(
        &mut self,
        _cacheable: CA,
    ) -> Result<CacheResponse, crate::error::Error<E>> {
        Ok(CacheResponse::Miss)
    }
    async fn store(&mut self, _identity: Vec<u8>) -> Result<(), crate::error::Error<E>> {
        Ok(())
    }
}