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
//! Unboxed aliasable values based on `Pin`. //! //! In Rust, it is currently impossible to soundly create unboxed self-referencing, or //! externally-referenced, types - see [this //! document](https://gist.github.com/Darksonn/1567538f56af1a8038ecc3c664a42462) for details. //! However, futures generated by async blocks need to be self-referencing, and this makes them //! [technically unsound](https://github.com/rust-lang/rust/issues/63818). So to avoid //! miscompilations, Rust has inserted a temporary loophole: No unique references to `!Unpin` types //! will actually be annotated with `noalias`, preventing the compiler from making optimizations //! based on the pointed-to types being not self-referential. //! //! This is a huge hack. Not all self-referential types are `!Unpin`, and some `!Unpin` types would //! actually work with `noalias`. Ultimately, the solution will be to provide an `Aliasable<T>` type //! in libcore that prevents any parent containers from being annotated with `noalias`, but //! unfortunately that doesn't exist yet. //! //! As a workaround, this crate provides an [`Aliasable<T>`] type that doesn't cause miscompilations //! today by being `!Unpin`, and is future-compatible with the hypothetical `Aliasable` type in //! libcore. Additionally, to avoid Miri giving errors, it is substituted for a boxed value when //! run using it. When `Aliasable` is finally added to the language itself, I will release a new //! version of this crate based on it and yank all previous versions. //! //! [`Aliasable<T>`]: https://docs.rs/pinned-aliasable/*/pinned_aliasable/struct.Aliasable.html //! //! # Examples //! //! A pair type: //! //! ```rust //! use core::pin::Pin; //! use core::cell::Cell; //! //! use pinned_aliasable::Aliasable; //! use pin_project_lite::pin_project; //! use pin_utils::pin_mut; //! //! pin_project! { //! pub struct Pair { //! #[pin] //! inner: Aliasable<PairInner>, //! } //! } //! struct PairInner { //! value: u64, //! other: Cell<Option<&'static PairInner>>, //! } //! impl Drop for PairInner { //! fn drop(&mut self) { //! if let Some(other) = self.other.get() { //! other.other.set(None); //! } //! } //! } //! //! impl Pair { //! pub fn new(value: u64) -> Self { //! Self { //! inner: Aliasable::new(PairInner { //! value, //! other: Cell::new(None), //! }) //! } //! } //! pub fn get(self: Pin<&Self>) -> u64 { //! self.project_ref().inner.get().other.get().unwrap().value //! } //! } //! //! pub fn link_up(left: Pin<&Pair>, right: Pin<&Pair>) { //! let left = unsafe { left.project_ref().inner.get_extended() }; //! let right = unsafe { right.project_ref().inner.get_extended() }; //! left.other.set(Some(right)); //! right.other.set(Some(left)); //! } //! //! fn main() { //! let pair_1 = Pair::new(10); //! let pair_2 = Pair::new(20); //! pin_mut!(pair_1); //! pin_mut!(pair_2); //! //! link_up(pair_1.as_ref(), pair_2.as_ref()); //! //! println!("Pair 2 value: {}", pair_1.as_ref().get()); //! println!("Pair 1 value: {}", pair_2.as_ref().get()); //! } //! ``` #![no_std] #![warn( clippy::pedantic, clippy::wrong_pub_self_convention, rust_2018_idioms, missing_docs, unused_qualifications, missing_debug_implementations, explicit_outlives_requirements, unused_lifetimes, unsafe_op_in_unsafe_fn )] #![allow(clippy::items_after_statements)] use core::fmt::{self, Debug, Formatter}; use core::marker::PhantomPinned; use core::pin::Pin; use pin_project_lite::pin_project; #[cfg_attr(miri, path = "boxed.rs")] #[cfg_attr(not(miri), path = "inline.rs")] mod base; pin_project! { /// An unboxed aliasable value. #[derive(Default)] pub struct Aliasable<T> { #[pin] base: base::Aliasable<T>, #[pin] _pinned: PhantomPinned, } } impl<T> Aliasable<T> { /// Create a new `Aliasable` that stores `val`. #[must_use] #[inline] pub fn new(val: T) -> Self { Self { base: base::Aliasable::new(val), _pinned: PhantomPinned, } } /// Get a shared reference to the value inside the `Aliasable`. /// /// This method takes [`Pin`]`<&Self>` instead of `&self` to enforce that all parent containers /// are `!`[`Unpin`], and thus won't be annotated with `noalias`. /// /// This crate intentionally does not provide a method to get an `&mut T`, because the value /// may be shared. To obtain an `&mut T` you should use an interior mutable container such as a /// mutex or [`UnsafeCell`](core::cell::UnsafeCell). #[must_use] #[inline] pub fn get(self: Pin<&Self>) -> &T { self.project_ref().base.get() } /// Get a shared reference to the value inside the `Aliasable` with an extended lifetime. /// /// # Safety /// /// The reference must not be held for longer than the `Aliasable` exists. #[must_use] #[inline] pub unsafe fn get_extended<'a>(self: Pin<&Self>) -> &'a T { unsafe { &*(self.get() as *const T) } } } impl<T> Debug for Aliasable<T> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.pad("Aliasable") } } #[test] fn miri_is_happy() { use core::cell::UnsafeCell; pin_project! { struct SelfRef { #[pin] value: Aliasable<UnsafeCell<i32>>, reference: Option<&'static mut i32>, } } let self_ref = SelfRef { value: Aliasable::new(UnsafeCell::new(1)), reference: None, }; pin_utils::pin_mut!(self_ref); let projected = self_ref.as_mut().project(); *projected.reference = Some(unsafe { &mut *projected.value.as_ref().get_extended().get() }); fn helper(self_ref: Pin<&mut SelfRef>) { let projected = self_ref.project(); { let reference = projected.reference.take().unwrap(); *reference = 2; } assert_eq!(unsafe { *projected.value.as_ref().get().get() }, 2); } helper(self_ref); } #[test] fn no_miscompilations() { use core::cell::Cell; pin_project! { struct SelfRef { #[pin] value: Aliasable<Cell<i32>>, reference: Option<&'static Cell<i32>>, } } let self_ref = SelfRef { value: Aliasable::new(Cell::new(0)), reference: None, }; pin_utils::pin_mut!(self_ref); let projected = self_ref.as_mut().project(); *projected.reference = Some(unsafe { projected.value.as_ref().get_extended() }); #[inline(never)] fn helper(self_ref: Pin<&mut SelfRef>) -> i32 { let projected = self_ref.project(); projected.value.as_ref().get().set(10); projected.reference.unwrap().set(20); projected.value.as_ref().get().get() } assert_eq!(helper(self_ref), 20); }