crossbeam_epoch/atomic.rs
1use alloc::boxed::Box;
2use core::alloc::Layout;
3use core::borrow::{Borrow, BorrowMut};
4use core::cmp;
5use core::fmt;
6use core::marker::PhantomData;
7use core::mem::{self, MaybeUninit};
8use core::ops::{Deref, DerefMut};
9use core::ptr;
10use core::slice;
11
12use crate::guard::Guard;
13use crate::primitive::sync::atomic::{AtomicUsize, Ordering};
14use crossbeam_utils::atomic::AtomicConsume;
15
16/// Given ordering for the success case in a compare-exchange operation, returns the strongest
17/// appropriate ordering for the failure case.
18#[inline]
19fn strongest_failure_ordering(ord: Ordering) -> Ordering {
20 use self::Ordering::*;
21 match ord {
22 Relaxed | Release => Relaxed,
23 Acquire | AcqRel => Acquire,
24 _ => SeqCst,
25 }
26}
27
28/// The error returned on failed compare-and-set operation.
29// TODO: remove in the next major version.
30#[deprecated(note = "Use `CompareExchangeError` instead")]
31pub type CompareAndSetError<'g, T, P> = CompareExchangeError<'g, T, P>;
32
33/// The error returned on failed compare-and-swap operation.
34pub struct CompareExchangeError<'g, T: ?Sized + Pointable, P: Pointer<T>> {
35 /// The value in the atomic pointer at the time of the failed operation.
36 pub current: Shared<'g, T>,
37
38 /// The new value, which the operation failed to store.
39 pub new: P,
40}
41
42impl<T, P: Pointer<T> + fmt::Debug> fmt::Debug for CompareExchangeError<'_, T, P> {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.debug_struct("CompareExchangeError")
45 .field("current", &self.current)
46 .field("new", &self.new)
47 .finish()
48 }
49}
50
51/// Memory orderings for compare-and-set operations.
52///
53/// A compare-and-set operation can have different memory orderings depending on whether it
54/// succeeds or fails. This trait generalizes different ways of specifying memory orderings.
55///
56/// The two ways of specifying orderings for compare-and-set are:
57///
58/// 1. Just one `Ordering` for the success case. In case of failure, the strongest appropriate
59/// ordering is chosen.
60/// 2. A pair of `Ordering`s. The first one is for the success case, while the second one is
61/// for the failure case.
62// TODO: remove in the next major version.
63#[deprecated(
64 note = "`compare_and_set` and `compare_and_set_weak` that use this trait are deprecated, \
65 use `compare_exchange` or `compare_exchange_weak instead`"
66)]
67pub trait CompareAndSetOrdering {
68 /// The ordering of the operation when it succeeds.
69 fn success(&self) -> Ordering;
70
71 /// The ordering of the operation when it fails.
72 ///
73 /// The failure ordering can't be `Release` or `AcqRel` and must be equivalent or weaker than
74 /// the success ordering.
75 fn failure(&self) -> Ordering;
76}
77
78#[allow(deprecated)]
79impl CompareAndSetOrdering for Ordering {
80 #[inline]
81 fn success(&self) -> Ordering {
82 *self
83 }
84
85 #[inline]
86 fn failure(&self) -> Ordering {
87 strongest_failure_ordering(*self)
88 }
89}
90
91#[allow(deprecated)]
92impl CompareAndSetOrdering for (Ordering, Ordering) {
93 #[inline]
94 fn success(&self) -> Ordering {
95 self.0
96 }
97
98 #[inline]
99 fn failure(&self) -> Ordering {
100 self.1
101 }
102}
103
104/// Returns a bitmask containing the unused least significant bits of an aligned pointer to `T`.
105#[inline]
106fn low_bits<T: ?Sized + Pointable>() -> usize {
107 (1 << T::ALIGN.trailing_zeros()) - 1
108}
109
110/// Panics if the pointer is not properly unaligned.
111#[inline]
112fn ensure_aligned<T: ?Sized + Pointable>(raw: usize) {
113 assert_eq!(raw & low_bits::<T>(), 0, "unaligned pointer");
114}
115
116/// Given a tagged pointer `data`, returns the same pointer, but tagged with `tag`.
117///
118/// `tag` is truncated to fit into the unused bits of the pointer to `T`.
119#[inline]
120fn compose_tag<T: ?Sized + Pointable>(data: usize, tag: usize) -> usize {
121 (data & !low_bits::<T>()) | (tag & low_bits::<T>())
122}
123
124/// Decomposes a tagged pointer `data` into the pointer and the tag.
125#[inline]
126fn decompose_tag<T: ?Sized + Pointable>(data: usize) -> (usize, usize) {
127 (data & !low_bits::<T>(), data & low_bits::<T>())
128}
129
130/// Types that are pointed to by a single word.
131///
132/// In concurrent programming, it is necessary to represent an object within a word because atomic
133/// operations (e.g., reads, writes, read-modify-writes) support only single words. This trait
134/// qualifies such types that are pointed to by a single word.
135///
136/// The trait generalizes `Box<T>` for a sized type `T`. In a box, an object of type `T` is
137/// allocated in heap and it is owned by a single-word pointer. This trait is also implemented for
138/// `[MaybeUninit<T>]` by storing its size along with its elements and pointing to the pair of array
139/// size and elements.
140///
141/// Pointers to `Pointable` types can be stored in [`Atomic`], [`Owned`], and [`Shared`]. In
142/// particular, Crossbeam supports dynamically sized slices as follows.
143///
144/// ```
145/// use std::mem::MaybeUninit;
146/// use crossbeam_epoch::Owned;
147///
148/// let o = Owned::<[MaybeUninit<i32>]>::init(10); // allocating [i32; 10]
149/// ```
150pub trait Pointable {
151 /// The alignment of pointer.
152 const ALIGN: usize;
153
154 /// The type for initializers.
155 type Init;
156
157 /// Initializes a with the given initializer.
158 ///
159 /// # Safety
160 ///
161 /// The result should be a multiple of `ALIGN`.
162 unsafe fn init(init: Self::Init) -> usize;
163
164 /// Dereferences the given pointer.
165 ///
166 /// # Safety
167 ///
168 /// - The given `ptr` should have been initialized with [`Pointable::init`].
169 /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
170 /// - `ptr` should not be mutably dereferenced by [`Pointable::deref_mut`] concurrently.
171 unsafe fn deref<'a>(ptr: usize) -> &'a Self;
172
173 /// Mutably dereferences the given pointer.
174 ///
175 /// # Safety
176 ///
177 /// - The given `ptr` should have been initialized with [`Pointable::init`].
178 /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
179 /// - `ptr` should not be dereferenced by [`Pointable::deref`] or [`Pointable::deref_mut`]
180 /// concurrently.
181 unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self;
182
183 /// Drops the object pointed to by the given pointer.
184 ///
185 /// # Safety
186 ///
187 /// - The given `ptr` should have been initialized with [`Pointable::init`].
188 /// - `ptr` should not have yet been dropped by [`Pointable::drop`].
189 /// - `ptr` should not be dereferenced by [`Pointable::deref`] or [`Pointable::deref_mut`]
190 /// concurrently.
191 unsafe fn drop(ptr: usize);
192}
193
194impl<T> Pointable for T {
195 const ALIGN: usize = mem::align_of::<T>();
196
197 type Init = T;
198
199 unsafe fn init(init: Self::Init) -> usize {
200 Box::into_raw(Box::new(init)) as usize
201 }
202
203 unsafe fn deref<'a>(ptr: usize) -> &'a Self {
204 &*(ptr as *const T)
205 }
206
207 unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self {
208 &mut *(ptr as *mut T)
209 }
210
211 unsafe fn drop(ptr: usize) {
212 drop(Box::from_raw(ptr as *mut T));
213 }
214}
215
216/// Array with size.
217///
218/// # Memory layout
219///
220/// An array consisting of size and elements:
221///
222/// ```text
223/// elements
224/// |
225/// |
226/// ------------------------------------
227/// | size | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
228/// ------------------------------------
229/// ```
230///
231/// Its memory layout is different from that of `Box<[T]>` in that size is in the allocation (not
232/// along with pointer as in `Box<[T]>`).
233///
234/// Elements are not present in the type, but they will be in the allocation.
235#[repr(C)]
236struct Array<T> {
237 /// The number of elements (not the number of bytes).
238 len: usize,
239 elements: [MaybeUninit<T>; 0],
240}
241
242impl<T> Array<T> {
243 fn layout(len: usize) -> Layout {
244 Layout::new::<Self>()
245 .extend(Layout::array::<MaybeUninit<T>>(len).unwrap())
246 .unwrap()
247 .0
248 .pad_to_align()
249 }
250}
251
252impl<T> Pointable for [MaybeUninit<T>] {
253 const ALIGN: usize = mem::align_of::<Array<T>>();
254
255 type Init = usize;
256
257 unsafe fn init(len: Self::Init) -> usize {
258 let layout = Array::<T>::layout(len);
259 let ptr = alloc::alloc::alloc(layout).cast::<Array<T>>();
260 if ptr.is_null() {
261 alloc::alloc::handle_alloc_error(layout);
262 }
263 ptr::addr_of_mut!((*ptr).len).write(len);
264 ptr as usize
265 }
266
267 unsafe fn deref<'a>(ptr: usize) -> &'a Self {
268 let array = &*(ptr as *const Array<T>);
269 slice::from_raw_parts(array.elements.as_ptr() as *const _, array.len)
270 }
271
272 unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut Self {
273 let array = &*(ptr as *mut Array<T>);
274 slice::from_raw_parts_mut(array.elements.as_ptr() as *mut _, array.len)
275 }
276
277 unsafe fn drop(ptr: usize) {
278 let len = (*(ptr as *mut Array<T>)).len;
279 let layout = Array::<T>::layout(len);
280 alloc::alloc::dealloc(ptr as *mut u8, layout);
281 }
282}
283
284/// An atomic pointer that can be safely shared between threads.
285///
286/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
287/// least significant bits of the address. For example, the tag for a pointer to a sized type `T`
288/// should be less than `(1 << mem::align_of::<T>().trailing_zeros())`.
289///
290/// Any method that loads the pointer must be passed a reference to a [`Guard`].
291///
292/// Crossbeam supports dynamically sized types. See [`Pointable`] for details.
293pub struct Atomic<T: ?Sized + Pointable> {
294 data: AtomicUsize,
295 _marker: PhantomData<*mut T>,
296}
297
298unsafe impl<T: ?Sized + Pointable + Send + Sync> Send for Atomic<T> {}
299unsafe impl<T: ?Sized + Pointable + Send + Sync> Sync for Atomic<T> {}
300
301impl<T> Atomic<T> {
302 /// Allocates `value` on the heap and returns a new atomic pointer pointing to it.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// use crossbeam_epoch::Atomic;
308 ///
309 /// let a = Atomic::new(1234);
310 /// # unsafe { drop(a.into_owned()); } // avoid leak
311 /// ```
312 pub fn new(init: T) -> Atomic<T> {
313 Self::init(init)
314 }
315}
316
317impl<T: ?Sized + Pointable> Atomic<T> {
318 /// Allocates `value` on the heap and returns a new atomic pointer pointing to it.
319 ///
320 /// # Examples
321 ///
322 /// ```
323 /// use crossbeam_epoch::Atomic;
324 ///
325 /// let a = Atomic::<i32>::init(1234);
326 /// # unsafe { drop(a.into_owned()); } // avoid leak
327 /// ```
328 pub fn init(init: T::Init) -> Atomic<T> {
329 Self::from(Owned::init(init))
330 }
331
332 /// Returns a new atomic pointer pointing to the tagged pointer `data`.
333 fn from_usize(data: usize) -> Self {
334 Self {
335 data: AtomicUsize::new(data),
336 _marker: PhantomData,
337 }
338 }
339
340 /// Returns a new null atomic pointer.
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use crossbeam_epoch::Atomic;
346 ///
347 /// let a = Atomic::<i32>::null();
348 /// ```
349 #[cfg(not(crossbeam_loom))]
350 pub const fn null() -> Atomic<T> {
351 Self {
352 data: AtomicUsize::new(0),
353 _marker: PhantomData,
354 }
355 }
356 /// Returns a new null atomic pointer.
357 #[cfg(crossbeam_loom)]
358 pub fn null() -> Atomic<T> {
359 Self {
360 data: AtomicUsize::new(0),
361 _marker: PhantomData,
362 }
363 }
364
365 /// Loads a `Shared` from the atomic pointer.
366 ///
367 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
368 /// operation.
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// use crossbeam_epoch::{self as epoch, Atomic};
374 /// use std::sync::atomic::Ordering::SeqCst;
375 ///
376 /// let a = Atomic::new(1234);
377 /// let guard = &epoch::pin();
378 /// let p = a.load(SeqCst, guard);
379 /// # unsafe { drop(a.into_owned()); } // avoid leak
380 /// ```
381 pub fn load<'g>(&self, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
382 unsafe { Shared::from_usize(self.data.load(ord)) }
383 }
384
385 /// Loads a `Shared` from the atomic pointer using a "consume" memory ordering.
386 ///
387 /// This is similar to the "acquire" ordering, except that an ordering is
388 /// only guaranteed with operations that "depend on" the result of the load.
389 /// However consume loads are usually much faster than acquire loads on
390 /// architectures with a weak memory model since they don't require memory
391 /// fence instructions.
392 ///
393 /// The exact definition of "depend on" is a bit vague, but it works as you
394 /// would expect in practice since a lot of software, especially the Linux
395 /// kernel, rely on this behavior.
396 ///
397 /// # Examples
398 ///
399 /// ```
400 /// use crossbeam_epoch::{self as epoch, Atomic};
401 ///
402 /// let a = Atomic::new(1234);
403 /// let guard = &epoch::pin();
404 /// let p = a.load_consume(guard);
405 /// # unsafe { drop(a.into_owned()); } // avoid leak
406 /// ```
407 pub fn load_consume<'g>(&self, _: &'g Guard) -> Shared<'g, T> {
408 unsafe { Shared::from_usize(self.data.load_consume()) }
409 }
410
411 /// Stores a `Shared` or `Owned` pointer into the atomic pointer.
412 ///
413 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
414 /// operation.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use crossbeam_epoch::{Atomic, Owned, Shared};
420 /// use std::sync::atomic::Ordering::SeqCst;
421 ///
422 /// let a = Atomic::new(1234);
423 /// # unsafe { drop(a.load(SeqCst, &crossbeam_epoch::pin()).into_owned()); } // avoid leak
424 /// a.store(Shared::null(), SeqCst);
425 /// a.store(Owned::new(1234), SeqCst);
426 /// # unsafe { drop(a.into_owned()); } // avoid leak
427 /// ```
428 pub fn store<P: Pointer<T>>(&self, new: P, ord: Ordering) {
429 self.data.store(new.into_usize(), ord);
430 }
431
432 /// Stores a `Shared` or `Owned` pointer into the atomic pointer, returning the previous
433 /// `Shared`.
434 ///
435 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
436 /// operation.
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
442 /// use std::sync::atomic::Ordering::SeqCst;
443 ///
444 /// let a = Atomic::new(1234);
445 /// let guard = &epoch::pin();
446 /// let p = a.swap(Shared::null(), SeqCst, guard);
447 /// # unsafe { drop(p.into_owned()); } // avoid leak
448 /// ```
449 pub fn swap<'g, P: Pointer<T>>(&self, new: P, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
450 unsafe { Shared::from_usize(self.data.swap(new.into_usize(), ord)) }
451 }
452
453 /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
454 /// value is the same as `current`. The tag is also taken into account, so two pointers to the
455 /// same object, but with different tags, will not be considered equal.
456 ///
457 /// The return value is a result indicating whether the new pointer was written. On success the
458 /// pointer that was written is returned. On failure the actual current value and `new` are
459 /// returned.
460 ///
461 /// This method takes two `Ordering` arguments to describe the memory
462 /// ordering of this operation. `success` describes the required ordering for the
463 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
464 /// `failure` describes the required ordering for the load operation that takes place when
465 /// the comparison fails. Using `Acquire` as success ordering makes the store part
466 /// of this operation `Relaxed`, and using `Release` makes the successful load
467 /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
468 /// and must be equivalent to or weaker than the success ordering.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
474 /// use std::sync::atomic::Ordering::SeqCst;
475 ///
476 /// let a = Atomic::new(1234);
477 ///
478 /// let guard = &epoch::pin();
479 /// let curr = a.load(SeqCst, guard);
480 /// let res1 = a.compare_exchange(curr, Shared::null(), SeqCst, SeqCst, guard);
481 /// let res2 = a.compare_exchange(curr, Owned::new(5678), SeqCst, SeqCst, guard);
482 /// # unsafe { drop(curr.into_owned()); } // avoid leak
483 /// ```
484 pub fn compare_exchange<'g, P>(
485 &self,
486 current: Shared<'_, T>,
487 new: P,
488 success: Ordering,
489 failure: Ordering,
490 _: &'g Guard,
491 ) -> Result<Shared<'g, T>, CompareExchangeError<'g, T, P>>
492 where
493 P: Pointer<T>,
494 {
495 let new = new.into_usize();
496 self.data
497 .compare_exchange(current.into_usize(), new, success, failure)
498 .map(|_| unsafe { Shared::from_usize(new) })
499 .map_err(|current| unsafe {
500 CompareExchangeError {
501 current: Shared::from_usize(current),
502 new: P::from_usize(new),
503 }
504 })
505 }
506
507 /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
508 /// value is the same as `current`. The tag is also taken into account, so two pointers to the
509 /// same object, but with different tags, will not be considered equal.
510 ///
511 /// Unlike [`compare_exchange`], this method is allowed to spuriously fail even when comparison
512 /// succeeds, which can result in more efficient code on some platforms. The return value is a
513 /// result indicating whether the new pointer was written. On success the pointer that was
514 /// written is returned. On failure the actual current value and `new` are returned.
515 ///
516 /// This method takes two `Ordering` arguments to describe the memory
517 /// ordering of this operation. `success` describes the required ordering for the
518 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
519 /// `failure` describes the required ordering for the load operation that takes place when
520 /// the comparison fails. Using `Acquire` as success ordering makes the store part
521 /// of this operation `Relaxed`, and using `Release` makes the successful load
522 /// `Relaxed`. The failure ordering can only be `SeqCst`, `Acquire` or `Relaxed`
523 /// and must be equivalent to or weaker than the success ordering.
524 ///
525 /// [`compare_exchange`]: Atomic::compare_exchange
526 ///
527 /// # Examples
528 ///
529 /// ```
530 /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
531 /// use std::sync::atomic::Ordering::SeqCst;
532 ///
533 /// let a = Atomic::new(1234);
534 /// let guard = &epoch::pin();
535 ///
536 /// let mut new = Owned::new(5678);
537 /// let mut ptr = a.load(SeqCst, guard);
538 /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak
539 /// loop {
540 /// match a.compare_exchange_weak(ptr, new, SeqCst, SeqCst, guard) {
541 /// Ok(p) => {
542 /// ptr = p;
543 /// break;
544 /// }
545 /// Err(err) => {
546 /// ptr = err.current;
547 /// new = err.new;
548 /// }
549 /// }
550 /// }
551 ///
552 /// let mut curr = a.load(SeqCst, guard);
553 /// loop {
554 /// match a.compare_exchange_weak(curr, Shared::null(), SeqCst, SeqCst, guard) {
555 /// Ok(_) => break,
556 /// Err(err) => curr = err.current,
557 /// }
558 /// }
559 /// # unsafe { drop(curr.into_owned()); } // avoid leak
560 /// ```
561 pub fn compare_exchange_weak<'g, P>(
562 &self,
563 current: Shared<'_, T>,
564 new: P,
565 success: Ordering,
566 failure: Ordering,
567 _: &'g Guard,
568 ) -> Result<Shared<'g, T>, CompareExchangeError<'g, T, P>>
569 where
570 P: Pointer<T>,
571 {
572 let new = new.into_usize();
573 self.data
574 .compare_exchange_weak(current.into_usize(), new, success, failure)
575 .map(|_| unsafe { Shared::from_usize(new) })
576 .map_err(|current| unsafe {
577 CompareExchangeError {
578 current: Shared::from_usize(current),
579 new: P::from_usize(new),
580 }
581 })
582 }
583
584 /// Fetches the pointer, and then applies a function to it that returns a new value.
585 /// Returns a `Result` of `Ok(previous_value)` if the function returned `Some`, else `Err(_)`.
586 ///
587 /// Note that the given function may be called multiple times if the value has been changed by
588 /// other threads in the meantime, as long as the function returns `Some(_)`, but the function
589 /// will have been applied only once to the stored value.
590 ///
591 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
592 /// ordering of this operation. The first describes the required ordering for
593 /// when the operation finally succeeds while the second describes the
594 /// required ordering for loads. These correspond to the success and failure
595 /// orderings of [`Atomic::compare_exchange`] respectively.
596 ///
597 /// Using [`Acquire`] as success ordering makes the store part of this
598 /// operation [`Relaxed`], and using [`Release`] makes the final successful
599 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
600 /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
601 /// success ordering.
602 ///
603 /// [`Relaxed`]: Ordering::Relaxed
604 /// [`Acquire`]: Ordering::Acquire
605 /// [`Release`]: Ordering::Release
606 /// [`SeqCst`]: Ordering::SeqCst
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use crossbeam_epoch::{self as epoch, Atomic};
612 /// use std::sync::atomic::Ordering::SeqCst;
613 ///
614 /// let a = Atomic::new(1234);
615 /// let guard = &epoch::pin();
616 ///
617 /// let res1 = a.fetch_update(SeqCst, SeqCst, guard, |x| Some(x.with_tag(1)));
618 /// assert!(res1.is_ok());
619 ///
620 /// let res2 = a.fetch_update(SeqCst, SeqCst, guard, |x| None);
621 /// assert!(res2.is_err());
622 /// # unsafe { drop(a.into_owned()); } // avoid leak
623 /// ```
624 pub fn fetch_update<'g, F>(
625 &self,
626 set_order: Ordering,
627 fail_order: Ordering,
628 guard: &'g Guard,
629 mut func: F,
630 ) -> Result<Shared<'g, T>, Shared<'g, T>>
631 where
632 F: FnMut(Shared<'g, T>) -> Option<Shared<'g, T>>,
633 {
634 let mut prev = self.load(fail_order, guard);
635 while let Some(next) = func(prev) {
636 match self.compare_exchange_weak(prev, next, set_order, fail_order, guard) {
637 Ok(_result) => return Ok(prev),
638 Err(next_prev) => prev = next_prev.current,
639 }
640 }
641 Err(prev)
642 }
643
644 /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
645 /// value is the same as `current`. The tag is also taken into account, so two pointers to the
646 /// same object, but with different tags, will not be considered equal.
647 ///
648 /// The return value is a result indicating whether the new pointer was written. On success the
649 /// pointer that was written is returned. On failure the actual current value and `new` are
650 /// returned.
651 ///
652 /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory
653 /// ordering of this operation.
654 ///
655 /// # Migrating to `compare_exchange`
656 ///
657 /// `compare_and_set` is equivalent to `compare_exchange` with the following mapping for
658 /// memory orderings:
659 ///
660 /// Original | Success | Failure
661 /// -------- | ------- | -------
662 /// Relaxed | Relaxed | Relaxed
663 /// Acquire | Acquire | Acquire
664 /// Release | Release | Relaxed
665 /// AcqRel | AcqRel | Acquire
666 /// SeqCst | SeqCst | SeqCst
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// # #![allow(deprecated)]
672 /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
673 /// use std::sync::atomic::Ordering::SeqCst;
674 ///
675 /// let a = Atomic::new(1234);
676 ///
677 /// let guard = &epoch::pin();
678 /// let curr = a.load(SeqCst, guard);
679 /// let res1 = a.compare_and_set(curr, Shared::null(), SeqCst, guard);
680 /// let res2 = a.compare_and_set(curr, Owned::new(5678), SeqCst, guard);
681 /// # unsafe { drop(curr.into_owned()); } // avoid leak
682 /// ```
683 // TODO: remove in the next major version.
684 #[allow(deprecated)]
685 #[deprecated(note = "Use `compare_exchange` instead")]
686 pub fn compare_and_set<'g, O, P>(
687 &self,
688 current: Shared<'_, T>,
689 new: P,
690 ord: O,
691 guard: &'g Guard,
692 ) -> Result<Shared<'g, T>, CompareAndSetError<'g, T, P>>
693 where
694 O: CompareAndSetOrdering,
695 P: Pointer<T>,
696 {
697 self.compare_exchange(current, new, ord.success(), ord.failure(), guard)
698 }
699
700 /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current
701 /// value is the same as `current`. The tag is also taken into account, so two pointers to the
702 /// same object, but with different tags, will not be considered equal.
703 ///
704 /// Unlike [`compare_and_set`], this method is allowed to spuriously fail even when comparison
705 /// succeeds, which can result in more efficient code on some platforms. The return value is a
706 /// result indicating whether the new pointer was written. On success the pointer that was
707 /// written is returned. On failure the actual current value and `new` are returned.
708 ///
709 /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory
710 /// ordering of this operation.
711 ///
712 /// [`compare_and_set`]: Atomic::compare_and_set
713 ///
714 /// # Migrating to `compare_exchange_weak`
715 ///
716 /// `compare_and_set_weak` is equivalent to `compare_exchange_weak` with the following mapping for
717 /// memory orderings:
718 ///
719 /// Original | Success | Failure
720 /// -------- | ------- | -------
721 /// Relaxed | Relaxed | Relaxed
722 /// Acquire | Acquire | Acquire
723 /// Release | Release | Relaxed
724 /// AcqRel | AcqRel | Acquire
725 /// SeqCst | SeqCst | SeqCst
726 ///
727 /// # Examples
728 ///
729 /// ```
730 /// # #![allow(deprecated)]
731 /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared};
732 /// use std::sync::atomic::Ordering::SeqCst;
733 ///
734 /// let a = Atomic::new(1234);
735 /// let guard = &epoch::pin();
736 ///
737 /// let mut new = Owned::new(5678);
738 /// let mut ptr = a.load(SeqCst, guard);
739 /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak
740 /// loop {
741 /// match a.compare_and_set_weak(ptr, new, SeqCst, guard) {
742 /// Ok(p) => {
743 /// ptr = p;
744 /// break;
745 /// }
746 /// Err(err) => {
747 /// ptr = err.current;
748 /// new = err.new;
749 /// }
750 /// }
751 /// }
752 ///
753 /// let mut curr = a.load(SeqCst, guard);
754 /// loop {
755 /// match a.compare_and_set_weak(curr, Shared::null(), SeqCst, guard) {
756 /// Ok(_) => break,
757 /// Err(err) => curr = err.current,
758 /// }
759 /// }
760 /// # unsafe { drop(curr.into_owned()); } // avoid leak
761 /// ```
762 // TODO: remove in the next major version.
763 #[allow(deprecated)]
764 #[deprecated(note = "Use `compare_exchange_weak` instead")]
765 pub fn compare_and_set_weak<'g, O, P>(
766 &self,
767 current: Shared<'_, T>,
768 new: P,
769 ord: O,
770 guard: &'g Guard,
771 ) -> Result<Shared<'g, T>, CompareAndSetError<'g, T, P>>
772 where
773 O: CompareAndSetOrdering,
774 P: Pointer<T>,
775 {
776 self.compare_exchange_weak(current, new, ord.success(), ord.failure(), guard)
777 }
778
779 /// Bitwise "and" with the current tag.
780 ///
781 /// Performs a bitwise "and" operation on the current tag and the argument `val`, and sets the
782 /// new tag to the result. Returns the previous pointer.
783 ///
784 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
785 /// operation.
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
791 /// use std::sync::atomic::Ordering::SeqCst;
792 ///
793 /// let a = Atomic::<i32>::from(Shared::null().with_tag(3));
794 /// let guard = &epoch::pin();
795 /// assert_eq!(a.fetch_and(2, SeqCst, guard).tag(), 3);
796 /// assert_eq!(a.load(SeqCst, guard).tag(), 2);
797 /// ```
798 pub fn fetch_and<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
799 unsafe { Shared::from_usize(self.data.fetch_and(val | !low_bits::<T>(), ord)) }
800 }
801
802 /// Bitwise "or" with the current tag.
803 ///
804 /// Performs a bitwise "or" operation on the current tag and the argument `val`, and sets the
805 /// new tag to the result. Returns the previous pointer.
806 ///
807 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
808 /// operation.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
814 /// use std::sync::atomic::Ordering::SeqCst;
815 ///
816 /// let a = Atomic::<i32>::from(Shared::null().with_tag(1));
817 /// let guard = &epoch::pin();
818 /// assert_eq!(a.fetch_or(2, SeqCst, guard).tag(), 1);
819 /// assert_eq!(a.load(SeqCst, guard).tag(), 3);
820 /// ```
821 pub fn fetch_or<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
822 unsafe { Shared::from_usize(self.data.fetch_or(val & low_bits::<T>(), ord)) }
823 }
824
825 /// Bitwise "xor" with the current tag.
826 ///
827 /// Performs a bitwise "xor" operation on the current tag and the argument `val`, and sets the
828 /// new tag to the result. Returns the previous pointer.
829 ///
830 /// This method takes an [`Ordering`] argument which describes the memory ordering of this
831 /// operation.
832 ///
833 /// # Examples
834 ///
835 /// ```
836 /// use crossbeam_epoch::{self as epoch, Atomic, Shared};
837 /// use std::sync::atomic::Ordering::SeqCst;
838 ///
839 /// let a = Atomic::<i32>::from(Shared::null().with_tag(1));
840 /// let guard = &epoch::pin();
841 /// assert_eq!(a.fetch_xor(3, SeqCst, guard).tag(), 1);
842 /// assert_eq!(a.load(SeqCst, guard).tag(), 2);
843 /// ```
844 pub fn fetch_xor<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> {
845 unsafe { Shared::from_usize(self.data.fetch_xor(val & low_bits::<T>(), ord)) }
846 }
847
848 /// Takes ownership of the pointee.
849 ///
850 /// This consumes the atomic and converts it into [`Owned`]. As [`Atomic`] doesn't have a
851 /// destructor and doesn't drop the pointee while [`Owned`] does, this is suitable for
852 /// destructors of data structures.
853 ///
854 /// # Panics
855 ///
856 /// Panics if this pointer is null, but only in debug mode.
857 ///
858 /// # Safety
859 ///
860 /// This method may be called only if the pointer is valid and nobody else is holding a
861 /// reference to the same object.
862 ///
863 /// # Examples
864 ///
865 /// ```rust
866 /// # use std::mem;
867 /// # use crossbeam_epoch::Atomic;
868 /// struct DataStructure {
869 /// ptr: Atomic<usize>,
870 /// }
871 ///
872 /// impl Drop for DataStructure {
873 /// fn drop(&mut self) {
874 /// // By now the DataStructure lives only in our thread and we are sure we don't hold
875 /// // any Shared or & to it ourselves.
876 /// unsafe {
877 /// drop(mem::replace(&mut self.ptr, Atomic::null()).into_owned());
878 /// }
879 /// }
880 /// }
881 /// ```
882 pub unsafe fn into_owned(self) -> Owned<T> {
883 Owned::from_usize(self.data.into_inner())
884 }
885
886 /// Takes ownership of the pointee if it is non-null.
887 ///
888 /// This consumes the atomic and converts it into [`Owned`]. As [`Atomic`] doesn't have a
889 /// destructor and doesn't drop the pointee while [`Owned`] does, this is suitable for
890 /// destructors of data structures.
891 ///
892 /// # Safety
893 ///
894 /// This method may be called only if the pointer is valid and nobody else is holding a
895 /// reference to the same object, or the pointer is null.
896 ///
897 /// # Examples
898 ///
899 /// ```rust
900 /// # use std::mem;
901 /// # use crossbeam_epoch::Atomic;
902 /// struct DataStructure {
903 /// ptr: Atomic<usize>,
904 /// }
905 ///
906 /// impl Drop for DataStructure {
907 /// fn drop(&mut self) {
908 /// // By now the DataStructure lives only in our thread and we are sure we don't hold
909 /// // any Shared or & to it ourselves, but it may be null, so we have to be careful.
910 /// let old = mem::replace(&mut self.ptr, Atomic::null());
911 /// unsafe {
912 /// if let Some(x) = old.try_into_owned() {
913 /// drop(x)
914 /// }
915 /// }
916 /// }
917 /// }
918 /// ```
919 pub unsafe fn try_into_owned(self) -> Option<Owned<T>> {
920 let data = self.data.into_inner();
921 if decompose_tag::<T>(data).0 == 0 {
922 None
923 } else {
924 Some(Owned::from_usize(data))
925 }
926 }
927}
928
929impl<T: ?Sized + Pointable> fmt::Debug for Atomic<T> {
930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931 let data = self.data.load(Ordering::SeqCst);
932 let (raw, tag) = decompose_tag::<T>(data);
933
934 f.debug_struct("Atomic")
935 .field("raw", &raw)
936 .field("tag", &tag)
937 .finish()
938 }
939}
940
941impl<T: ?Sized + Pointable> fmt::Pointer for Atomic<T> {
942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
943 let data = self.data.load(Ordering::SeqCst);
944 let (raw, _) = decompose_tag::<T>(data);
945 fmt::Pointer::fmt(&(raw as *const ()), f)
946 }
947}
948
949impl<T: ?Sized + Pointable> Clone for Atomic<T> {
950 /// Returns a copy of the atomic value.
951 ///
952 /// Note that a `Relaxed` load is used here. If you need synchronization, use it with other
953 /// atomics or fences.
954 fn clone(&self) -> Self {
955 let data = self.data.load(Ordering::Relaxed);
956 Atomic::from_usize(data)
957 }
958}
959
960impl<T: ?Sized + Pointable> Default for Atomic<T> {
961 fn default() -> Self {
962 Atomic::null()
963 }
964}
965
966impl<T: ?Sized + Pointable> From<Owned<T>> for Atomic<T> {
967 /// Returns a new atomic pointer pointing to `owned`.
968 ///
969 /// # Examples
970 ///
971 /// ```
972 /// use crossbeam_epoch::{Atomic, Owned};
973 ///
974 /// let a = Atomic::<i32>::from(Owned::new(1234));
975 /// # unsafe { drop(a.into_owned()); } // avoid leak
976 /// ```
977 fn from(owned: Owned<T>) -> Self {
978 let data = owned.data;
979 mem::forget(owned);
980 Self::from_usize(data)
981 }
982}
983
984impl<T> From<Box<T>> for Atomic<T> {
985 fn from(b: Box<T>) -> Self {
986 Self::from(Owned::from(b))
987 }
988}
989
990impl<T> From<T> for Atomic<T> {
991 fn from(t: T) -> Self {
992 Self::new(t)
993 }
994}
995
996impl<'g, T: ?Sized + Pointable> From<Shared<'g, T>> for Atomic<T> {
997 /// Returns a new atomic pointer pointing to `ptr`.
998 ///
999 /// # Examples
1000 ///
1001 /// ```
1002 /// use crossbeam_epoch::{Atomic, Shared};
1003 ///
1004 /// let a = Atomic::<i32>::from(Shared::<i32>::null());
1005 /// ```
1006 fn from(ptr: Shared<'g, T>) -> Self {
1007 Self::from_usize(ptr.data)
1008 }
1009}
1010
1011impl<T> From<*const T> for Atomic<T> {
1012 /// Returns a new atomic pointer pointing to `raw`.
1013 ///
1014 /// # Examples
1015 ///
1016 /// ```
1017 /// use std::ptr;
1018 /// use crossbeam_epoch::Atomic;
1019 ///
1020 /// let a = Atomic::<i32>::from(ptr::null::<i32>());
1021 /// ```
1022 fn from(raw: *const T) -> Self {
1023 Self::from_usize(raw as usize)
1024 }
1025}
1026
1027/// A trait for either `Owned` or `Shared` pointers.
1028pub trait Pointer<T: ?Sized + Pointable> {
1029 /// Returns the machine representation of the pointer.
1030 fn into_usize(self) -> usize;
1031
1032 /// Returns a new pointer pointing to the tagged pointer `data`.
1033 ///
1034 /// # Safety
1035 ///
1036 /// The given `data` should have been created by `Pointer::into_usize()`, and one `data` should
1037 /// not be converted back by `Pointer::from_usize()` multiple times.
1038 unsafe fn from_usize(data: usize) -> Self;
1039}
1040
1041/// An owned heap-allocated object.
1042///
1043/// This type is very similar to `Box<T>`.
1044///
1045/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
1046/// least significant bits of the address.
1047pub struct Owned<T: ?Sized + Pointable> {
1048 data: usize,
1049 _marker: PhantomData<Box<T>>,
1050}
1051
1052impl<T: ?Sized + Pointable> Pointer<T> for Owned<T> {
1053 #[inline]
1054 fn into_usize(self) -> usize {
1055 let data = self.data;
1056 mem::forget(self);
1057 data
1058 }
1059
1060 /// Returns a new pointer pointing to the tagged pointer `data`.
1061 ///
1062 /// # Panics
1063 ///
1064 /// Panics if the data is zero in debug mode.
1065 #[inline]
1066 unsafe fn from_usize(data: usize) -> Self {
1067 debug_assert!(data != 0, "converting zero into `Owned`");
1068 Owned {
1069 data,
1070 _marker: PhantomData,
1071 }
1072 }
1073}
1074
1075impl<T> Owned<T> {
1076 /// Returns a new owned pointer pointing to `raw`.
1077 ///
1078 /// This function is unsafe because improper use may lead to memory problems. Argument `raw`
1079 /// must be a valid pointer. Also, a double-free may occur if the function is called twice on
1080 /// the same raw pointer.
1081 ///
1082 /// # Panics
1083 ///
1084 /// Panics if `raw` is not properly aligned.
1085 ///
1086 /// # Safety
1087 ///
1088 /// The given `raw` should have been derived from `Owned`, and one `raw` should not be converted
1089 /// back by `Owned::from_raw()` multiple times.
1090 ///
1091 /// # Examples
1092 ///
1093 /// ```
1094 /// use crossbeam_epoch::Owned;
1095 ///
1096 /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
1097 /// ```
1098 pub unsafe fn from_raw(raw: *mut T) -> Owned<T> {
1099 let raw = raw as usize;
1100 ensure_aligned::<T>(raw);
1101 Self::from_usize(raw)
1102 }
1103
1104 /// Converts the owned pointer into a `Box`.
1105 ///
1106 /// # Examples
1107 ///
1108 /// ```
1109 /// use crossbeam_epoch::Owned;
1110 ///
1111 /// let o = Owned::new(1234);
1112 /// let b: Box<i32> = o.into_box();
1113 /// assert_eq!(*b, 1234);
1114 /// ```
1115 pub fn into_box(self) -> Box<T> {
1116 let (raw, _) = decompose_tag::<T>(self.data);
1117 mem::forget(self);
1118 unsafe { Box::from_raw(raw as *mut _) }
1119 }
1120
1121 /// Allocates `value` on the heap and returns a new owned pointer pointing to it.
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use crossbeam_epoch::Owned;
1127 ///
1128 /// let o = Owned::new(1234);
1129 /// ```
1130 pub fn new(init: T) -> Owned<T> {
1131 Self::init(init)
1132 }
1133}
1134
1135impl<T: ?Sized + Pointable> Owned<T> {
1136 /// Allocates `value` on the heap and returns a new owned pointer pointing to it.
1137 ///
1138 /// # Examples
1139 ///
1140 /// ```
1141 /// use crossbeam_epoch::Owned;
1142 ///
1143 /// let o = Owned::<i32>::init(1234);
1144 /// ```
1145 pub fn init(init: T::Init) -> Owned<T> {
1146 unsafe { Self::from_usize(T::init(init)) }
1147 }
1148
1149 /// Converts the owned pointer into a [`Shared`].
1150 ///
1151 /// # Examples
1152 ///
1153 /// ```
1154 /// use crossbeam_epoch::{self as epoch, Owned};
1155 ///
1156 /// let o = Owned::new(1234);
1157 /// let guard = &epoch::pin();
1158 /// let p = o.into_shared(guard);
1159 /// # unsafe { drop(p.into_owned()); } // avoid leak
1160 /// ```
1161 #[allow(clippy::needless_lifetimes)]
1162 pub fn into_shared<'g>(self, _: &'g Guard) -> Shared<'g, T> {
1163 unsafe { Shared::from_usize(self.into_usize()) }
1164 }
1165
1166 /// Returns the tag stored within the pointer.
1167 ///
1168 /// # Examples
1169 ///
1170 /// ```
1171 /// use crossbeam_epoch::Owned;
1172 ///
1173 /// assert_eq!(Owned::new(1234).tag(), 0);
1174 /// ```
1175 pub fn tag(&self) -> usize {
1176 let (_, tag) = decompose_tag::<T>(self.data);
1177 tag
1178 }
1179
1180 /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the
1181 /// unused bits of the pointer to `T`.
1182 ///
1183 /// # Examples
1184 ///
1185 /// ```
1186 /// use crossbeam_epoch::Owned;
1187 ///
1188 /// let o = Owned::new(0u64);
1189 /// assert_eq!(o.tag(), 0);
1190 /// let o = o.with_tag(2);
1191 /// assert_eq!(o.tag(), 2);
1192 /// ```
1193 pub fn with_tag(self, tag: usize) -> Owned<T> {
1194 let data = self.into_usize();
1195 unsafe { Self::from_usize(compose_tag::<T>(data, tag)) }
1196 }
1197}
1198
1199impl<T: ?Sized + Pointable> Drop for Owned<T> {
1200 fn drop(&mut self) {
1201 let (raw, _) = decompose_tag::<T>(self.data);
1202 unsafe {
1203 T::drop(raw);
1204 }
1205 }
1206}
1207
1208impl<T: ?Sized + Pointable> fmt::Debug for Owned<T> {
1209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1210 let (raw, tag) = decompose_tag::<T>(self.data);
1211
1212 f.debug_struct("Owned")
1213 .field("raw", &raw)
1214 .field("tag", &tag)
1215 .finish()
1216 }
1217}
1218
1219impl<T: Clone> Clone for Owned<T> {
1220 fn clone(&self) -> Self {
1221 Owned::new((**self).clone()).with_tag(self.tag())
1222 }
1223}
1224
1225impl<T: ?Sized + Pointable> Deref for Owned<T> {
1226 type Target = T;
1227
1228 fn deref(&self) -> &T {
1229 let (raw, _) = decompose_tag::<T>(self.data);
1230 unsafe { T::deref(raw) }
1231 }
1232}
1233
1234impl<T: ?Sized + Pointable> DerefMut for Owned<T> {
1235 fn deref_mut(&mut self) -> &mut T {
1236 let (raw, _) = decompose_tag::<T>(self.data);
1237 unsafe { T::deref_mut(raw) }
1238 }
1239}
1240
1241impl<T> From<T> for Owned<T> {
1242 fn from(t: T) -> Self {
1243 Owned::new(t)
1244 }
1245}
1246
1247impl<T> From<Box<T>> for Owned<T> {
1248 /// Returns a new owned pointer pointing to `b`.
1249 ///
1250 /// # Panics
1251 ///
1252 /// Panics if the pointer (the `Box`) is not properly aligned.
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// use crossbeam_epoch::Owned;
1258 ///
1259 /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) };
1260 /// ```
1261 fn from(b: Box<T>) -> Self {
1262 unsafe { Self::from_raw(Box::into_raw(b)) }
1263 }
1264}
1265
1266impl<T: ?Sized + Pointable> Borrow<T> for Owned<T> {
1267 fn borrow(&self) -> &T {
1268 self.deref()
1269 }
1270}
1271
1272impl<T: ?Sized + Pointable> BorrowMut<T> for Owned<T> {
1273 fn borrow_mut(&mut self) -> &mut T {
1274 self.deref_mut()
1275 }
1276}
1277
1278impl<T: ?Sized + Pointable> AsRef<T> for Owned<T> {
1279 fn as_ref(&self) -> &T {
1280 self.deref()
1281 }
1282}
1283
1284impl<T: ?Sized + Pointable> AsMut<T> for Owned<T> {
1285 fn as_mut(&mut self) -> &mut T {
1286 self.deref_mut()
1287 }
1288}
1289
1290/// A pointer to an object protected by the epoch GC.
1291///
1292/// The pointer is valid for use only during the lifetime `'g`.
1293///
1294/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused
1295/// least significant bits of the address.
1296pub struct Shared<'g, T: 'g + ?Sized + Pointable> {
1297 data: usize,
1298 _marker: PhantomData<(&'g (), *const T)>,
1299}
1300
1301impl<T: ?Sized + Pointable> Clone for Shared<'_, T> {
1302 fn clone(&self) -> Self {
1303 *self
1304 }
1305}
1306
1307impl<T: ?Sized + Pointable> Copy for Shared<'_, T> {}
1308
1309impl<T: ?Sized + Pointable> Pointer<T> for Shared<'_, T> {
1310 #[inline]
1311 fn into_usize(self) -> usize {
1312 self.data
1313 }
1314
1315 #[inline]
1316 unsafe fn from_usize(data: usize) -> Self {
1317 Shared {
1318 data,
1319 _marker: PhantomData,
1320 }
1321 }
1322}
1323
1324impl<'g, T> Shared<'g, T> {
1325 /// Converts the pointer to a raw pointer (without the tag).
1326 ///
1327 /// # Examples
1328 ///
1329 /// ```
1330 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1331 /// use std::sync::atomic::Ordering::SeqCst;
1332 ///
1333 /// let o = Owned::new(1234);
1334 /// let raw = &*o as *const _;
1335 /// let a = Atomic::from(o);
1336 ///
1337 /// let guard = &epoch::pin();
1338 /// let p = a.load(SeqCst, guard);
1339 /// assert_eq!(p.as_raw(), raw);
1340 /// # unsafe { drop(a.into_owned()); } // avoid leak
1341 /// ```
1342 pub fn as_raw(&self) -> *const T {
1343 let (raw, _) = decompose_tag::<T>(self.data);
1344 raw as *const _
1345 }
1346}
1347
1348impl<'g, T: ?Sized + Pointable> Shared<'g, T> {
1349 /// Returns a new null pointer.
1350 ///
1351 /// # Examples
1352 ///
1353 /// ```
1354 /// use crossbeam_epoch::Shared;
1355 ///
1356 /// let p = Shared::<i32>::null();
1357 /// assert!(p.is_null());
1358 /// ```
1359 pub fn null() -> Shared<'g, T> {
1360 Shared {
1361 data: 0,
1362 _marker: PhantomData,
1363 }
1364 }
1365
1366 /// Returns `true` if the pointer is null.
1367 ///
1368 /// # Examples
1369 ///
1370 /// ```
1371 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1372 /// use std::sync::atomic::Ordering::SeqCst;
1373 ///
1374 /// let a = Atomic::null();
1375 /// let guard = &epoch::pin();
1376 /// assert!(a.load(SeqCst, guard).is_null());
1377 /// a.store(Owned::new(1234), SeqCst);
1378 /// assert!(!a.load(SeqCst, guard).is_null());
1379 /// # unsafe { drop(a.into_owned()); } // avoid leak
1380 /// ```
1381 pub fn is_null(&self) -> bool {
1382 let (raw, _) = decompose_tag::<T>(self.data);
1383 raw == 0
1384 }
1385
1386 /// Dereferences the pointer.
1387 ///
1388 /// Returns a reference to the pointee that is valid during the lifetime `'g`.
1389 ///
1390 /// # Safety
1391 ///
1392 /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory.
1393 ///
1394 /// Another concern is the possibility of data races due to lack of proper synchronization.
1395 /// For example, consider the following scenario:
1396 ///
1397 /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)`
1398 /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()`
1399 ///
1400 /// The problem is that relaxed orderings don't synchronize initialization of the object with
1401 /// the read from the second thread. This is a data race. A possible solution would be to use
1402 /// `Release` and `Acquire` orderings.
1403 ///
1404 /// # Examples
1405 ///
1406 /// ```
1407 /// use crossbeam_epoch::{self as epoch, Atomic};
1408 /// use std::sync::atomic::Ordering::SeqCst;
1409 ///
1410 /// let a = Atomic::new(1234);
1411 /// let guard = &epoch::pin();
1412 /// let p = a.load(SeqCst, guard);
1413 /// unsafe {
1414 /// assert_eq!(p.deref(), &1234);
1415 /// }
1416 /// # unsafe { drop(a.into_owned()); } // avoid leak
1417 /// ```
1418 pub unsafe fn deref(&self) -> &'g T {
1419 let (raw, _) = decompose_tag::<T>(self.data);
1420 T::deref(raw)
1421 }
1422
1423 /// Dereferences the pointer.
1424 ///
1425 /// Returns a mutable reference to the pointee that is valid during the lifetime `'g`.
1426 ///
1427 /// # Safety
1428 ///
1429 /// * There is no guarantee that there are no more threads attempting to read/write from/to the
1430 /// actual object at the same time.
1431 ///
1432 /// The user must know that there are no concurrent accesses towards the object itself.
1433 ///
1434 /// * Other than the above, all safety concerns of `deref()` applies here.
1435 ///
1436 /// # Examples
1437 ///
1438 /// ```
1439 /// use crossbeam_epoch::{self as epoch, Atomic};
1440 /// use std::sync::atomic::Ordering::SeqCst;
1441 ///
1442 /// let a = Atomic::new(vec![1, 2, 3, 4]);
1443 /// let guard = &epoch::pin();
1444 ///
1445 /// let mut p = a.load(SeqCst, guard);
1446 /// unsafe {
1447 /// assert!(!p.is_null());
1448 /// let b = p.deref_mut();
1449 /// assert_eq!(b, &vec![1, 2, 3, 4]);
1450 /// b.push(5);
1451 /// assert_eq!(b, &vec![1, 2, 3, 4, 5]);
1452 /// }
1453 ///
1454 /// let p = a.load(SeqCst, guard);
1455 /// unsafe {
1456 /// assert_eq!(p.deref(), &vec![1, 2, 3, 4, 5]);
1457 /// }
1458 /// # unsafe { drop(a.into_owned()); } // avoid leak
1459 /// ```
1460 pub unsafe fn deref_mut(&mut self) -> &'g mut T {
1461 let (raw, _) = decompose_tag::<T>(self.data);
1462 T::deref_mut(raw)
1463 }
1464
1465 /// Converts the pointer to a reference.
1466 ///
1467 /// Returns `None` if the pointer is null, or else a reference to the object wrapped in `Some`.
1468 ///
1469 /// # Safety
1470 ///
1471 /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory.
1472 ///
1473 /// Another concern is the possibility of data races due to lack of proper synchronization.
1474 /// For example, consider the following scenario:
1475 ///
1476 /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)`
1477 /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()`
1478 ///
1479 /// The problem is that relaxed orderings don't synchronize initialization of the object with
1480 /// the read from the second thread. This is a data race. A possible solution would be to use
1481 /// `Release` and `Acquire` orderings.
1482 ///
1483 /// # Examples
1484 ///
1485 /// ```
1486 /// use crossbeam_epoch::{self as epoch, Atomic};
1487 /// use std::sync::atomic::Ordering::SeqCst;
1488 ///
1489 /// let a = Atomic::new(1234);
1490 /// let guard = &epoch::pin();
1491 /// let p = a.load(SeqCst, guard);
1492 /// unsafe {
1493 /// assert_eq!(p.as_ref(), Some(&1234));
1494 /// }
1495 /// # unsafe { drop(a.into_owned()); } // avoid leak
1496 /// ```
1497 pub unsafe fn as_ref(&self) -> Option<&'g T> {
1498 let (raw, _) = decompose_tag::<T>(self.data);
1499 if raw == 0 {
1500 None
1501 } else {
1502 Some(T::deref(raw))
1503 }
1504 }
1505
1506 /// Takes ownership of the pointee.
1507 ///
1508 /// # Panics
1509 ///
1510 /// Panics if this pointer is null, but only in debug mode.
1511 ///
1512 /// # Safety
1513 ///
1514 /// This method may be called only if the pointer is valid and nobody else is holding a
1515 /// reference to the same object.
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// use crossbeam_epoch::{self as epoch, Atomic};
1521 /// use std::sync::atomic::Ordering::SeqCst;
1522 ///
1523 /// let a = Atomic::new(1234);
1524 /// unsafe {
1525 /// let guard = &epoch::unprotected();
1526 /// let p = a.load(SeqCst, guard);
1527 /// drop(p.into_owned());
1528 /// }
1529 /// ```
1530 pub unsafe fn into_owned(self) -> Owned<T> {
1531 debug_assert!(!self.is_null(), "converting a null `Shared` into `Owned`");
1532 Owned::from_usize(self.data)
1533 }
1534
1535 /// Takes ownership of the pointee if it is not null.
1536 ///
1537 /// # Safety
1538 ///
1539 /// This method may be called only if the pointer is valid and nobody else is holding a
1540 /// reference to the same object, or if the pointer is null.
1541 ///
1542 /// # Examples
1543 ///
1544 /// ```
1545 /// use crossbeam_epoch::{self as epoch, Atomic};
1546 /// use std::sync::atomic::Ordering::SeqCst;
1547 ///
1548 /// let a = Atomic::new(1234);
1549 /// unsafe {
1550 /// let guard = &epoch::unprotected();
1551 /// let p = a.load(SeqCst, guard);
1552 /// if let Some(x) = p.try_into_owned() {
1553 /// drop(x);
1554 /// }
1555 /// }
1556 /// ```
1557 pub unsafe fn try_into_owned(self) -> Option<Owned<T>> {
1558 if self.is_null() {
1559 None
1560 } else {
1561 Some(Owned::from_usize(self.data))
1562 }
1563 }
1564
1565 /// Returns the tag stored within the pointer.
1566 ///
1567 /// # Examples
1568 ///
1569 /// ```
1570 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
1571 /// use std::sync::atomic::Ordering::SeqCst;
1572 ///
1573 /// let a = Atomic::<u64>::from(Owned::new(0u64).with_tag(2));
1574 /// let guard = &epoch::pin();
1575 /// let p = a.load(SeqCst, guard);
1576 /// assert_eq!(p.tag(), 2);
1577 /// # unsafe { drop(a.into_owned()); } // avoid leak
1578 /// ```
1579 pub fn tag(&self) -> usize {
1580 let (_, tag) = decompose_tag::<T>(self.data);
1581 tag
1582 }
1583
1584 /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the
1585 /// unused bits of the pointer to `T`.
1586 ///
1587 /// # Examples
1588 ///
1589 /// ```
1590 /// use crossbeam_epoch::{self as epoch, Atomic};
1591 /// use std::sync::atomic::Ordering::SeqCst;
1592 ///
1593 /// let a = Atomic::new(0u64);
1594 /// let guard = &epoch::pin();
1595 /// let p1 = a.load(SeqCst, guard);
1596 /// let p2 = p1.with_tag(2);
1597 ///
1598 /// assert_eq!(p1.tag(), 0);
1599 /// assert_eq!(p2.tag(), 2);
1600 /// assert_eq!(p1.as_raw(), p2.as_raw());
1601 /// # unsafe { drop(a.into_owned()); } // avoid leak
1602 /// ```
1603 pub fn with_tag(&self, tag: usize) -> Shared<'g, T> {
1604 unsafe { Self::from_usize(compose_tag::<T>(self.data, tag)) }
1605 }
1606}
1607
1608impl<T> From<*const T> for Shared<'_, T> {
1609 /// Returns a new pointer pointing to `raw`.
1610 ///
1611 /// # Panics
1612 ///
1613 /// Panics if `raw` is not properly aligned.
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```
1618 /// use crossbeam_epoch::Shared;
1619 ///
1620 /// let p = Shared::from(Box::into_raw(Box::new(1234)) as *const _);
1621 /// assert!(!p.is_null());
1622 /// # unsafe { drop(p.into_owned()); } // avoid leak
1623 /// ```
1624 fn from(raw: *const T) -> Self {
1625 let raw = raw as usize;
1626 ensure_aligned::<T>(raw);
1627 unsafe { Self::from_usize(raw) }
1628 }
1629}
1630
1631impl<'g, T: ?Sized + Pointable> PartialEq<Shared<'g, T>> for Shared<'g, T> {
1632 fn eq(&self, other: &Self) -> bool {
1633 self.data == other.data
1634 }
1635}
1636
1637impl<T: ?Sized + Pointable> Eq for Shared<'_, T> {}
1638
1639impl<'g, T: ?Sized + Pointable> PartialOrd<Shared<'g, T>> for Shared<'g, T> {
1640 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1641 self.data.partial_cmp(&other.data)
1642 }
1643}
1644
1645impl<T: ?Sized + Pointable> Ord for Shared<'_, T> {
1646 fn cmp(&self, other: &Self) -> cmp::Ordering {
1647 self.data.cmp(&other.data)
1648 }
1649}
1650
1651impl<T: ?Sized + Pointable> fmt::Debug for Shared<'_, T> {
1652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1653 let (raw, tag) = decompose_tag::<T>(self.data);
1654
1655 f.debug_struct("Shared")
1656 .field("raw", &raw)
1657 .field("tag", &tag)
1658 .finish()
1659 }
1660}
1661
1662impl<T: ?Sized + Pointable> fmt::Pointer for Shared<'_, T> {
1663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1664 let (raw, _) = decompose_tag::<T>(self.data);
1665 fmt::Pointer::fmt(&(raw as *const ()), f)
1666 }
1667}
1668
1669impl<T: ?Sized + Pointable> Default for Shared<'_, T> {
1670 fn default() -> Self {
1671 Shared::null()
1672 }
1673}
1674
1675#[cfg(all(test, not(crossbeam_loom)))]
1676mod tests {
1677 use super::{Atomic, Owned, Shared};
1678 use std::{format, mem::MaybeUninit};
1679
1680 #[test]
1681 fn valid_tag_i8() {
1682 Shared::<i8>::null().with_tag(0);
1683 }
1684
1685 #[test]
1686 fn valid_tag_i64() {
1687 Shared::<i64>::null().with_tag(7);
1688 }
1689
1690 #[test]
1691 fn const_atomic_null() {
1692 use super::Atomic;
1693 static _U: Atomic<u8> = Atomic::<u8>::null();
1694 }
1695
1696 #[test]
1697 fn array_init() {
1698 let mut owned = Owned::<[MaybeUninit<usize>]>::init(10);
1699 let arr: &mut [MaybeUninit<usize>] = &mut owned;
1700 arr[arr.len() - 1].write(20);
1701 assert_eq!(arr.len(), 10);
1702 }
1703
1704 #[test]
1705 fn format_null() {
1706 let atomic = Atomic::<usize>::null();
1707 assert_eq!(format!("{atomic:p}"), "0x0");
1708 let atomic = Atomic::<[MaybeUninit<usize>]>::null();
1709 assert_eq!(format!("{atomic:p}"), "0x0");
1710
1711 let shared = Shared::<usize>::null();
1712 assert_eq!(format!("{shared:p}"), "0x0");
1713 let shared = Shared::<[MaybeUninit<usize>]>::null();
1714 assert_eq!(format!("{shared:p}"), "0x0");
1715 }
1716}