mysql_connector/pool/
sync_pool.rs

1use {
2    super::{PoolItem, PoolPut},
3    crossbeam::queue::ArrayQueue,
4    std::{fmt, mem::ManuallyDrop},
5};
6
7pub struct SyncPool<T: SyncPoolContent, const N: usize> {
8    ctx: T::Ctx,
9    pool: ArrayQueue<T>,
10}
11
12impl<T: SyncPoolContent, const N: usize> PoolPut<T> for SyncPool<T, N> {
13    fn put(&self, mut value: T) {
14        // if there are too many items, they will be dropped
15        value.reset(&self.ctx);
16        let _ = self.pool.push(value);
17    }
18}
19
20impl<T: SyncPoolContent, const N: usize> SyncPool<T, N> {
21    pub fn new(ctx: T::Ctx) -> Self {
22        Self {
23            ctx,
24            pool: ArrayQueue::new(N),
25        }
26    }
27
28    pub fn get(&self) -> PoolItem<'_, T> {
29        let item = self.pool.pop().unwrap_or_else(|| T::new(&self.ctx));
30        PoolItem {
31            item: ManuallyDrop::new(item),
32            pool: self,
33        }
34    }
35}
36
37pub trait SyncPoolContent: Sized {
38    type Ctx: fmt::Debug;
39    fn new(ctx: &Self::Ctx) -> Self;
40    fn reset(&mut self, ctx: &Self::Ctx);
41}
42
43#[derive(Debug)]
44pub struct VecPoolCtx {
45    pub size_cap: usize,
46    pub init_size: usize,
47}
48
49impl<T> SyncPoolContent for Vec<T> {
50    type Ctx = VecPoolCtx;
51
52    fn new(ctx: &Self::Ctx) -> Self {
53        Self::with_capacity(ctx.init_size)
54    }
55
56    fn reset(&mut self, ctx: &Self::Ctx) {
57        unsafe {
58            self.set_len(0);
59        }
60        self.shrink_to(ctx.size_cap);
61    }
62}