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
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use async_trait::async_trait;

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> {
    async fn get<CA: Cacheable + Send + Sync + 'static>(&mut self, cacheable: CA) -> Result<CacheResponse, E>;
    async fn store(&mut self, identity: Vec<u8>) -> Result<(), E>;
}

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

#[async_trait]
impl<C, E> ReadableCache<E> for C
    where
        C: Cache<E> + Send + Sync + 'static,
        E: Send + Sync + 'static,
{

    async fn get<CA>(&mut self, cacheable: CA) -> Result<CacheResponse, E>
        where
            CA: Cacheable + Send + Sync + 'static
    {
        Cache::get(self, cacheable).await
    }
}

pub struct NopCache {}


#[async_trait]
impl Cache<()> for NopCache {
    async fn get<CA: Cacheable + Send + Sync + 'static>(&mut self, cacheable: CA) -> Result<CacheResponse, ()> {
        Ok(CacheResponse::Miss)
    }
    async fn store(&mut self, identity: Vec<u8>) -> Result<(), ()> {
        Ok(())
    }
}