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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// 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::rc::Rc;
use std::cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut};
use pool_object::Recyclable;

/// A wrapper around a `Rc` pointer to a `Poolable` object with interior mutability.
///
/// The `Poolable` object is wrapped by a `RefCell`, to be able to mutate the object with an immutable reference.
///
/// This `RefCell` is wrapped by an `Rc`, a reference-counted pointer, so multiple parts of the program can "own" the object.
///
///
/// This wrapper allows a custom `Drop` implementation: when a `RcHandle` 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 `Rc` is dropped and the strong
/// reference count decrease to 1, meaning that the only structure holding a reference is the `RcPool` itself.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct RcHandle<T: Recyclable>(pub Rc<RefCell<T>>);

impl<T: Recyclable> AsRef<Rc<RefCell<T>>> for RcHandle<T> {
    fn as_ref(&self) -> &Rc<RefCell<T>> {
        &self.0
    }
}

impl<T: Recyclable> RcHandle<T> {
    /// Creates a new `RcHandle` from a `Recyclable` object.
    #[doc(hidden)]
    pub fn new(item: T) -> Self {
        debug!("Creating a RcHandle.");
        RcHandle(Rc::new(RefCell::new(item)))
    }

    /// Immutably borrows the wrapped value.
    ///
    /// Refer to the [RefCell::borrow](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.borrow)
    /// method for more information.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently mutably borrowed.
    ///
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::RcPool;
    /// # 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 = RcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// assert_eq!(monster.borrow().level, 10);
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn borrow(&self) -> Ref<T> {
        debug!("Borrowing an immutable reference to the inner object.");
        self.0.borrow()
    }

    /// Immutably borrows the wrapped value, returning an error if the value is currently mutably borrowed.
    ///
    /// Refer to the [RefCell::try_borrow](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow)
    /// method for more information.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::RcPool;
    /// # 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 = RcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// let mut_borrowed = monster.borrow_mut();
    /// // Monster is already mutably borrowed.
    /// assert!(monster.try_borrow().is_err());
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
        debug!("Trying to borrow an immutable reference to the inner object.");
        self.0.try_borrow()
    }

    /// Mutably borrows the wrapped value.
    ///
    /// Refer to the [RefCell::borrow_mut](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.borrow_mut)
    /// method for more information.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed.
    ///
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::RcPool;
    /// # 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 = RcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// monster.borrow_mut().level_up();
    /// assert_eq!(monster.borrow().level, 11);
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn borrow_mut(&self) -> RefMut<T> {
        debug!("Borrowing a mutable reference to the inner object.");
        self.0.borrow_mut()
    }

    /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
    ///
    /// Refer to the [RefCell::try_borrow_mut](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.try_borrow_mut)
    /// method for more information.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::RcPool;
    /// # 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 = RcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// let borrowed = monster.borrow();
    /// // Monster already borrowed.
    /// assert!(monster.try_borrow_mut().is_err());
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
        debug!("Trying to borrow a mutable reference to the inner object.");
        self.0.try_borrow_mut()
    }

    /// Returns a raw pointer to the underlying data.
    ///
    /// Refer to the [RefCell::as_ptr](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.as_ptr)
    /// method for more information.
    ///
    /// # Example
    ///
    /// ```rust
    /// use maskerad_object_pool::RcPool;
    /// # 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 = RcPool::with_capacity(10, || {
    ///     Monster::default()
    /// });
    ///
    /// let monster = pool.create_strict()?;
    /// let monster_ptr = monster.as_ptr();
    /// #
    /// #   Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #   try_main().unwrap();
    /// # }
    /// ```
    pub fn as_ptr(&self) -> *mut T {
        debug!("Returning a raw pointer to the inner object.");
        self.0.as_ptr()
    }
}

impl<T: Recyclable> Drop for RcHandle<T> {
    /// This `Drop` implementation allow us to reinitialize the `Poolable` object
    /// if the strong reference count of the inner `Rc` is equal to 2.
    ///
    /// If it is the case, `T` is reinitialized, the inner `Rc` is dropped and the strong
    /// reference count is decreased to 1, meaning that the only structure holding a reference is the `RcPool` itself.
    fn drop(&mut self) {
        trace!("The RcHandle is being dropped.");
        // 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 Rc::strong_count(&self.0) == 2 {
            trace!("The reference count of the RcHandle is equal to 2. Reinitializing the inner object.");
            self.0.borrow_mut().reinitialize();
        }
    }
}

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