use std::collections::HashMap;
use async_trait::async_trait;
use futures::lock::Mutex;
use xstack::driver_wrapper;
use crate::KBucketKey;
pub mod syscall {
use async_trait::async_trait;
use crate::KBucketKey;
#[async_trait]
pub trait DriverKadStore: Sync + Send {
async fn insert(&self, key: KBucketKey, record: Vec<u8>) -> std::io::Result<()>;
async fn remove(&self, key: &KBucketKey) -> std::io::Result<Option<Vec<u8>>>;
async fn get(&self, key: &KBucketKey) -> std::io::Result<Option<Vec<u8>>>;
}
}
driver_wrapper!(
["A type wrapper of [`DriverKadStore`](syscall::DriverKadStore)"]
KadStore[syscall::DriverKadStore]
);
pub struct KadMemoryStore(Mutex<HashMap<KBucketKey, Vec<u8>>>);
impl KadMemoryStore {
pub fn new() -> Self {
KadMemoryStore(Default::default())
}
}
#[async_trait]
impl syscall::DriverKadStore for KadMemoryStore {
async fn insert(&self, key: KBucketKey, record: Vec<u8>) -> std::io::Result<()> {
self.0.lock().await.insert(key, record);
Ok(())
}
async fn remove(&self, key: &KBucketKey) -> std::io::Result<Option<Vec<u8>>> {
Ok(self.0.lock().await.remove(key))
}
async fn get(&self, key: &KBucketKey) -> std::io::Result<Option<Vec<u8>>> {
Ok(self.0.lock().await.get(key).map(|record| record.to_owned()))
}
}