atex 0.3.0

Lib for async local task evaluation(sqlite or in-memory)
Documentation
use std::marker::PhantomData;
use std::mem;

use crate::entities::error::AtexError;
use crate::proto::{IPool, IPoolFactory};

pub struct Pool<K, V> {
    data: Vec<Option<(K, V)>>,
}

pub struct PoolFactory<K, V> {
    len: usize,
    phantom: PhantomData<(K, V)>,
}

impl<K, V> Pool<K, V> {
    fn new(len: usize) -> Self {
        let data = (0..len).map(|_| None).collect();
        Self { data }
    }
}

impl<K, V> PoolFactory<K, V> {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            phantom: PhantomData::default(),
        }
    }
}

impl<K: Send + Sync + Clone, V: Send + Sync> IPool<K, V> for Pool<K, V> {
    fn len(&self) -> usize {
        self.data.len()
    }

    fn free_cells(&self) -> Vec<usize> {
        let mut free = Vec::with_capacity(self.data.len());
        for i in 0..self.data.len() {
            if self.data[i].is_none() {
                free.push(i)
            }
        }
        free
    }

    fn get_keys(&self) -> Vec<K> {
        let mut keys = Vec::new();
        for (key, _) in self.data.iter().flatten() {
            keys.push(key.clone())
        }
        keys
    }

    fn get_cell(&mut self, id: usize) -> Result<(K, V), AtexError> {
        match mem::replace(&mut self.data[id], None) {
            None => Err(AtexError::GetFromEmptyCell),
            Some(val) => Ok(val),
        }
    }

    fn put_cell(&mut self, id: usize, key: K, val: V) -> Result<(), AtexError> {
        match mem::replace(&mut self.data[id], Some((key, val))) {
            Some(_) => Err(AtexError::PutInNonEmptyCell),
            _ => Ok(()),
        }
    }
}

impl<K: Send + Sync + Clone, V: Send + Sync> IPoolFactory<K, V> for PoolFactory<K, V> {
    type Pool = Pool<K, V>;

    fn len(&self) -> usize {
        self.len
    }

    fn produce(&self) -> Self::Pool {
        Pool::new(self.len)
    }
}