objectpool 0.1.0

Yet another lock-free object pool, support no_std
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#![doc = include_str!("../README.md")]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#![deny(missing_docs)]

#[cfg(not(feature = "std"))]
extern crate alloc as std;

#[cfg(feature = "std")]
extern crate std;

#[cfg(not(any(feature = "std", feature = "alloc")))]
compile_error!("`objectpool` requires either the 'std' or 'alloc' feature to be enabled.");

use core::{mem::ManuallyDrop, ptr::NonNull};

use crossbeam_queue::{ArrayQueue, SegQueue};

#[cfg(not(feature = "loom"))]
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};

#[cfg(feature = "loom")]
use loom::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};

#[cfg(not(feature = "std"))]
use std::boxed::Box;

mod abort;

/// A reusable `T`.
pub struct ReusableObject<T> {
  pool: Pool<T>,
  obj: ManuallyDrop<T>,
}

impl<T> AsRef<T> for ReusableObject<T> {
  fn as_ref(&self) -> &T {
    &self.obj
  }
}

impl<T> AsMut<T> for ReusableObject<T> {
  fn as_mut(&mut self) -> &mut T {
    &mut self.obj
  }
}

impl<T> core::ops::Deref for ReusableObject<T> {
  type Target = T;

  fn deref(&self) -> &Self::Target {
    &self.obj
  }
}

impl<T> core::ops::DerefMut for ReusableObject<T> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.obj
  }
}

impl<T> Drop for ReusableObject<T> {
  fn drop(&mut self) {
    // SAFETY: The object is dropped, we never reuse the ManuallyDrop again.
    unsafe {
      self.pool.attach(ManuallyDrop::take(&mut self.obj));
    }
  }
}

/// A reusable `T`.
pub struct ReusableObjectRef<'a, T> {
  pool: &'a Pool<T>,
  obj: ManuallyDrop<T>,
}

impl<'a, T> AsRef<T> for ReusableObjectRef<'a, T> {
  fn as_ref(&self) -> &T {
    &self.obj
  }
}

impl<'a, T> AsMut<T> for ReusableObjectRef<'a, T> {
  fn as_mut(&mut self) -> &mut T {
    &mut self.obj
  }
}

impl<'a, T> core::ops::Deref for ReusableObjectRef<'a, T> {
  type Target = T;

  fn deref(&self) -> &Self::Target {
    &self.obj
  }
}

impl<'a, T> core::ops::DerefMut for ReusableObjectRef<'a, T> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.obj
  }
}

impl<'a, T> Drop for ReusableObjectRef<'a, T> {
  fn drop(&mut self) {
    // SAFETY: The object is dropped, we never reuse the ManuallyDrop again.
    unsafe {
      self.pool.attach(ManuallyDrop::take(&mut self.obj));
    }
  }
}

// It is ok to have a large enum variant here because the enum will always be `Box::into_raw(Box::new(_))`
#[allow(clippy::large_enum_variant)]
enum Backed<T> {
  Bounded(ArrayQueue<T>),
  Unbounded(SegQueue<T>),
}

struct Queue<T> {
  refs: AtomicUsize,
  queue: Backed<T>,
}

impl<T> Queue<T> {
  #[inline]
  fn bounded(queue: ArrayQueue<T>) -> Self {
    Self {
      refs: AtomicUsize::new(1),
      queue: Backed::Bounded(queue),
    }
  }

  #[inline]
  fn unbounded(queue: SegQueue<T>) -> Self {
    Self {
      refs: AtomicUsize::new(1),
      queue: Backed::Unbounded(queue),
    }
  }

  #[inline]
  fn push(&self, obj: T) {
    match &self.queue {
      Backed::Bounded(queue) => {
        let _ = queue.push(obj);
      }
      Backed::Unbounded(queue) => queue.push(obj),
    }
  }

  #[inline]
  fn pop(&self) -> Option<T> {
    match &self.queue {
      Backed::Bounded(queue) => queue.pop(),
      Backed::Unbounded(queue) => queue.pop(),
    }
  }
}

/// Lock-free object pool.
pub struct Pool<T> {
  refs: AtomicPtr<()>,
  queue: *mut Queue<T>,
  new: NonNull<dyn Fn() -> T + Send + Sync + 'static>,
  reset: NonNull<dyn Fn(&mut T) + Send + Sync + 'static>,
}

unsafe impl<T: Send> Send for Pool<T> {}
unsafe impl<T: Sync> Sync for Pool<T> {}

impl<T> Pool<T> {
  /// Create a new pool with the given capacity.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |_v| {});
  /// ```
  #[inline]
  pub fn bounded(
    capacity: usize,
    new: impl Fn() -> T + Send + Sync + 'static,
    reset: impl Fn(&mut T) + Send + Sync + 'static,
  ) -> Self {
    let queue = Queue::bounded(ArrayQueue::<T>::new(capacity));
    Self::new(queue, new, reset)
  }

  /// Create a new pool with the unbounded capacity.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::unbounded(Default::default, |_v| {});
  /// ```
  #[inline]
  pub fn unbounded(
    new: impl Fn() -> T + Send + Sync + 'static,
    reset: impl Fn(&mut T) + Send + Sync + 'static,
  ) -> Self {
    let queue = Queue::unbounded(SegQueue::<T>::new());
    Self::new(queue, new, reset)
  }

  /// Get an object from the pool.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |_v| {});
  ///
  /// let mut obj = pool.get();
  ///
  /// assert_eq!(*obj, 0);
  ///
  /// *obj = 42;
  /// drop(obj);
  /// ```
  #[inline]
  pub fn get(&self) -> ReusableObjectRef<T> {
    ReusableObjectRef {
      pool: self,
      obj: ManuallyDrop::new(self.queue().pop().unwrap_or_else(|| self.new_object())),
    }
  }

  /// Get an object from the pool.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |_v| {});
  ///
  /// let mut obj = pool.get_owned();
  ///
  /// assert_eq!(*obj, 0);
  ///
  /// *obj = 42;
  /// drop(obj);
  /// ```
  #[inline]
  pub fn get_owned(&self) -> ReusableObject<T> {
    ReusableObject {
      pool: self.clone(),
      obj: ManuallyDrop::new(self.queue().pop().unwrap_or_else(|| self.new_object())),
    }
  }

  /// Get an object from the pool with a fallback.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |_| {});
  ///
  /// let mut obj = pool.get_or_else(|| 42);
  ///
  /// assert_eq!(*obj, 42);
  /// ```
  #[inline]
  pub fn get_or_else(&self, fallback: impl Fn() -> T) -> ReusableObjectRef<T> {
    ReusableObjectRef {
      pool: self,
      obj: ManuallyDrop::new(self.queue().pop().unwrap_or_else(fallback)),
    }
  }

  /// Get an object from the pool with a fallback.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |_| {});
  ///
  /// let mut obj = pool.get_owned_or_else(|| 42);
  ///
  /// assert_eq!(*obj, 42);
  /// ```
  #[inline]
  pub fn get_owned_or_else(&self, fallback: impl Fn() -> T) -> ReusableObject<T> {
    ReusableObject {
      pool: self.clone(),
      obj: ManuallyDrop::new(self.queue().pop().unwrap_or_else(fallback)),
    }
  }

  /// Clear the pool.
  ///
  /// # Example
  ///
  /// ```rust
  /// use objectpool::Pool;
  ///
  /// let pool = Pool::<u32>::bounded(10, Default::default, |v| {});
  ///
  /// let mut obj = pool.get();
  /// *obj = 42;
  /// drop(obj);
  ///
  /// pool.clear();
  /// ```
  #[inline]
  pub fn clear(&self) {
    while self.queue().pop().is_some() {}
  }

  #[inline]
  fn new(
    queue: Queue<T>,
    new: impl Fn() -> T + Send + Sync + 'static,
    reset: impl Fn(&mut T) + Send + Sync + 'static,
  ) -> Self {
    let ptr = Box::into_raw(Box::new(queue));

    unsafe {
      Self {
        queue: ptr,
        refs: AtomicPtr::new(ptr as *mut ()),
        // SAFETY: Box::new is safe because the closure is 'static.
        new: NonNull::new_unchecked(Box::into_raw(Box::new(new))),
        // SAFETY: Box::new is safe because the closure is 'static.
        reset: NonNull::new_unchecked(Box::into_raw(Box::new(reset))),
      }
    }
  }

  /// Return an object to the pool.
  #[inline]
  fn attach(&self, mut obj: T) {
    self.reset_object(&mut obj);
    self.queue().push(obj);
  }

  #[inline]
  fn new_object(&self) -> T {
    // SAFETY: The new closure is 'static and the pointer is valid until the last Pool instance is droped.
    let constructor = unsafe { &*(self.new.as_ptr()) };
    constructor()
  }

  #[inline]
  fn reset_object(&self, obj: &mut T) {
    // SAFETY: The reset closure is 'static and the pointer is valid until the last Pool instance is droped.
    let resetter = unsafe { &*(self.reset.as_ptr()) };
    resetter(obj);
  }

  #[inline]
  fn queue(&self) -> &Queue<T> {
    // SAFETY: The pointer is valid until the last Pool instance is droped.
    unsafe { &*self.queue }
  }
}

impl<T> Clone for Pool<T> {
  fn clone(&self) -> Self {
    unsafe {
      let shared: *mut Queue<T> = self.refs.load(Ordering::Relaxed).cast();

      let old_size = (*shared).refs.fetch_add(1, Ordering::Release);
      if old_size > usize::MAX >> 1 {
        abort::abort();
      }

      // SAFETY: The ptr is always non-null, and the data is only deallocated when the
      // last Pool is dropped.
      Self {
        refs: AtomicPtr::new(shared as *mut ()),
        queue: self.queue,
        new: self.new,
        reset: self.reset,
      }
    }
  }
}

impl<T> Drop for Pool<T> {
  fn drop(&mut self) {
    unsafe {
      self.refs.with_mut(|shared| {
        let shared: *mut Queue<T> = shared.cast();
        // `Shared` storage... follow the drop steps from Arc.
        if (*shared).refs.fetch_sub(1, Ordering::Release) != 1 {
          return;
        }

        // This fence is needed to prevent reordering of use of the data and
        // deletion of the data.  Because it is marked `Release`, the decreasing
        // of the reference count synchronizes with this `Acquire` fence. This
        // means that use of the data happens before decreasing the reference
        // count, which happens before this fence, which happens before the
        // deletion of the data.
        //
        // As explained in the [Boost documentation][1],
        //
        // > It is important to enforce any possible access to the object in one
        // > thread (through an existing reference) to *happen before* deleting
        // > the object in a different thread. This is achieved by a "release"
        // > operation after dropping a reference (any access to the object
        // > through this reference must obviously happened before), and an
        // > "acquire" operation before deleting the object.
        //
        // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
        //
        // Thread sanitizer does not support atomic fences. Use an atomic load
        // instead.
        (*shared).refs.load(Ordering::Acquire);

        // Drop the data
        let _ = Box::from_raw(shared);
        let _ = Box::from_raw(self.new.as_ptr());
        let _ = Box::from_raw(self.reset.as_ptr());
      });
    }
  }
}

#[cfg(not(feature = "loom"))]
trait AtomicMut<T> {
  fn with_mut<F, R>(&mut self, f: F) -> R
  where
    F: FnOnce(&mut *mut T) -> R;
}

#[cfg(not(feature = "loom"))]
impl<T> AtomicMut<T> for AtomicPtr<T> {
  fn with_mut<F, R>(&mut self, f: F) -> R
  where
    F: FnOnce(&mut *mut T) -> R,
  {
    f(self.get_mut())
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[cfg(not(feature = "std"))]
  use std::{vec, vec::Vec};

  #[cfg(all(feature = "std", not(feature = "loom")))]
  use std::thread;

  #[cfg(all(feature = "std", feature = "loom", not(miri)))]
  use loom::thread;

  fn create_pool(cap: usize) -> Pool<Vec<u8>> {
    Pool::bounded(cap, Vec::new, |val| {
      val.clear();
    })
  }

  fn basic_get_and_put_in() {
    let pool = create_pool(10);

    // Get a new object from the pool
    let mut obj = pool.get();
    assert_eq!(*obj, Vec::new());

    // Modify and return the object
    obj.push(42);
    drop(obj);

    // Get the object back from the pool
    let obj = pool.get();
    assert_eq!(*obj, Vec::new());
  }

  #[test]
  fn basic_get_and_put() {
    #[cfg(feature = "loom")]
    loom::model(basic_get_and_put_in);

    #[cfg(not(feature = "loom"))]
    basic_get_and_put_in();
  }

  fn get_or_else_in() {
    let pool = create_pool(10);

    // Get an object from the pool with a fallback
    let mut obj = pool.get_or_else(|| vec![42]);
    assert_eq!(*obj, [42]);

    // Modify and return the object
    obj.push(43);
    drop(obj);

    // Get the object back from the pool with a fallback
    let obj = pool.get_or_else(|| vec![42]);
    assert_eq!(*obj, []);

    let _objs = (0..10)
      .map(|_| pool.get_or_else(|| vec![42]))
      .collect::<Vec<_>>();

    let obj = pool.get_or_else(|| vec![42]);
    assert_eq!(*obj, [42]);
  }

  #[test]
  fn get_or_else() {
    #[cfg(feature = "loom")]
    loom::model(get_or_else_in);

    #[cfg(not(feature = "loom"))]
    get_or_else_in();
  }

  fn pool_clone_in() {
    let pool = create_pool(10);
    let pool_clone = pool.clone();

    // Get an object from the cloned pool
    let mut obj = pool_clone.get();
    assert_eq!(*obj, []);

    // Modify and return the object
    obj.push(42);
    drop(obj);

    // Get the object back from the original pool
    let obj = pool.get();
    assert_eq!(*obj, []);
  }

  #[test]
  fn pool_clone() {
    #[cfg(feature = "loom")]
    loom::model(pool_clone_in);

    #[cfg(not(feature = "loom"))]
    pool_clone_in();
  }

  #[cfg(feature = "std")]
  fn multi_threaded_access_in() {
    #[cfg(not(any(feature = "loom", miri)))]
    const OUTER: usize = 10;
    #[cfg(any(feature = "loom", miri))]
    const OUTER: usize = 2;

    #[cfg(not(any(feature = "loom", miri)))]
    const INNER: usize = 100;
    #[cfg(any(feature = "loom", miri))]
    const INNER: usize = 10;

    let pool = create_pool(10);

    let mut handles = vec![];

    for _ in 0..OUTER {
      let pool = pool.clone();
      let handle = thread::spawn(move || {
        for i in 0..INNER {
          let mut obj = pool.get();
          obj.push(i as u8);
          drop(obj);
        }
      });
      handles.push(handle);
    }

    for handle in handles {
      handle.join().expect("Thread panicked");
    }

    // Check that the pool is still functional after multi-threaded access
    let obj = pool.get();
    assert_eq!(*obj, []);
  }

  #[test]
  #[cfg(feature = "std")]
  fn multi_threaded_access() {
    #[cfg(all(feature = "std", not(feature = "loom")))]
    multi_threaded_access_in();

    #[cfg(all(feature = "std", feature = "loom"))]
    loom::model(multi_threaded_access_in);
  }

  fn custom_new_and_reset_in() {
    let pool = Pool::bounded(
      10,
      || 100, // new closure that creates an i32 with value 100
      |val: &mut i32| {
        *val = 200;
      }, // reset closure that resets the value to 200
    );

    // Get a new object from the pool
    let mut obj = pool.get();
    assert_eq!(*obj, 100);

    // Modify and return the object
    *obj = 42;
    drop(obj);

    // Get the object back from the pool
    let obj = pool.get();
    assert_eq!(*obj, 200);
  }

  #[test]
  fn custom_new_and_reset() {
    #[cfg(feature = "loom")]
    loom::model(custom_new_and_reset_in);

    #[cfg(not(feature = "loom"))]
    custom_new_and_reset_in();
  }

  #[cfg(not(feature = "loom"))]
  fn stress_test_in() {
    let pool = create_pool(10);

    for _ in 0..1_000_000 {
      let mut obj = pool.get();
      obj.push(42);
    }

    // Check that the pool is still functional after stress test
    let obj = pool.get();
    assert_eq!(*obj, []);
  }

  #[test]
  #[cfg(not(feature = "loom"))]
  fn stress_test() {
    stress_test_in();
  }

  fn test_reusable_object_in() {
    let pool = create_pool(10);

    {
      let mut obj = pool.get();
      obj.push(42);
      assert_eq!(*obj, [42]);
      // obj goes out of scope and is returned to the pool
    }

    // Get the object back from the pool
    let obj = pool.get();
    assert_eq!(*obj, []);
  }

  #[test]
  fn test_reusable_object() {
    #[cfg(feature = "loom")]
    loom::model(test_reusable_object_in);

    #[cfg(not(feature = "loom"))]
    test_reusable_object_in();
  }

  fn test_reset_on_put_in() {
    let pool = create_pool(10);

    let mut obj = pool.get();
    obj.push(123);
    drop(obj); // Object is returned to the pool and reset

    // Get the object back from the pool
    let obj = pool.get();
    assert_eq!(*obj, []); // Ensure that the object was reset
  }

  #[test]
  fn test_reset_on_put() {
    #[cfg(feature = "loom")]
    loom::model(test_reset_on_put_in);

    #[cfg(not(feature = "loom"))]
    test_reset_on_put_in();
  }

  fn test_as_ref_in() {
    let pool = create_pool(10);

    let mut obj = pool.get();
    obj.push(42);

    {
      let obj_ref = obj.as_ref();
      assert_eq!(*obj_ref, [42]);
    }

    {
      let obj_mut = obj.as_mut();
      obj_mut.push(43);
    }

    let mut obj = pool.get_owned();
    obj.push(42);
    {
      let obj_ref = obj.as_ref();
      assert_eq!(*obj_ref, [42]);
    }

    {
      let obj_mut = obj.as_mut();
      obj_mut.push(43);
    }
  }

  #[test]
  fn test_as_ref() {
    #[cfg(feature = "loom")]
    loom::model(test_as_ref_in);

    #[cfg(not(feature = "loom"))]
    test_as_ref_in();
  }
}