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
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: Clone { async fn get<CA: Cacheable + Send + Sync + 'static>( &mut self, cacheable: CA, ) -> Result<CacheResponse, crate::error::Error>; async fn store(&mut self, identity: Vec<u8>) -> Result<(), crate::error::Error>; } #[async_trait] pub trait ReadableCache { async fn get<CA: Cacheable + Send + Sync + 'static>( &mut self, cacheable: CA, ) -> Result<CacheResponse, crate::error::Error>; } #[async_trait] impl<C> ReadableCache for C where C: Cache + Send + Sync + 'static, { async fn get<CA>(&mut self, cacheable: CA) -> Result<CacheResponse, crate::error::Error> where CA: Cacheable + Send + Sync + 'static, { Cache::get(self, cacheable).await } } #[derive(Clone)] pub struct NopCache {} #[async_trait] impl Cache for NopCache { async fn get<CA: Cacheable + Send + Sync + 'static>( &mut self, _cacheable: CA, ) -> Result<CacheResponse, crate::error::Error> { Ok(CacheResponse::Miss) } async fn store(&mut self, _identity: Vec<u8>) -> Result<(), crate::error::Error> { Ok(()) } }