arc_swap/as_raw.rs
1use super::{Guard, RefCnt};
2
3mod sealed {
4 pub trait Sealed {}
5}
6
7use self::sealed::Sealed;
8
9/// A trait describing things that can be turned into a raw pointer.
10///
11/// This is just an abstraction of things that can be passed to the
12/// [`compare_and_swap`](struct.ArcSwapAny.html#method.compare_and_swap).
13///
14/// # Examples
15///
16/// ```
17/// use std::ptr;
18/// use std::sync::Arc;
19///
20/// use arc_swap::ArcSwapOption;
21///
22/// let a = Arc::new(42);
23/// let shared = ArcSwapOption::from(Some(Arc::clone(&a)));
24///
25/// shared.compare_and_swap(&a, Some(Arc::clone(&a)));
26/// shared.compare_and_swap(&None::<Arc<_>>, Some(Arc::clone(&a)));
27/// shared.compare_and_swap(shared.load(), Some(Arc::clone(&a)));
28/// shared.compare_and_swap(&shared.load(), Some(Arc::clone(&a)));
29/// shared.compare_and_swap(ptr::null(), Some(Arc::clone(&a)));
30/// ```
31///
32/// Due to technical limitation, this is not implemented for owned `Arc`/`Option<Arc<_>>`, they
33/// need to be borrowed.
34pub trait AsRaw<T>: Sealed {
35 /// Converts the value into a raw pointer.
36 fn as_raw(&self) -> *mut T;
37}
38
39impl<'a, T: RefCnt> Sealed for &'a T {}
40impl<'a, T: RefCnt> AsRaw<T::Base> for &'a T {
41 fn as_raw(&self) -> *mut T::Base {
42 T::as_ptr(self)
43 }
44}
45
46impl<'a, T: RefCnt> Sealed for &'a Guard<T> {}
47impl<'a, T: RefCnt> AsRaw<T::Base> for &'a Guard<T> {
48 fn as_raw(&self) -> *mut T::Base {
49 T::as_ptr(self)
50 }
51}
52
53impl<T: RefCnt> Sealed for Guard<T> {}
54impl<T: RefCnt> AsRaw<T::Base> for Guard<T> {
55 fn as_raw(&self) -> *mut T::Base {
56 T::as_ptr(self)
57 }
58}
59
60impl<T> Sealed for *mut T {}
61impl<T> AsRaw<T> for *mut T {
62 fn as_raw(&self) -> *mut T {
63 *self
64 }
65}
66
67impl<T> Sealed for *const T {}
68impl<T> AsRaw<T> for *const T {
69 fn as_raw(&self) -> *mut T {
70 *self as *mut T
71 }
72}