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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use epoch::Scope;

/// Given ordering for the success case in a compare-exchange operation, returns the strongest
/// appropriate ordering for the failure case.
#[inline]
fn strongest_failure_ordering(ord: Ordering) -> Ordering {
    use self::Ordering::*;
    match ord {
        Relaxed => Relaxed,
        Release => Relaxed,
        Acquire => Acquire,
        AcqRel => Acquire,
        SeqCst => SeqCst,
        _ => SeqCst,
    }
}

/// Panics if the pointer is not properly unaligned.
#[inline]
fn ensure_aligned<T>(raw: *const T) {
    assert!(raw as usize & low_bits::<T>() == 0, "unaligned pointer");
}

/// Returns a bitmask containing the unused least significant bits of an aligned pointer to `T`.
#[inline]
fn low_bits<T>() -> usize {
    (1 << mem::align_of::<T>().trailing_zeros()) - 1
}

/// Given a tagged pointer `data`, returns the same pointer, but tagged with `tag`.
/// Panics if the tag doesn't fit into the unused bits of the pointer.
#[inline]
fn data_with_tag<T>(data: usize, tag: usize) -> usize {
    let mask = low_bits::<T>();
    validate_tag::<T>(tag);
    (data & !mask) | tag
}

/// An atomic pointer that can be safely shared between threads.
///
/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
/// least significant bits of the address.
///
/// Any method that loads the pointer must be passed a reference to a [`Scope`].
///
/// [`Scope`]: struct.Scope.html
#[derive(Debug)]
pub struct Atomic<T> {
    data: AtomicUsize,
    _marker: PhantomData<*mut T>,
}

unsafe impl<T: Send + Sync> Send for Atomic<T> {}
unsafe impl<T: Send + Sync> Sync for Atomic<T> {}

/// Panics if the tag doesn't fit into the unused bits of an aligned pointer to `T`.
#[inline]
fn validate_tag<T>(tag: usize) {
    let mask = low_bits::<T>();
    assert!(
        tag <= mask,
        "tag too large to fit into the unused bits: {} > {}",
        tag,
        mask
    );
}

impl<T> Atomic<T> {
    /// Returns a new atomic pointer initialized with the tagged pointer `data`.
    fn from_data(data: usize) -> Self {
        Atomic {
            data: AtomicUsize::new(data),
            _marker: PhantomData,
        }
    }

    /// Returns a new null atomic pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Atomic;
    ///
    /// let a = Atomic::<i32>::null();
    /// ```
    pub fn null() -> Self {
        Atomic {
            data: AtomicUsize::new(0),
            _marker: PhantomData,
        }
    }

    /// Allocates `value` on the heap and returns a new atomic pointer pointing to it.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Atomic;
    ///
    /// let a = Atomic::new(1234);
    /// ```
    pub fn new(value: T) -> Self {
        Self::from_owned(Owned::new(value))
    }

    /// Returns a new atomic pointer pointing to `owned`.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{Atomic, Owned};
    ///
    /// let a = Atomic::from_owned(Owned::new(1234));
    /// ```
    pub fn from_owned(owned: Owned<T>) -> Self {
        let data = owned.data;
        mem::forget(owned);
        Self::from_data(data)
    }

    /// Returns a new atomic pointer pointing to `ptr`.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{Atomic, Ptr};
    ///
    /// let a = Atomic::from_ptr(Ptr::<i32>::null());
    /// ```
    pub fn from_ptr(ptr: Ptr<T>) -> Self {
        Self::from_data(ptr.data)
    }

    /// Loads a `Ptr` from the atomic pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    /// epoch::pin(|scope| {
    ///     let p = a.load(SeqCst, scope);
    /// });
    /// ```
    pub fn load<'scope>(&self, ord: Ordering, _: &'scope Scope) -> Ptr<'scope, T> {
        Ptr::from_data(self.data.load(ord))
    }

    /// Stores a `Ptr` into the atomic pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    /// a.store(Ptr::null(), SeqCst);
    /// ```
    pub fn store(&self, new: Ptr<T>, ord: Ordering) {
        self.data.store(new.data, ord);
    }

    /// Stores an `Owned` into the atomic pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::null();
    /// a.store_owned(Owned::new(1234), SeqCst);
    /// ```
    pub fn store_owned(&self, new: Owned<T>, ord: Ordering) {
        let data = new.data;
        mem::forget(new);
        self.data.store(data, ord);
    }

    /// Stores a `Ptr` into the atomic pointer, returning the previous `Ptr`.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    /// epoch::pin(|scope| {
    ///     let p = a.swap(Ptr::null(), SeqCst, scope);
    /// });
    /// ```
    pub fn swap<'scope>(&self, new: Ptr<T>, ord: Ordering, _: &'scope Scope) -> Ptr<'scope, T> {
        Ptr::from_data(self.data.swap(new.data, ord))
    }

    /// Stores `new` into the atomic pointer if the current value is the same as `current`.
    ///
    /// The return value is a result indicating whether the new pointer was written. On failure the
    /// actual current value is returned.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    ///
    /// epoch::pin(|scope| {
    ///     let mut curr = a.load(SeqCst, scope);
    ///     let res = a.compare_and_swap(curr, Ptr::null(), SeqCst, scope);
    /// });
    /// ```
    pub fn compare_and_swap<'scope>(
        &self,
        current: Ptr<T>,
        new: Ptr<T>,
        ord: Ordering,
        _: &'scope Scope,
    ) -> Result<(), Ptr<'scope, T>> {
        let fail_ord = strongest_failure_ordering(ord);
        match self.data.compare_exchange(current.data, new.data, ord, fail_ord) {
            Ok(_) => Ok(()),
            Err(previous) => Err(Ptr::from_data(previous)),
        }
    }

    /// Stores `new` into the atomic pointer if the current value is the same as `current`.
    ///
    /// Unlike [`compare_and_swap`], this method is allowed to spuriously fail even when
    /// comparison succeeds, which can result in more efficient code on some platforms.
    /// The return value is a result indicating whether the new pointer was written. On failure the
    /// actual current value is returned.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`compare_and_swap`]: struct.Atomic.html#method.compare_and_swap
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    ///
    /// epoch::pin(|scope| {
    ///     let mut curr = a.load(SeqCst, scope);
    ///     loop {
    ///         match a.compare_and_swap_weak(curr, Ptr::null(), SeqCst, scope) {
    ///             Ok(()) => break,
    ///             Err(c) => curr = c,
    ///         }
    ///     }
    /// });
    /// ```
    pub fn compare_and_swap_weak<'scope>(
        &self,
        current: Ptr<T>,
        new: Ptr<T>,
        ord: Ordering,
        _: &'scope Scope,
    ) -> Result<(), Ptr<'scope, T>> {
        let fail_ord = strongest_failure_ordering(ord);
        match self.data.compare_exchange_weak(current.data, new.data, ord, fail_ord) {
            Ok(_) => Ok(()),
            Err(previous) => Err(Ptr::from_data(previous)),
        }
    }

    /// Stores `new` into the atomic pointer if the current value is the same as `current`.
    ///
    /// The return value is a result indicating whether the new pointer was written. On success the
    /// pointer that was written is returned. On failure `new` and the actual current value are
    /// returned.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    ///
    /// epoch::pin(|scope| {
    ///     let mut curr = a.load(SeqCst, scope);
    ///     let res = a.compare_and_swap_owned(curr, Owned::new(5678), SeqCst, scope);
    /// });
    /// ```
    pub fn compare_and_swap_owned<'scope>(
        &self,
        current: Ptr<T>,
        new: Owned<T>,
        ord: Ordering,
        _: &'scope Scope,
    ) -> Result<Ptr<'scope, T>, (Ptr<'scope, T>, Owned<T>)> {
        let fail_ord = strongest_failure_ordering(ord);
        match self.data.compare_exchange(current.data, new.data, ord, fail_ord) {
            Ok(_) => {
                let data = new.data;
                mem::forget(new);
                Ok(Ptr::from_data(data))
            }
            Err(previous) => Err((Ptr::from_data(previous), new)),
        }
    }

    /// Stores `new` into the atomic pointer if the current value is the same as `current`.
    ///
    /// Unlike [`compare_and_swap_owned`], this method is allowed to spuriously fail even when
    /// comparison succeeds, which can result in more efficient code on some platforms.
    /// The return value is a result indicating whether the new pointer was written. On success the
    /// pointer that was written is returned. On failure `new` and the actual current value are
    /// returned.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`compare_and_swap_owned`]: struct.Atomic.html#method.compare_and_swap_owned
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    ///
    /// epoch::pin(|scope| {
    ///     let mut new = Owned::new(5678);
    ///     let mut ptr = a.load(SeqCst, scope);
    ///     loop {
    ///         match a.compare_and_swap_weak_owned(ptr, new, SeqCst, scope) {
    ///             Ok(p) => {
    ///                 ptr = p;
    ///                 break;
    ///             }
    ///             Err((p, n)) => {
    ///                 ptr = p;
    ///                 new = n;
    ///             }
    ///         }
    ///     }
    /// });
    /// ```
    pub fn compare_and_swap_weak_owned<'scope>(
        &self,
        current: Ptr<T>,
        new: Owned<T>,
        ord: Ordering,
        _: &'scope Scope,
    ) -> Result<Ptr<'scope, T>, (Ptr<'scope, T>, Owned<T>)> {
        let fail_ord = strongest_failure_ordering(ord);
        match self.data.compare_exchange_weak(current.data, new.data, ord, fail_ord) {
            Ok(_) => {
                let data = new.data;
                mem::forget(new);
                Ok(Ptr::from_data(data))
            }
            Err(previous) => Err((Ptr::from_data(previous), new)),
        }
    }

    /// Bitwise "and" with the current tag.
    ///
    /// Performs a bitwise "and" operation on the current tag and the argument `val`, and sets the
    /// new tag to the result. Returns the previous pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::<i32>::from_ptr(Ptr::null().with_tag(3));
    /// epoch::pin(|scope| {
    ///     assert_eq!(a.fetch_and(2, SeqCst, scope).tag(), 3);
    ///     assert_eq!(a.load(SeqCst, scope).tag(), 2);
    /// });
    /// ```
    pub fn fetch_and<'scope>(&self, val: usize, ord: Ordering, _: &'scope Scope) -> Ptr<'scope, T> {
        Ptr::from_data(self.data.fetch_and(val | !low_bits::<T>(), ord))
    }

    /// Bitwise "or" with the current tag.
    ///
    /// Performs a bitwise "or" operation on the current tag and the argument `val`, and sets the
    /// new tag to the result. Returns the previous pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::<i32>::from_ptr(Ptr::null().with_tag(1));
    /// epoch::pin(|scope| {
    ///     assert_eq!(a.fetch_or(2, SeqCst, scope).tag(), 1);
    ///     assert_eq!(a.load(SeqCst, scope).tag(), 3);
    /// });
    /// ```
    pub fn fetch_or<'scope>(&self, val: usize, ord: Ordering, _: &'scope Scope) -> Ptr<'scope, T> {
        Ptr::from_data(self.data.fetch_or(val & low_bits::<T>(), ord))
    }

    /// Bitwise "xor" with the current tag.
    ///
    /// Performs a bitwise "xor" operation on the current tag and the argument `val`, and sets the
    /// new tag to the result. Returns the previous pointer.
    ///
    /// This method takes an [`Ordering`] argument which describes the memory ordering of this
    /// operation.
    ///
    /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Ptr};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::<i32>::from_ptr(Ptr::null().with_tag(1));
    /// epoch::pin(|scope| {
    ///     assert_eq!(a.fetch_xor(3, SeqCst, scope).tag(), 1);
    ///     assert_eq!(a.load(SeqCst, scope).tag(), 2);
    /// });
    /// ```
    pub fn fetch_xor<'scope>(&self, val: usize, ord: Ordering, _: &'scope Scope) -> Ptr<'scope, T> {
        Ptr::from_data(self.data.fetch_xor(val & low_bits::<T>(), ord))
    }
}

impl<T> Default for Atomic<T> {
    fn default() -> Self {
        Atomic::null()
    }
}

/// An owned heap-allocated object.
///
/// This type is very similar to `Box<T>`.
///
/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
/// least significant bits of the address.
#[derive(Debug)]
pub struct Owned<T> {
    data: usize,
    _marker: PhantomData<Box<T>>,
}

impl<T> Owned<T> {
    /// Returns a new owned pointer initialized with the tagged pointer `data`.
    fn from_data(data: usize) -> Self {
        Owned {
            data: data,
            _marker: PhantomData,
        }
    }

    /// Allocates `value` on the heap and returns a new owned pointer pointing to it.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Owned;
    ///
    /// let o = Owned::new(1234);
    /// ```
    pub fn new(value: T) -> Self {
        Self::from_box(Box::new(value))
    }

    /// Returns a new owned pointer initialized with `b`.
    ///
    /// # Panics
    ///
    /// Panics if the pointer (the `Box`) is not properly aligned.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Owned;
    ///
    /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
    /// ```
    pub fn from_box(b: Box<T>) -> Self {
        unsafe { Self::from_raw(Box::into_raw(b)) }
    }

    /// Returns a new owned pointer initialized with `raw`.
    ///
    /// # Panics
    ///
    /// Panics if `raw` is not properly aligned.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Owned;
    ///
    /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
    /// ```
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        ensure_aligned(raw);
        Self::from_data(raw as usize)
    }

    /// Converts the owned pointer to a [`Ptr`].
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Owned};
    ///
    /// let o = Owned::new(1234);
    /// epoch::pin(|scope| {
    ///     let p = o.into_ptr(scope);
    /// });
    /// ```
    ///
    /// [`Ptr`]: struct.Ptr.html
    pub fn into_ptr<'scope>(self, _: &'scope Scope) -> Ptr<'scope, T> {
        let data = self.data;
        mem::forget(self);
        Ptr::from_data(data)
    }

    /// Returns the tag stored within the pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Owned;
    ///
    /// assert_eq!(Owned::new(1234).tag(), 0);
    /// ```
    pub fn tag(&self) -> usize {
        self.data & low_bits::<T>()
    }

    /// Returns the same pointer, but tagged with `tag`.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Owned;
    ///
    /// let o = Owned::new(0u64);
    /// assert_eq!(o.tag(), 0);
    /// let o = o.with_tag(5);
    /// assert_eq!(o.tag(), 5);
    /// ```
    pub fn with_tag(self, tag: usize) -> Self {
        let data = self.data;
        mem::forget(self);
        Self::from_data(data_with_tag::<T>(data, tag))
    }
}

impl<T> Drop for Owned<T> {
    fn drop(&mut self) {
        let raw = (self.data & !low_bits::<T>()) as *mut T;
        unsafe {
            drop(Box::from_raw(raw));
        }
    }
}

impl<T> Deref for Owned<T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*((self.data & !low_bits::<T>()) as *const T) }
    }
}

impl<T> DerefMut for Owned<T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *((self.data & !low_bits::<T>()) as *mut T) }
    }
}

/// A pointer to an object protected by the epoch GC.
///
/// The pointer is valid for use only within `'scope`.
///
/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
/// least significant bits of the address.
#[derive(Debug)]
pub struct Ptr<'scope, T: 'scope> {
    data: usize,
    _marker: PhantomData<&'scope T>,
}

impl<'scope, T> Clone for Ptr<'scope, T> {
    fn clone(&self) -> Self {
        Ptr {
            data: self.data,
            _marker: PhantomData,
        }
    }
}

impl<'scope, T> Copy for Ptr<'scope, T> {}

impl<'scope, T> Ptr<'scope, T> {
    /// Returns a new pointer initialized with the tagged pointer `data`.
    fn from_data(data: usize) -> Self {
        Ptr {
            data: data,
            _marker: PhantomData,
        }
    }

    /// Returns a new null pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Ptr;
    ///
    /// let p = Ptr::<i32>::null();
    /// assert!(p.is_null());
    /// ```
    pub fn null() -> Self {
        Ptr {
            data: 0,
            _marker: PhantomData,
        }
    }

    /// Returns a new pointer initialized with `raw`.
    ///
    /// # Panics
    ///
    /// Panics if `raw` is not properly aligned.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::Ptr;
    ///
    /// let p = unsafe { Ptr::from_raw(Box::into_raw(Box::new(1234))) };
    /// assert!(!p.is_null());
    /// ```
    pub unsafe fn from_raw(raw: *const T) -> Self {
        ensure_aligned(raw);
        Ptr {
            data: raw as usize,
            _marker: PhantomData,
        }
    }

    /// Returns `true` if the pointer is null.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::null();
    /// epoch::pin(|scope| {
    ///     assert!(a.load(SeqCst, scope).is_null());
    ///     a.store_owned(Owned::new(1234), SeqCst);
    ///     assert!(!a.load(SeqCst, scope).is_null());
    /// });
    /// ```
    pub fn is_null(&self) -> bool {
        self.as_raw().is_null()
    }

    /// Converts the pointer to a raw pointer (without the tag).
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let o = Owned::new(1234);
    /// let raw = &*o as *const _;
    /// let a = Atomic::from_owned(o);
    ///
    /// epoch::pin(|scope| {
    ///     let p = a.load(SeqCst, scope);
    ///     assert_eq!(p.as_raw(), raw);
    /// });
    /// ```
    pub fn as_raw(&self) -> *const T {
        (self.data & !low_bits::<T>()) as *const T
    }

    /// Dereferences the pointer.
    ///
    /// Returns a reference to the pointee that is valid in `'scope`.
    ///
    /// # Safety
    ///
    /// Dereferencing a pointer to an invalid object is not a concern, since invalid `Ptr`s
    /// can only be constructed via other unsafe functions.
    ///
    /// However, this method doesn't check whether the pointer is null, so dereferencing a null
    /// pointer is unsafe.
    ///
    /// Another source of unsafety is the possibility of unsynchronized reads to the objects.
    /// For example, the following scenario is unsafe:
    ///
    /// * A thread stores a new object: `a.store_owned(Owned::new(10), Relaxed)`
    /// * Another thread reads it: `*a.load(Relaxed, scope).as_ref().unwrap()`
    ///
    /// The problem is that relaxed orderings don't synchronize initialization of the object with
    /// the read from the second thread. This is a data race. A possible solution would be to use
    /// `Release` and `Acquire` orderings (or stronger).
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    /// epoch::pin(|scope| {
    ///     let p = a.load(SeqCst, scope);
    ///     unsafe {
    ///         assert_eq!(p.deref(), &1234);
    ///     }
    /// });
    /// ```
    pub unsafe fn deref(&self) -> &'scope T {
        &*self.as_raw()
    }

    /// Converts the pointer to a reference.
    ///
    /// Returns `None` if the pointer is null, or else a reference to the object wrapped in `Some`.
    ///
    /// # Safety
    ///
    /// This method checks whether the pointer is null, and if not, assumes that it's pointing to a
    /// valid object. However, this is not considered a source of unsafety because invalid `Ptr`s
    /// can only be constructed via other unsafe functions.
    ///
    /// The only source of unsafety is the possibility of unsynchronized reads to the objects.
    /// For example, the following scenario is unsafe:
    ///
    /// * A thread stores a new object: `a.store_owned(Owned::new(10), Relaxed)`
    /// * Another thread reads it: `*a.load(Relaxed, scope).as_ref().unwrap()`
    ///
    /// The problem is that relaxed orderings don't synchronize initialization of the object with
    /// the read from the second thread. This is a data race. A possible solution would be to use
    /// `Release` and `Acquire` orderings (or stronger).
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(1234);
    /// epoch::pin(|scope| {
    ///     let p = a.load(SeqCst, scope);
    ///     unsafe {
    ///         assert_eq!(p.as_ref(), Some(&1234));
    ///     }
    /// });
    /// ```
    pub unsafe fn as_ref(&self) -> Option<&'scope T> {
        self.as_raw().as_ref()
    }

    /// Returns the tag stored within the pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic, Owned};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::from_owned(Owned::new(0u64).with_tag(5));
    /// epoch::pin(|scope| {
    ///     let p = a.load(SeqCst, scope);
    ///     assert_eq!(p.tag(), 5);
    /// });
    /// ```
    pub fn tag(&self) -> usize {
        self.data & low_bits::<T>()
    }

    /// Returns the same pointer, but tagged with `tag`.
    ///
    /// # Examples
    ///
    /// ```
    /// use coco::epoch::{self, Atomic};
    /// use std::sync::atomic::Ordering::SeqCst;
    ///
    /// let a = Atomic::new(0u64);
    /// epoch::pin(|scope| {
    ///     let p1 = a.load(SeqCst, scope);
    ///     let p2 = p1.with_tag(5);
    ///
    ///     assert_eq!(p1.tag(), 0);
    ///     assert_eq!(p2.tag(), 5);
    ///     assert_eq!(p1.as_raw(), p2.as_raw());
    /// });
    /// ```
    pub fn with_tag(&self, tag: usize) -> Self {
        Self::from_data(data_with_tag::<T>(self.data, tag))
    }
}

impl<'scope, T> Default for Ptr<'scope, T> {
    fn default() -> Self {
        Ptr::null()
    }
}