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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/// This is shamelessly based on the dynamic-pool crate, with
/// modifications
use crossbeam::queue::ArrayQueue;
use std::{
    collections::HashMap,
    default::Default,
    fmt::Debug,
    hash::{BuildHasher, Hash},
    ops::{Deref, DerefMut},
    sync::{Arc, Weak},
    cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering},
    mem,
};

pub trait Poolable {
    fn alloc() -> Self;
    fn reset(&mut self);
}

impl<K, V, R> Poolable for HashMap<K, V, R>
where
    K: Hash + Eq,
    V: Hash + Eq,
    R: Default + BuildHasher,
{
    fn alloc() -> Self {
        HashMap::default()
    }

    fn reset(&mut self) {
        self.clear()
    }
}

impl<T> Poolable for Vec<T> {
    fn alloc() -> Self {
        Vec::new()
    }

    fn reset(&mut self) {
        self.clear()
    }
}

/// a lock-free, thread-safe, dynamically-sized object pool.
///
/// this pool begins with an initial capacity and will continue
/// creating new objects on request when none are available.  pooled
/// objects are returned to the pool on destruction (with an extra
/// provision to optionally "reset" the state of an object for
/// re-use).
///
/// if, during an attempted return, a pool already has
/// `maximum_capacity` objects in the pool, the pool will throw away
/// that object.
#[derive(Clone, Debug)]
pub struct Pool<T: Poolable>(Arc<ArrayQueue<T>>);

impl<T: Poolable + Sync + Send + 'static> Pool<T> {
    /// creates a new `Pool<T>`. this pool will retain up to
    /// `maximum_capacity` objects.
    pub fn new(maximum_capacity: usize) -> Pool<T> {
        Pool(Arc::new(ArrayQueue::new(maximum_capacity)))
    }

    /// takes an item from the pool, creating one if none are available.
    pub fn take(&self) -> Pooled<T> {
        let object = self.0.pop().unwrap_or_else(|_| <T as Poolable>::alloc());
        Pooled { pool: Arc::downgrade(&self.0), object: Some(object) }
    }
}

/// an object, checked out from a pool.
#[derive(Debug, Clone)]
pub struct Pooled<T: Poolable> {
    pool: Weak<ArrayQueue<T>>,
    object: Option<T>,
}

impl<T: Poolable + PartialEq> PartialEq for Pooled<T> {
    fn eq(&self, other: &Pooled<T>) -> bool {
        self.object.eq(&other.object)
    }
}

impl<T: Poolable + Eq> Eq for Pooled<T> {}

impl<T: Poolable + PartialOrd> PartialOrd for Pooled<T> {
    fn partial_cmp(&self, other: &Pooled<T>) -> Option<Ordering> {
        self.object.partial_cmp(&other.object)
    }
}

impl<T: Poolable + Ord> Ord for Pooled<T> {
    fn cmp(&self, other: &Pooled<T>) -> Ordering {
        self.object.cmp(&other.object)
    }
}

impl<T: Poolable> Pooled<T> {
    /// Creates a `Pooled` that isn't connected to any pool. E.G. for
    /// branches where you know a given `Pooled` will always be empty.
    pub fn orphan(t: T) -> Self {
        Pooled {
            pool: Weak::new(),
            object: Some(t)
        }
    }

    pub fn detach(mut self) -> T {
        mem::replace(&mut self.object, None).unwrap()
    }
}

impl<T: Poolable> AsRef<T> for Pooled<T> {
    fn as_ref(&self) -> &T {
        self.object.as_ref().expect("invariant: object is always `some`.")
    }
}

impl<T: Poolable> Deref for Pooled<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.object.as_ref().expect("invariant: object is always `some`.")
    }
}

impl<T: Poolable> DerefMut for Pooled<T> {
    fn deref_mut(&mut self) -> &mut T {
        self.object.as_mut().expect("invariant: object is always `some`.")
    }
}

impl<T: Poolable> Drop for Pooled<T> {
    fn drop(&mut self) {
        if let Some(mut object) = self.object.take() {
            object.reset();
            if let Some(q) = self.pool.upgrade() {
                q.push(object).ok();
            }
        }
    }
}