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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Garbage collection.
//!
//! # Bags and garbage queues
//!
//! Objects that get removed from concurrent data structures must be stashed away until the global
//! epoch sufficiently advances so that they become safe for destruction. Pointers to such garbage
//! objects are kept in bags.
//!
//! When a bag becomes full, it is marked with the current global epoch pushed into a `Garbage`
//! queue. Usually each instance of concurrent data structure has it's own `Garbage` queue that
//! gets fully destroyed as soon as the data structure gets dropped.
//!
//! Whenever a bag is pushed into the queue, some garbage is collected and destroyed along the way.
//! Garbage collection can also be manually triggered by calling method `collect`.
//!
//! # The global garbage queue
//!
//! Some data structures don't own objects but merely transfer them between threads, e.g. queues.
//! As such, queues don't execute destructors - they only allocate and free some memory. it would
//! be costly for each queue to handle it's own `Garbage`, so there is a special global queue all
//! data structures can share.
//!
//! The global garbage queue is very efficient. Each thread has a thread-local bag that is
//! populated with garbage, and when it becomes full, it is finally pushed into queue. This design
//! reduces contention on data structures. The global queue cannot be explicitly accessed - the
//! only way to interact with it is by calling function `defer_free`.

use std::cell::UnsafeCell;
use std::cmp;
use std::fmt;
use std::mem;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, SeqCst};

use epoch::{self, Atomic, Owned, Scope, Ptr};

/// Maximum number of objects a bag can contain.
#[cfg(not(feature = "strict_gc"))]
const MAX_OBJECTS: usize = 64;
#[cfg(feature = "strict_gc")]
const MAX_OBJECTS: usize = 4;

/// The global epoch.
///
/// The last bit in this number is unused and is always zero. Every so often the global epoch is
/// incremented, i.e. we say it "advances". A pinned thread may advance the global epoch only if
/// all currently pinned threads have been pinned in the current epoch.
///
/// If an object became garbage in some epoch, then we can be sure that after two advancements no
/// thread will hold a reference to it. That is the crux of safe memory reclamation.
pub static EPOCH: AtomicUsize = ATOMIC_USIZE_INIT;

/// Holds removed objects that will be eventually destroyed.
pub struct Bag {
    /// Number of objects in the bag.
    len: AtomicUsize,
    /// Removed objects.
    objects: [UnsafeCell<(unsafe fn(*mut u8, usize), *mut u8, usize)>; MAX_OBJECTS],
    /// The global epoch at the moment when this bag got pushed into the queue.
    epoch: usize,
    /// The next bag in the queue.
    next: Atomic<Bag>,
}

impl Bag {
    /// Returns a new, empty bag.
    pub fn new() -> Self {
        Bag {
            len: AtomicUsize::new(0),
            objects: unsafe { mem::zeroed() },
            epoch: unsafe { mem::uninitialized() },
            next: Atomic::null(),
        }
    }

    /// Returns `true` if the bag is empty.
    pub fn is_empty(&self) -> bool {
        self.len.load(Relaxed) == 0
    }

    /// Attempts to insert a garbage object into the bag and returns `true` if succeeded.
    pub fn try_insert<T>(&self, destroy: unsafe fn(*mut T, usize), object: *const T, count: usize)
                         -> bool {
        // Erase type `*mut T` and use `*mut u8` instead.
        let destroy: unsafe fn(*mut u8, usize) = unsafe { mem::transmute(destroy) };
        let object = object as *const u8 as *mut u8;

        let mut len = self.len.load(Acquire);
        loop {
            // Is the bag full?
            if len == self.objects.len() {
                return false;
            }

            // Try incrementing `len`.
            match self.len.compare_exchange(len, len + 1, AcqRel, Acquire) {
                Ok(_) => {
                    // Success! Now store the garbage object into the array. The current thread
                    // will synchronize with the thread that destroys it through epoch advancement.
                    unsafe { *self.objects[len].get() = (destroy, object, count) }
                    return true;
                }
                Err(l) => len = l,
            }
        }
    }

    /// Destroys all objects in the bag.
    ///
    /// Note: can be called only once!
    unsafe fn destroy_all_objects(&self) {
        for cell in self.objects.iter().take(self.len.load(Relaxed)) {
            let (destroy, object, count) = *cell.get();
            destroy(object, count);
        }
    }
}

/// A garbage queue.
///
/// This is where a concurrent data structure can store removed objects for deferred destruction.
///
/// Stored garbage objects are first kept in the garbage buffer. When the buffer becomes full, it's
/// objects are flushed into the garbage queue. Flushing can be manually triggered by calling
/// [`flush`].
///
/// Some garbage in the queue can be manually collected by calling [`collect`].
///
/// [`flush`]: method.flush.html
/// [`collect`]: method.collect.html
#[deprecated(since = "0.2.0", note = "Use scope::defer_free and scope::defer_drop instead")]
pub struct Garbage {
    /// Head of the queue.
    head: Atomic<Bag>,
    /// Tail of the queue.
    tail: Atomic<Bag>,
    /// The next bag that will be pushed into the queue as soon as it gets full.
    pending: Atomic<Bag>,
}

unsafe impl Send for Garbage {}
unsafe impl Sync for Garbage {}

impl Garbage {
    /// Returns a new, empty garbage queue.
    pub fn new() -> Self {
        let garbage = Garbage {
            head: Atomic::null(),
            tail: Atomic::null(),
            pending: Atomic::null(),
        };

        // This code may be executing while a thread harness is initializing, so normal pinning
        // would try to access it while it is being initialized. Such accesses fail with a panic.
        // We must therefore cheat by creating a fake pin.
        let pin = unsafe { &mem::zeroed::<Scope>() };

        // The head of the queue is always a sentinel entry.
        let sentinel = Owned::new(Bag::new()).into_ptr(pin);
        garbage.head.store(sentinel, Relaxed);
        garbage.tail.store(sentinel, Relaxed);

        garbage
    }

    /// Attempts to compare-and-swap the pending bag `old` with a new, empty one.
    ///
    /// The return value is a result indicating whether the compare-and-swap successfully installed
    /// a new bag. On success the new bag is returned. On failure the current more up-to-date
    /// pending bag is returned.
    fn replace_pending<'p>(&self, old: Ptr<'p, Bag>, scope: &'p Scope)
                           -> Result<Ptr<'p, Bag>, Ptr<'p, Bag>> {
        match self.pending.compare_and_swap_weak_owned(old, Owned::new(Bag::new()), AcqRel, scope) {
            Ok(new) => {
                if !old.is_null() {
                    // Push the old bag into the queue.
                    let bag = unsafe { Box::from_raw(old.as_raw() as *mut _) };
                    self.push(bag, scope);
                }

                // Spare some cycles on garbage collection.
                // Note: This may itself produce garbage and allocate new bags.
                epoch::thread::try_advance(scope);
                self.collect(scope);

                Ok(new)
            }
            Err((pending, _)) => Err(pending)
        }
    }

    /// Adds an object that will later be freed.
    ///
    /// The specified object is an array allocated at address `object` and consists of `count`
    /// elements of type `T`.
    ///
    /// This method inserts the object into the garbage buffer. When the buffers becomes full, it's
    /// objects are flushed into the garbage queue.
    pub unsafe fn defer_free<T>(&self, object: *const T, count: usize, scope: &Scope) {
        unsafe fn free<T>(ptr: *mut T, count: usize) {
            // Free the memory, but don't run the destructors.
            drop(Vec::from_raw_parts(ptr, 0, count));
        }
        self.defer_destroy(free, object, count, scope);
    }

    /// Adds an object that will later be dropped and freed.
    ///
    /// The specified object is an array allocated at address `object` and consists of `count`
    /// elements of type `T`.
    ///
    /// This method inserts the object into the garbage buffer. When the buffers becomes full, it's
    /// objects are flushed into the garbage queue.
    ///
    /// Note: The object must be `Send + 'self`.
    pub unsafe fn defer_drop<T>(&self, object: *const T, count: usize, scope: &Scope) {
        unsafe fn destruct<T>(ptr: *mut T, count: usize) {
            // Run the destructors and free the memory.
            drop(Vec::from_raw_parts(ptr, count, count));
        }
        self.defer_destroy(destruct, object, count, scope);
    }

    /// Adds an object that will later be destroyed using `destroy`.
    ///
    /// The specified object is an array allocated at address `object` and consists of `count`
    /// elements of type `T`.
    ///
    /// This method inserts the object into the garbage buffer. When the buffers becomes full, it's
    /// objects are flushed into the garbage queue.
    ///
    /// Note: The object must be `Send + 'self`.
    pub unsafe fn defer_destroy<T>(
        &self,
        destroy: unsafe fn(*mut T, usize),
        object: *const T,
        count: usize,
        scope: &Scope
    ) {
        let mut pending = self.pending.load(Acquire, scope);
        loop {
            match pending.as_ref() {
                Some(p) if p.try_insert(destroy, object, count) => break,
                _ => {
                    match self.replace_pending(pending, scope) {
                        Ok(p) => pending = p,
                        Err(p) => pending = p,
                    }
                }
            }
        }
    }

    /// Flushes the buffered garbage.
    ///
    /// It is wise to flush the garbage just after passing a very large object to one of the
    /// `defer_*` methods, so that it isn't sitting in the buffer for a long time.
    pub fn flush(&self, scope: &Scope) {
        let mut pending = self.pending.load(Acquire, scope);
        loop {
            match unsafe { pending.as_ref() } {
                None => break,
                Some(p) => {
                    if p.is_empty() {
                        // The bag is already empty.
                        break;
                    } else {
                        match self.replace_pending(pending, scope) {
                            Ok(_) => break,
                            Err(p) => pending = p,
                        }
                    }
                }
            }
        }
    }

    /// Collects some garbage from the queue and destroys it.
    ///
    /// Generally speaking, it's not necessary to call this method because garbage production
    /// already triggers garbage destruction. However, if there are long periods without garbage
    /// production, it might be a good idea to call this method from time to time.
    ///
    /// This method collects several buffers worth of garbage objects.
    pub fn collect(&self, scope: &Scope) {
        /// Number of bags to destroy.
        const COLLECT_STEPS: usize = 8;

        let epoch = EPOCH.load(SeqCst);
        let condition = |bag: &Bag| {
            // A pinned thread can witness at most one epoch advancement. Therefore, any bag that
            // is within one epoch of the current one cannot be destroyed yet.
            let diff = epoch.wrapping_sub(bag.epoch);
            cmp::min(diff, 0usize.wrapping_sub(diff)) > 2
        };

        for _ in 0..COLLECT_STEPS {
            match self.try_pop_if(&condition, scope) {
                None => break,
                Some(bag) => unsafe { bag.destroy_all_objects() },
            }
        }
    }

    /// Pushes a bag into the queue.
    fn push(&self, mut bag: Box<Bag>, scope: &Scope) {
        // Mark the bag with the current epoch.
        bag.epoch = EPOCH.load(SeqCst);
        let mut bag = Owned::from_box(bag);

        let mut tail = self.tail.load(Acquire, scope);
        loop {
            let next = unsafe { tail.deref().next.load(Acquire, scope) };

            if next.is_null() {
                // Try installing the new bag.
                match unsafe { tail.deref() }.next.compare_and_swap_weak_owned(next, bag, AcqRel, scope) {
                    Ok(b) => {
                        // Tail pointer shouldn't fall behind. Let's move it forward.
                        let _ = self.tail.compare_and_swap(tail, b, AcqRel, scope);
                        break;
                    }
                    Err((t, b)) => {
                        tail = t;
                        bag = b;
                    }
                }
            } else {
                // This is not the actual tail. Move the tail pointer forward.
                match self.tail.compare_and_swap_weak(tail, next, AcqRel, scope) {
                    Ok(()) => tail = next,
                    Err(t) => tail = t,
                }
            }
        }
    }

    /// Attempts to pop a bag from the front of the queue and returns it if `condition` is met.
    ///
    /// If the bag in the front doesn't meet it or if the queue is empty, `None` is returned.
    fn try_pop_if<'p, F>(&self, condition: F, scope: &'p Scope) -> Option<&'p Bag>
        where F: Fn(&Bag) -> bool
    {
        let mut head = self.head.load(Acquire, scope);

        loop {
            let next = unsafe { head.deref().next.load(Acquire, scope) };

            match unsafe { next.as_ref() } {
                Some(n) if condition(n) => {
                    // Try moving the head forward.
                    match self.head.compare_and_swap_weak(head, next, AcqRel, scope) {
                        Ok(()) => {
                            // The old head may be later freed.
                            unsafe { scope.defer_free(head) }
                            // The new head holds the popped value (heads are sentinels!).
                            return Some(n);
                        }
                        Err(h) => head = h,
                    }
                }
                None | Some(_) => return None,
            }
        }
    }
}

impl Drop for Garbage {
    fn drop(&mut self) {
        unsafe {
            epoch::unprotected(|scope| {
                // Load the pending bag, then destroy it and all it's objects.
                let pending = self.pending.load(Relaxed, scope).as_raw();
                if !pending.is_null() {
                    (*pending).destroy_all_objects();
                    drop(Vec::from_raw_parts(pending as *mut Bag, 0, 1));
                }

                // Destroy all bags and objects in the queue.
                let mut head = self.head.load(Relaxed, scope).as_raw();
                loop {
                    // Load the next bag and destroy the current head.
                    let next = (*head).next.load(Relaxed, scope).as_raw();
                    drop(Vec::from_raw_parts(head as *mut Bag, 0, 1));

                    // If the next node is null, we've reached the end of the queue.
                    if next.is_null() {
                        break;
                    }

                    // Move one step forward.
                    head = next;

                    // Destroy all objects in this bag.
                    // The bag itself will be destroyed in the next iteration of the loop.
                    (*head).destroy_all_objects();
                }
            })
        }
    }
}

impl fmt::Debug for Garbage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Garbage {{ ... }}")
    }
}

/// Returns a reference to a global garbage, which is lazily initialized.
fn global() -> &'static Garbage {
    static GLOBAL: AtomicUsize = ATOMIC_USIZE_INIT;

    let current = GLOBAL.load(Acquire);

    let garbage = if current == 0 {
        // Initialize the singleton.
        let raw = Box::into_raw(Box::new(Garbage::new()));
        let new = raw as usize;
        let previous = GLOBAL.compare_and_swap(0, new, AcqRel);

        if previous == 0 {
            // Ok, we initialized it.
            new
        } else {
            // Another thread has already initialized it.
            unsafe { drop(Box::from_raw(raw)); }
            previous
        }
    } else {
        current
    };

    unsafe { &*(garbage as *const Garbage) }
}

/// Pushes a bag into the global garbage.
pub fn push(bag: Box<Bag>, scope: &Scope) {
    global().push(bag, scope);
}

/// Collects several bags from the global queue and destroys their objects.
pub fn collect(scope: &Scope) {
    global().collect(scope);
}

/// Destroys the global garbage.
///
/// # Safety
///
/// This function may only be called at the very end of the main thread, and only if the main
/// thread has never been pinned.
#[cfg(feature = "internals")]
pub unsafe fn destroy_global() {
    let global = global() as *const Garbage as *mut Garbage;
    drop(Box::from_raw(global));
}

#[cfg(test)]
mod tests {
    extern crate rand;

    use std::mem;
    use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
    use std::sync::atomic::Ordering::SeqCst;
    use std::sync::Arc;
    use std::thread;

    use self::rand::{Rng, thread_rng};

    use super::Garbage;
    use ::epoch;

    #[test]
    fn smoke() {
        let g = Garbage::new();
        epoch::pin(|scope| unsafe {
            let a = Box::into_raw(Box::new(7));
            g.defer_free(a, 1, scope);
            assert!(!g.pending.load(SeqCst, scope).deref().is_empty());
        });
    }

    #[test]
    fn flush_pending() {
        let g = Garbage::new();
        let mut rng = thread_rng();

        for _ in 0..100_000 {
            epoch::pin(|scope| unsafe {
                let a = Box::into_raw(Box::new(7));
                g.defer_drop(a, 1, scope);

                if rng.gen_range(0, 100) == 0 {
                    g.flush(scope);
                    assert!(g.pending.load(SeqCst, scope).deref().is_empty());
                }
            });
        }
    }

    #[test]
    fn incremental() {
        const COUNT: usize = 100_000;
        static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT;

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            for _ in 0..COUNT {
                let a = Box::into_raw(Box::new(7i32));
                unsafe fn destroy(ptr: *mut i32, count: usize) {
                    drop(Box::from_raw(ptr));
                    DESTROYS.fetch_add(count, SeqCst);
                }
                g.defer_destroy(destroy, a, 1, scope);
            }
            g.flush(scope);
        });

        let mut last = 0;

        while last < COUNT {
            let curr = DESTROYS.load(SeqCst);
            assert!(curr - last < 1000);
            last = curr;

            epoch::pin(|scope| g.collect(scope));
        }
        assert!(DESTROYS.load(SeqCst) == COUNT);
    }

    #[test]
    fn buffering() {
        const COUNT: usize = 10;
        static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT;

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            for _ in 0..COUNT {
                let a = Box::into_raw(Box::new(7i32));
                unsafe fn destroy(ptr: *mut i32, count: usize) {
                    drop(Box::from_raw(ptr));
                    DESTROYS.fetch_add(count, SeqCst);
                }
                g.defer_destroy(destroy, a, 1, scope);
            }
        });

        for _ in 0..100_000 {
            epoch::pin(|scope| {
                g.collect(scope);
                assert!(DESTROYS.load(SeqCst) < COUNT);
            });
        }
        epoch::pin(|scope| g.flush(scope));

        while DESTROYS.load(SeqCst) < COUNT {
            epoch::pin(|scope| g.collect(scope));
        }
        assert_eq!(DESTROYS.load(SeqCst), COUNT);
    }

    #[test]
    fn count_drops() {
        const COUNT: usize = 100_000;
        static DROPS: AtomicUsize = ATOMIC_USIZE_INIT;

        struct Elem(i32);

        impl Drop for Elem {
            fn drop(&mut self) {
                DROPS.fetch_add(1, SeqCst);
            }
        }

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            for _ in 0..COUNT {
                let a = Box::into_raw(Box::new(Elem(7i32)));
                g.defer_drop(a, 1, scope);
            }
            g.flush(scope);
        });

        while DROPS.load(SeqCst) < COUNT {
            epoch::pin(|scope| g.collect(scope));
        }
        assert_eq!(DROPS.load(SeqCst), COUNT);
    }

    #[test]
    fn count_destroy() {
        const COUNT: usize = 100_000;
        static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT;

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            for _ in 0..COUNT {
                let a = Box::into_raw(Box::new(7i32));
                unsafe fn destroy(ptr: *mut i32, count: usize) {
                    drop(Box::from_raw(ptr));
                    DESTROYS.fetch_add(count, SeqCst);
                }
                g.defer_destroy(destroy, a, 1, scope);
            }
            g.flush(scope);
        });

        while DESTROYS.load(SeqCst) < COUNT {
            epoch::pin(|scope| g.collect(scope));
        }
        assert_eq!(DESTROYS.load(SeqCst), COUNT);
    }

    #[test]
    fn drop_array() {
        const COUNT: usize = 700;
        static DROPS: AtomicUsize = ATOMIC_USIZE_INIT;

        struct Elem(i32);

        impl Drop for Elem {
            fn drop(&mut self) {
                DROPS.fetch_add(1, SeqCst);
            }
        }

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            let mut v = Vec::with_capacity(COUNT);
            for i in 0..COUNT {
                v.push(Elem(i as i32));
            }

            g.defer_drop(v.as_mut_ptr(), v.len(), scope);
            g.flush(scope);

            mem::forget(v);
        });

        while DROPS.load(SeqCst) < COUNT {
            epoch::pin(|scope| g.collect(scope));
        }
        assert_eq!(DROPS.load(SeqCst), COUNT);
    }

    #[test]
    fn destroy_array() {
        const COUNT: usize = 100_000;
        static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT;

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            let mut v = Vec::with_capacity(COUNT);
            for i in 0..COUNT {
                v.push(i as i32);
            }

            unsafe fn destroy(ptr: *mut i32, count: usize) {
                assert!(count == COUNT);
                drop(Vec::from_raw_parts(ptr, count, count));
                DESTROYS.fetch_add(count, SeqCst);
            }
            g.defer_destroy(destroy, v.as_mut_ptr(), v.len(), scope);
            g.flush(scope);

            mem::forget(v);
        });

        while DESTROYS.load(SeqCst) < COUNT {
            epoch::pin(|scope| g.collect(scope));
        }
        assert_eq!(DESTROYS.load(SeqCst), COUNT);
    }

    #[test]
    fn drop_garbage() {
        const COUNT: usize = 100_000;
        static DROPS: AtomicUsize = ATOMIC_USIZE_INIT;

        struct Elem(i32);

        impl Drop for Elem {
            fn drop(&mut self) {
                DROPS.fetch_add(1, SeqCst);
            }
        }

        let g = Garbage::new();

        epoch::pin(|scope| unsafe {
            for _ in 0..COUNT {
                let a = Box::into_raw(Box::new(Elem(7i32)));
                g.defer_drop(a, 1, scope);
            }
            g.flush(scope);
        });

        drop(g);
        assert_eq!(DROPS.load(SeqCst), COUNT);
    }

    #[test]
    fn stress() {
        const THREADS: usize = 8;
        const COUNT: usize = 100_000;
        static DROPS: AtomicUsize = ATOMIC_USIZE_INIT;

        struct Elem(i32);

        impl Drop for Elem {
            fn drop(&mut self) {
                DROPS.fetch_add(1, SeqCst);
            }
        }

        let g = Arc::new(Garbage::new());

        let threads = (0..THREADS).map(|_| {
            let g = g.clone();

            thread::spawn(move || {
                for _ in 0..COUNT {
                    epoch::pin(|scope| unsafe {
                        let a = Box::into_raw(Box::new(Elem(7i32)));
                        g.defer_drop(a, 1, scope);
                    });
                }
            })
        }).collect::<Vec<_>>();

        for t in threads {
            t.join().unwrap();
        }

        drop(g);
        assert_eq!(DROPS.load(SeqCst), COUNT * THREADS);
    }
}