arcref.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #[cfg(not(feature = "std"))]
  2. use core::{
  3. borrow::Borrow,
  4. marker::{PhantomData, Unsize},
  5. mem::ManuallyDrop,
  6. ops::{Deref, DispatchFromDyn},
  7. };
  8. #[cfg(all(not(feature = "std"), feature = "alloc"))]
  9. extern crate alloc;
  10. #[cfg(all(not(feature = "std"), feature = "alloc"))]
  11. use alloc::sync::Arc;
  12. #[cfg(feature = "std")]
  13. use std::{
  14. borrow::Borrow,
  15. marker::{PhantomData, Unsize},
  16. mem::ManuallyDrop,
  17. ops::{Deref, DispatchFromDyn},
  18. sync::Arc,
  19. };
  20. pub trait AsArcRef<T>
  21. where
  22. T: ?Sized,
  23. {
  24. /// Borrow the [`Arc`] and convert the reference into [`ArcRef`].
  25. fn aref(&self) -> ArcRef<'_, T>;
  26. }
  27. pub struct ArcRef<'a, T: ?Sized> {
  28. ptr: *const T,
  29. _phantom: PhantomData<&'a ()>,
  30. }
  31. unsafe impl<T: ?Sized + Send + Sync> Send for ArcRef<'_, T> {}
  32. unsafe impl<T: ?Sized + Send + Sync> Sync for ArcRef<'_, T> {}
  33. #[cfg(any(feature = "std", feature = "alloc"))]
  34. impl<'a, T: ?Sized> ArcRef<'a, T> {
  35. pub fn new(arc: &'a Arc<T>) -> Self {
  36. Self {
  37. ptr: Arc::as_ptr(arc),
  38. _phantom: PhantomData,
  39. }
  40. }
  41. /// Create a new `ArcRef` from a raw pointer.
  42. ///
  43. /// # Safety
  44. /// The given pointer MUST be created by `Arc::as_ptr` or `Arc::into_raw`.
  45. /// The caller is responsible to ensure that the pointer is valid for the
  46. /// lifetime of the `ArcRef`.
  47. pub unsafe fn new_unchecked(arc_ptr: *const T) -> Self {
  48. Self {
  49. ptr: arc_ptr,
  50. _phantom: PhantomData,
  51. }
  52. }
  53. pub fn with_arc<Func, Out>(self, func: Func) -> Out
  54. where
  55. Func: FnOnce(&Arc<T>) -> Out,
  56. {
  57. func(&ManuallyDrop::new(unsafe { Arc::from_raw(self.ptr) }))
  58. }
  59. pub fn clone_arc(self) -> Arc<T> {
  60. self.with_arc(|arc| arc.clone())
  61. }
  62. pub fn ptr_eq_arc(self, other: &Arc<T>) -> bool {
  63. self.with_arc(|arc| Arc::ptr_eq(arc, other))
  64. }
  65. }
  66. #[cfg(all(not(feature = "std"), feature = "alloc"))]
  67. impl<T> AsArcRef<T> for Arc<T>
  68. where
  69. T: ?Sized,
  70. {
  71. fn aref(&self) -> ArcRef<'_, T> {
  72. ArcRef::new(self)
  73. }
  74. }
  75. impl<T> AsRef<T> for ArcRef<'_, T>
  76. where
  77. T: ?Sized,
  78. {
  79. fn as_ref(&self) -> &T {
  80. self.deref()
  81. }
  82. }
  83. impl<T> Borrow<T> for ArcRef<'_, T>
  84. where
  85. T: ?Sized,
  86. {
  87. fn borrow(&self) -> &T {
  88. self.deref()
  89. }
  90. }
  91. impl<'a, T> Clone for ArcRef<'a, T>
  92. where
  93. T: ?Sized,
  94. {
  95. fn clone(&self) -> Self {
  96. Self {
  97. ptr: self.ptr,
  98. _phantom: PhantomData,
  99. }
  100. }
  101. }
  102. impl<T> Copy for ArcRef<'_, T> where T: ?Sized {}
  103. impl<T: ?Sized> Deref for ArcRef<'_, T> {
  104. type Target = T;
  105. fn deref(&self) -> &T {
  106. unsafe {
  107. // SAFETY: `self.ptr` points to a valid `T` instance because it was
  108. // created from a valid `Arc<T>`.
  109. self.ptr.as_ref().unwrap_unchecked()
  110. }
  111. }
  112. }
  113. impl<'a, T, U> DispatchFromDyn<ArcRef<'a, U>> for ArcRef<'a, T>
  114. where
  115. T: ?Sized + Unsize<U>,
  116. U: ?Sized,
  117. {
  118. }
  119. #[cfg(test)]
  120. mod tests {
  121. use super::*;
  122. #[test]
  123. fn create_from_arc() {
  124. let data = Arc::new(42);
  125. let _arc_ref = ArcRef::new(&data);
  126. }
  127. #[test]
  128. fn deref() {
  129. let data = Arc::new(42);
  130. let arc_ref = ArcRef::new(&data);
  131. assert_eq!(*arc_ref, 42);
  132. }
  133. #[test]
  134. fn clone_into_arc() {
  135. let data = Arc::new(42);
  136. let arc_ref = ArcRef::new(&data);
  137. let cloned = arc_ref.clone_arc();
  138. assert_eq!(Arc::strong_count(&data), 2);
  139. assert_eq!(*cloned, 42);
  140. }
  141. #[test]
  142. fn dyn_compatible_receiver() {
  143. struct Data(u32);
  144. trait Trait {
  145. fn foo(self: ArcRef<Self>) -> u32;
  146. }
  147. impl Trait for Data {
  148. fn foo(self: ArcRef<Self>) -> u32 {
  149. self.0
  150. }
  151. }
  152. let data = Arc::new(Data(42));
  153. let arc_ref = ArcRef::new(&data);
  154. assert_eq!(arc_ref.foo(), 42);
  155. }
  156. #[test]
  157. fn clone_from_train_methods() {
  158. struct Data(u32);
  159. trait Trait {
  160. fn foo(&self) -> u32;
  161. fn clone_self(self: ArcRef<Self>) -> Arc<dyn Trait>;
  162. }
  163. impl Trait for Data {
  164. fn foo(&self) -> u32 {
  165. self.0
  166. }
  167. fn clone_self(self: ArcRef<Self>) -> Arc<dyn Trait> {
  168. self.clone_arc() as _
  169. }
  170. }
  171. let data = Arc::new(Data(42));
  172. let arc_ref = ArcRef::new(&data);
  173. let cloned = arc_ref.clone_self();
  174. assert_eq!(arc_ref.foo(), 42);
  175. assert_eq!(cloned.foo(), 42);
  176. }
  177. }