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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2017 -2018 Maskerad Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use std::sync::{Arc, LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError,
                TryLockResult};
use pool_object::Recyclable;

/// A wrapper around a `Arc` pointer to a `RwLock<Poolable>` object.
///
/// The `Poolable` object is wrapped by a `RwLock`, allowing read/write access to the object from multiple threads.
///
/// This `RwLock` is wrapped by an `Arc`, an atomic reference-counted pointer, allowing the object to be shared between threads.
///
///
/// This wrapper allows a custom `Drop` implementation: when an `ArcHandle` is dropped, the contained `Poolable` object is reinitialized
/// if its strong reference count is equal to two. If it is the case, the object is reinitialized, the inner `Arc` is dropped and the strong
/// reference count decrease to 1, meaning that the only structure holding a reference is the `ArcPool` itself.
#[derive(Debug)]
pub struct ArcHandle<T: Recyclable>(pub Arc<RwLock<T>>);

impl<T: Recyclable> AsRef<Arc<RwLock<T>>> for ArcHandle<T> {
    fn as_ref(&self) -> &Arc<RwLock<T>> {
        &self.0
    }
}

impl<T: Recyclable> ArcHandle<T> {
    /// Creates a new `ArcHandle` from a `Recyclable` object.
    #[doc(hidden)]
    pub fn new(item: T) -> Self {
        ArcHandle(Arc::new(RwLock::new(item)))
    }

    /// Locks this rwlock with shared read access, blocking the current thread until it can be acquired.
    ///
    /// Refer to the [RwLock::read](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.read)
    /// method for more information.
    ///
    /// # Errors
    ///
    /// This function will return an error if the RwLock is poisoned.
    /// An RwLock is poisoned whenever a writer panics while holding an exclusive lock.
    /// The failure will occur immediately after the lock has been acquired.
    ///
    /// # Panics
    ///
    /// This function might panic when called if the lock is already held by the current thread.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::ArcPool;
    /// # use maskerad_object_pool::Recyclable;
    /// # use std::error::Error;
    /// #
    /// # struct Monster {
    /// # hp :u32,
    /// # pub level: u32,
    /// # }
    /// #
    /// # impl Default for Monster {
    /// #    fn default() -> Self {
    /// #        Monster {
    /// #            hp: 10,
    /// #            level: 10,
    /// #        }
    /// #    }
    /// # }
    /// #
    /// # impl Recyclable for Monster {
    /// #   fn reinitialize(&mut self) {
    /// #       self.level = 1;
    /// #   }
    /// # }
    /// #
    /// # impl Monster {
    /// #    pub fn level_up(&mut self) {
    /// #        self.level += 1;
    /// #    }
    /// # }
    /// #
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let pool = ArcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// assert_eq!(monster.read().unwrap().level, 10);
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn read(&self) -> LockResult<RwLockReadGuard<T>> {
        self.0.read()
    }

    /// Attempts to acquire this rwlock with shared read access.
    ///
    /// Refer to the [RwLock::try_read](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.try_read)
    /// method for more information.
    ///
    /// # Errors
    ///
    /// This function will return an error if the RwLock is poisoned.
    /// An RwLock is poisoned whenever a writer panics while holding an exclusive lock.
    /// An error will only be returned if the lock would have otherwise been acquired.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::ArcPool;
    /// # use maskerad_object_pool::Recyclable;
    /// # use std::error::Error;
    /// #
    /// # struct Monster {
    /// # hp :u32,
    /// # pub level: u32,
    /// # }
    /// #
    /// # impl Default for Monster {
    /// #    fn default() -> Self {
    /// #        Monster {
    /// #            hp: 10,
    /// #            level: 10,
    /// #        }
    /// #    }
    /// # }
    /// #
    /// # impl Recyclable for Monster {
    /// #   fn reinitialize(&mut self) {
    /// #       self.level = 1;
    /// #   }
    /// # }
    /// #
    /// # impl Monster {
    /// #    pub fn level_up(&mut self) {
    /// #        self.level += 1;
    /// #    }
    /// # }
    /// #
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let pool = ArcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// // The RwLock has not been poisoned yet, there is no writers.
    /// assert!(monster.try_read().is_ok());
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<T>> {
        self.0.try_read()
    }

    /// Locks this rwlock with exclusive write access, blocking the current thread until it can be acquired.
    ///
    /// Refer to the [RwLock::write](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.write)
    /// method for more information.
    ///
    /// # Errors
    ///
    /// This function will return an error if the RwLock is poisoned.
    /// An RwLock is poisoned whenever a writer panics while holding an exclusive lock.
    /// An error will be returned when the lock is acquired.
    ///
    /// # Panics
    ///
    /// This function might panic when called if the lock is already held by the current thread.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::ArcPool;
    /// # use maskerad_object_pool::Recyclable;
    /// # use std::error::Error;
    /// #
    /// # struct Monster {
    /// # hp :u32,
    /// # pub level: u32,
    /// # }
    /// #
    /// # impl Default for Monster {
    /// #    fn default() -> Self {
    /// #        Monster {
    /// #            hp: 10,
    /// #            level: 10,
    /// #        }
    /// #    }
    /// # }
    /// #
    /// # impl Recyclable for Monster {
    /// #   fn reinitialize(&mut self) {
    /// #       self.level = 1;
    /// #   }
    /// # }
    /// #
    /// # impl Monster {
    /// #    pub fn level_up(&mut self) {
    /// #        self.level += 1;
    /// #    }
    /// # }
    /// #
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let pool = ArcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// monster.write().unwrap().level_up();
    /// assert_eq!(monster.read().unwrap().level, 11);
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn write(&self) -> LockResult<RwLockWriteGuard<T>> {
        self.0.write()
    }

    /// Attempts to lock this rwlock with exclusive write access.
    ///
    /// Refer to the [RwLock::try_write](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.try_write)
    /// method for more information.
    ///
    /// # Errors
    ///
    /// This function will return an error if the RwLock is poisoned.
    /// An RwLock is poisoned whenever a writer panics while holding an exclusive lock.
    /// An error will only be returned if the lock would have otherwise been acquired.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::ArcPool;
    /// # use maskerad_object_pool::Recyclable;
    /// # use std::error::Error;
    /// #
    /// # struct Monster {
    /// # hp :u32,
    /// # pub level: u32,
    /// # }
    /// #
    /// # impl Default for Monster {
    /// #    fn default() -> Self {
    /// #        Monster {
    /// #            hp: 10,
    /// #            level: 10,
    /// #        }
    /// #    }
    /// # }
    /// #
    /// # impl Recyclable for Monster {
    /// #   fn reinitialize(&mut self) {
    /// #       self.level = 1;
    /// #   }
    /// # }
    /// #
    /// # impl Monster {
    /// #    pub fn level_up(&mut self) {
    /// #        self.level += 1;
    /// #    }
    /// # }
    /// #
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let pool = ArcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// let reader = monster.read().unwrap();
    ///
    /// // With an RwLock, there can be at any given time, either:
    /// // - multiple readers
    /// // - a single writer
    /// // There is already a reader, try_write will return an error.
    /// assert!(monster.try_write().is_err());
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
        self.0.try_write()
    }

    /// Determines whether the lock is poisoned.
    ///
    /// Refer to the [RwLock::is_poisoned](https://doc.rust-lang.org/std/sync/struct.RwLock.html#method.is_poisoned)
    /// method for more information.
    pub fn is_poisoned(&self) -> bool {
        self.0.is_poisoned()
    }

    fn drop_handle(&mut self) -> Result<(), TryLockError<RwLockWriteGuard<T>>> {
        // Outer(Inner) -> Outer is dropped, then Inner is dropped.
        // That's why we check if the refcount is equal to 2 :
        // PoolObjectHandler is dropped (refcount == 2), then Rc<RefCell<T>> is dropped (refcount == 1 -> only the pool has a ref to the data).
        if Arc::strong_count(self.as_ref()) == 2 {
            //We use try_write. Using write is a blocking operations, and this function is called from the destructor.
            match self.0.try_write() {
                Ok(mut guard) => {
                    (*guard).reinitialize();
                }
                Err(error) => {
                    return Err(error);
                }
            }
        }
        Ok(())
    }
}

impl<T: Recyclable> Drop for ArcHandle<T> {
    /// This `Drop` implementation allow us to reinitialize the `Poolable` object
    /// if the strong reference count of the inner `Arc` is equal to 2.
    ///
    /// If it is the case, `T` is reinitialized, the inner `Arc` is dropped and the strong
    /// reference count is decreased to 1, meaning that the only structure holding a reference is the `ArcPool` itself.
    fn drop(&mut self) {
        self.drop_handle().unwrap();
    }
}

impl<T: Recyclable> Clone for ArcHandle<T> {
    fn clone(&self) -> Self {
        ArcHandle(self.0.clone())
    }
}