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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#![deny(missing_docs)]
#![cfg_attr(feature = "nightly", feature(test))]
use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
pub type CreateFn<T> = Box<Fn() -> T + Send + Sync + 'static>;
pub struct Pool<T: Send + 'static>(Arc<_Pool<T>>);
struct _Pool<T: Send + 'static> {
stack: Stack<T>,
create: CreateFn<T>,
}
impl<T: Send + 'static> Clone for Pool<T> {
fn clone(&self) -> Pool<T> {
Pool(self.0.clone())
}
}
impl<T: fmt::Debug + Send + 'static> fmt::Debug for Pool<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Pool(...)")
}
}
#[derive(Debug)]
pub struct RefGuard<'a, T: Send + 'static> {
pool: &'a Pool<T>,
data: Option<T>,
}
#[derive(Debug)]
pub struct Guard<T: Send + 'static> {
pool: Pool<T>,
data: Option<T>,
}
impl<T: Send + 'static> Pool<T> {
pub fn new(create: CreateFn<T>) -> Pool<T> {
Pool(Arc::new(_Pool {
stack: Stack::new(),
create: create,
}))
}
pub fn get(&self) -> Guard<T> {
match self.0.stack.pop() {
None => Guard { pool: self.clone(), data: Some((self.0.create)()) },
Some(data) => Guard { pool: self.clone(), data: Some(data) },
}
}
pub fn get_ref(&self) -> RefGuard<T> {
match self.0.stack.pop() {
None => RefGuard { pool: self, data: Some((self.0.create)()) },
Some(data) => RefGuard { pool: self, data: Some(data) },
}
}
fn put(&self, data: T) {
self.0.stack.push(data);
}
}
impl<'a, T: Send + 'static> Drop for RefGuard<'a, T> {
fn drop(&mut self) {
let data = self.data.take().unwrap();
self.pool.put(data);
}
}
impl<'a, T: Send + 'static> ops::Deref for RefGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T { self.data.as_ref().unwrap() }
}
impl<'a, T: Send + 'static> ops::DerefMut for RefGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T { self.data.as_mut().unwrap() }
}
impl<T: Send + 'static> Drop for Guard<T> {
fn drop(&mut self) {
let data = self.data.take().unwrap();
self.pool.put(data);
}
}
impl<T: Send + 'static> ops::Deref for Guard<T> {
type Target = T;
fn deref(&self) -> &T { self.data.as_ref().unwrap() }
}
impl<T: Send + 'static> ops::DerefMut for Guard<T> {
fn deref_mut(&mut self) -> &mut T { self.data.as_mut().unwrap() }
}
struct Stack<T: Send + 'static> {
stack: UnsafeCell<Vec<T>>,
lock: SpinLock,
}
unsafe impl<T: Send + 'static> Sync for Stack<T> {}
impl<T: Send + 'static> Stack<T> {
fn new() -> Stack<T> {
Stack {
stack: UnsafeCell::new(vec![]),
lock: SpinLock::new(),
}
}
fn push(&self, data: T) {
self.lock.lock();
let mut stack = unsafe { &mut *self.stack.get() };
stack.push(data);
self.lock.unlock();
}
fn pop(&self) -> Option<T> {
self.lock.lock();
let mut stack = unsafe { &mut *self.stack.get() };
let data = stack.pop();
self.lock.unlock();
data
}
}
impl<T: fmt::Debug + Send + 'static> fmt::Debug for Stack<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Stack")
.field("stack", &"...")
.field("lock", &self.lock)
.finish()
}
}
#[derive(Debug)]
struct SpinLock {
locked: AtomicBool,
}
impl SpinLock {
fn new() -> SpinLock {
SpinLock { locked: AtomicBool::new(false) }
}
fn lock(&self) {
while self.locked.swap(true, Ordering::Acquire) {}
}
fn unlock(&self) {
self.locked.store(false, Ordering::Release)
}
}
#[cfg(test)]
#[cfg(feature = "nightly")]
mod bench;
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use super::{CreateFn, Pool};
#[derive(Debug, Eq, PartialEq)]
struct Dummy(usize);
fn dummy() -> CreateFn<Dummy> {
let count = AtomicUsize::new(0);
Box::new(move || {
Dummy(count.fetch_add(1, SeqCst))
})
}
#[test]
fn empty() {
let pool = Pool::new(dummy());
assert_eq!(&Dummy(0), &*pool.get());
}
#[test]
fn reuse() {
let pool = Pool::new(dummy());
{
assert_eq!(&Dummy(0), &*pool.get());
}
assert_eq!(&Dummy(0), &*pool.get());
}
#[test]
fn no_reuse() {
let pool = Pool::new(dummy());
let val = pool.get();
assert_eq!(&Dummy(0), &*val);
assert_eq!(&Dummy(1), &*pool.get());
}
#[test]
fn is_sync() {
fn foo<T: Sync>() {}
foo::<Pool<String>>()
}
}