| 1 |
#![allow(clippy::missing_safety_doc, clippy::needless_lifetimes)] |
| 2 |
|
| 3 |
use core::cell::UnsafeCell; |
| 4 |
use core::marker::PhantomData; |
| 5 |
use core::mem; |
| 6 |
use core::ptr::{drop_in_place, read, NonNull}; |
| 7 |
use core::sync::atomic::{AtomicBool, Ordering}; |
| 8 |
|
| 9 |
extern crate alloc; |
| 10 |
|
| 11 |
use alloc::alloc::{dealloc, Layout}; |
| 12 |
|
| 13 |
// Self referential structs are currently not supported with safe vanilla Rust. |
| 14 |
// The only reasonable safe alternative is to expect the user to juggle 2 separate |
| 15 |
// data structures which is a mess. The library solution rental is both no longer |
| 16 |
// maintained and really heavy to compile. So begrudgingly I rolled my own version. |
| 17 |
// These are some of the core invariants we require for this to be safe to use. |
| 18 |
// |
| 19 |
// 1. owner is initialized when UnsafeSelfCell is constructed. |
| 20 |
// 2. owner is NEVER changed again. |
| 21 |
// 3. The pointer to owner and dependent never changes, even when moved. |
| 22 |
// 4. The only access to owner and dependent is as immutable reference. |
| 23 |
// 5. owner lives longer than dependent. |
| 24 |
|
| 25 |
#[doc(hidden)] |
| 26 |
pub struct JoinedCell<Owner, Dependent> { |
| 27 |
pub owner: Owner, |
| 28 |
pub dependent: Dependent, |
| 29 |
} |
| 30 |
|
| 31 |
// Library controlled struct that marks all accesses as unsafe. |
| 32 |
// Because the macro generated struct impl can be extended, could be unsafe. |
| 33 |
#[doc(hidden)] |
| 34 |
pub struct UnsafeSelfCell<ContainedIn, Owner, DependentStatic: 'static> { |
| 35 |
joined_void_ptr: NonNull<u8>, |
| 36 |
|
| 37 |
// ContainedIn is necessary for type safety since we don't fully |
| 38 |
// prohibit access to the UnsafeSelfCell; swapping between different |
| 39 |
// structs can be unsafe otherwise, see Issue #17. |
| 40 |
contained_in_marker: PhantomData<ContainedIn>, |
| 41 |
|
| 42 |
owner_marker: PhantomData<Owner>, |
| 43 |
// DependentStatic is only used to correctly derive Send and Sync. |
| 44 |
dependent_marker: PhantomData<DependentStatic>, |
| 45 |
} |
| 46 |
|
| 47 |
impl<ContainedIn, Owner, DependentStatic> UnsafeSelfCell<ContainedIn, Owner, DependentStatic> { |
| 48 |
pub unsafe fn new(joined_void_ptr: NonNull<u8>) -> Self { |
| 49 |
Self { |
| 50 |
joined_void_ptr, |
| 51 |
contained_in_marker: PhantomData, |
| 52 |
owner_marker: PhantomData, |
| 53 |
dependent_marker: PhantomData, |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// Calling any of these *unsafe* functions with the wrong Dependent type is UB. |
| 58 |
|
| 59 |
pub unsafe fn borrow_owner<'a, Dependent>(&'a self) -> &'a Owner { |
| 60 |
let joined_ptr = self.joined_void_ptr.cast::<JoinedCell<Owner, Dependent>>(); |
| 61 |
|
| 62 |
&(*joined_ptr.as_ptr()).owner |
| 63 |
} |
| 64 |
|
| 65 |
pub unsafe fn borrow_dependent<'a, Dependent>(&'a self) -> &'a Dependent { |
| 66 |
let joined_ptr = self.joined_void_ptr.cast::<JoinedCell<Owner, Dependent>>(); |
| 67 |
|
| 68 |
&(*joined_ptr.as_ptr()).dependent |
| 69 |
} |
| 70 |
|
| 71 |
pub unsafe fn borrow_mut<'a, Dependent>(&'a mut self) -> (&'a Owner, &'a mut Dependent) { |
| 72 |
let joined_ptr = self.joined_void_ptr.cast::<JoinedCell<Owner, Dependent>>(); |
| 73 |
|
| 74 |
// This function used to return `&'a mut JoinedCell<Owner, Dependent>`. |
| 75 |
// It now creates two references to the fields instead to avoid claiming mutable access |
| 76 |
// to the whole `JoinedCell` (including the owner!) here. |
| 77 |
( |
| 78 |
&(*joined_ptr.as_ptr()).owner, |
| 79 |
&mut (*joined_ptr.as_ptr()).dependent, |
| 80 |
) |
| 81 |
} |
| 82 |
|
| 83 |
// Any subsequent use of this struct other than dropping it is UB. |
| 84 |
pub unsafe fn drop_joined<Dependent>(&mut self) { |
| 85 |
let joined_ptr = self.joined_void_ptr.cast::<JoinedCell<Owner, Dependent>>(); |
| 86 |
|
| 87 |
// Also used in case drop_in_place(...dependent) fails |
| 88 |
let _guard = OwnerAndCellDropGuard { joined_ptr }; |
| 89 |
|
| 90 |
// IMPORTANT dependent must be dropped before owner. |
| 91 |
// We don't want to rely on an implicit order of struct fields. |
| 92 |
// So we drop the struct, field by field manually. |
| 93 |
drop_in_place(&mut (*joined_ptr.as_ptr()).dependent); |
| 94 |
|
| 95 |
// Dropping owner |
| 96 |
// and deallocating |
| 97 |
// due to _guard at end of scope. |
| 98 |
} |
| 99 |
|
| 100 |
pub unsafe fn into_owner<Dependent>(self) -> Owner { |
| 101 |
let joined_ptr = self.joined_void_ptr.cast::<JoinedCell<Owner, Dependent>>(); |
| 102 |
|
| 103 |
// In case drop_in_place(...dependent) fails |
| 104 |
let drop_guard = OwnerAndCellDropGuard::new(joined_ptr); |
| 105 |
|
| 106 |
// Drop dependent |
| 107 |
drop_in_place(&mut (*joined_ptr.as_ptr()).dependent); |
| 108 |
|
| 109 |
mem::forget(drop_guard); |
| 110 |
|
| 111 |
let owner_ptr: *const Owner = &(*joined_ptr.as_ptr()).owner; |
| 112 |
|
| 113 |
// Move owner out so it can be returned. |
| 114 |
// Must not read before dropping dependent!! (Which happened above.) |
| 115 |
let owner = read(owner_ptr); |
| 116 |
|
| 117 |
// Deallocate JoinedCell |
| 118 |
let layout = Layout::new::<JoinedCell<Owner, Dependent>>(); |
| 119 |
dealloc(self.joined_void_ptr.as_ptr(), layout); |
| 120 |
|
| 121 |
owner |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
unsafe impl<ContainedIn, Owner, DependentStatic> Send |
| 126 |
for UnsafeSelfCell<ContainedIn, Owner, DependentStatic> |
| 127 |
where |
| 128 |
// Only derive Send if Owner and DependentStatic is also Send |
| 129 |
Owner: Send, |
| 130 |
DependentStatic: Send, |
| 131 |
{ |
| 132 |
} |
| 133 |
|
| 134 |
unsafe impl<ContainedIn, Owner, DependentStatic> Sync |
| 135 |
for UnsafeSelfCell<ContainedIn, Owner, DependentStatic> |
| 136 |
where |
| 137 |
// Only derive Sync if Owner and DependentStatic is also Sync |
| 138 |
Owner: Sync, |
| 139 |
DependentStatic: Sync, |
| 140 |
{ |
| 141 |
} |
| 142 |
|
| 143 |
// Wrapper pointer type that is `Send` only for internal use. |
| 144 |
#[repr(transparent)] |
| 145 |
#[doc(hidden)] |
| 146 |
#[derive(Copy, Clone)] |
| 147 |
pub struct SendMutPtr<T>(*mut T); |
| 148 |
|
| 149 |
impl<T> SendMutPtr<T> { |
| 150 |
#[inline] |
| 151 |
pub fn new(ptr: *mut T) -> Self { |
| 152 |
Self(ptr) |
| 153 |
} |
| 154 |
|
| 155 |
// SAFETY: Same as `ptr::write` and the usage must be done is such a way that writes to it can't |
| 156 |
// be raced, for example by letting users decide the timing of the write. |
| 157 |
#[inline] |
| 158 |
pub unsafe fn write(self, val: T) { |
| 159 |
self.0.write(val); |
| 160 |
} |
| 161 |
|
| 162 |
// SAFETY: Same as `ptr::read`. |
| 163 |
#[inline] |
| 164 |
pub unsafe fn read(self) -> T { |
| 165 |
read(self.0) |
| 166 |
} |
| 167 |
|
| 168 |
// SAFETY: Same as `alloc::dealloc` and `Self::write`. |
| 169 |
#[inline] |
| 170 |
pub unsafe fn dealloc(self, layout: Layout) { |
| 171 |
dealloc(self.0 as *mut u8, layout); |
| 172 |
} |
| 173 |
|
| 174 |
#[inline] |
| 175 |
pub fn into_non_null(self) -> Option<NonNull<T>> { |
| 176 |
NonNull::new(self.0) |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
// SAFETY: See `Self::write`. |
| 181 |
unsafe impl<T> Send for SendMutPtr<T> {} |
| 182 |
|
| 183 |
// This struct is used to safely deallocate only the owner if dependent |
| 184 |
// construction fails. |
| 185 |
// |
| 186 |
// mem::forget it once it's no longer needed or dtor will be UB. |
| 187 |
#[doc(hidden)] |
| 188 |
pub struct OwnerAndCellDropGuard<Owner, Dependent> { |
| 189 |
joined_ptr: NonNull<JoinedCell<Owner, Dependent>>, |
| 190 |
} |
| 191 |
|
| 192 |
impl<Owner, Dependent> OwnerAndCellDropGuard<Owner, Dependent> { |
| 193 |
pub unsafe fn new(joined_ptr: NonNull<JoinedCell<Owner, Dependent>>) -> Self { |
| 194 |
Self { joined_ptr } |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
impl<Owner, Dependent> Drop for OwnerAndCellDropGuard<Owner, Dependent> { |
| 199 |
fn drop(&mut self) { |
| 200 |
struct DeallocGuard { |
| 201 |
ptr: *mut u8, |
| 202 |
layout: Layout, |
| 203 |
} |
| 204 |
impl Drop for DeallocGuard { |
| 205 |
fn drop(&mut self) { |
| 206 |
unsafe { dealloc(self.ptr, self.layout) } |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
// Deallocate even when the drop_in_place(...owner) panics |
| 211 |
let _guard = DeallocGuard { |
| 212 |
ptr: self.joined_ptr.as_ptr() as *mut u8, |
| 213 |
layout: Layout::new::<JoinedCell<Owner, Dependent>>(), |
| 214 |
}; |
| 215 |
|
| 216 |
unsafe { |
| 217 |
// We must only drop owner and the struct itself, |
| 218 |
// The whole point of this drop guard is to clean up the partially |
| 219 |
// initialized struct should building the dependent fail. |
| 220 |
drop_in_place(&mut (*self.joined_ptr.as_ptr()).owner); |
| 221 |
} |
| 222 |
|
| 223 |
// Deallocation happens at end of scope |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
// SAFETY: The only type dependent code it runs is `drop_in_place` for the `Owner`, so that MUST be |
| 228 |
// `Send`. |
| 229 |
unsafe impl<Owner: Send, Dependent> Send for OwnerAndCellDropGuard<Owner, Dependent> {} |
| 230 |
|
| 231 |
// Older versions of rust do not support addr_of_mut!. What we want to do here |
| 232 |
// is to emulate the behavior of that macro by going (incorrectly) via a |
| 233 |
// reference cast. Technically this is UB, but testing does not show the older |
| 234 |
// compiler versions (ab)using this. For discussions about this behavior see |
| 235 |
// https://github.com/Voultapher/self_cell/pull/31 and |
| 236 |
// https://github.com/Voultapher/self_cell/issues/30 and |
| 237 |
// https://github.com/Voultapher/self_cell/pull/33 |
| 238 |
// |
| 239 |
// Because of 'procedural macros cannot expand to macro definitions' |
| 240 |
// we have wrap this in functions. |
| 241 |
impl<Owner, Dependent> JoinedCell<Owner, Dependent> { |
| 242 |
#[doc(hidden)] |
| 243 |
#[cfg(not(feature = "old_rust"))] |
| 244 |
pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) { |
| 245 |
let owner_ptr = core::ptr::addr_of_mut!((*this).owner); |
| 246 |
let dependent_ptr = core::ptr::addr_of_mut!((*this).dependent); |
| 247 |
|
| 248 |
(owner_ptr, dependent_ptr) |
| 249 |
} |
| 250 |
|
| 251 |
#[doc(hidden)] |
| 252 |
#[cfg(feature = "old_rust")] |
| 253 |
#[rustversion::since(1.51)] |
| 254 |
pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) { |
| 255 |
let owner_ptr = core::ptr::addr_of_mut!((*this).owner); |
| 256 |
let dependent_ptr = core::ptr::addr_of_mut!((*this).dependent); |
| 257 |
|
| 258 |
(owner_ptr, dependent_ptr) |
| 259 |
} |
| 260 |
|
| 261 |
#[doc(hidden)] |
| 262 |
#[cfg(feature = "old_rust")] |
| 263 |
#[rustversion::before(1.51)] |
| 264 |
pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) { |
| 265 |
// See comment above, technically this is UB. |
| 266 |
let owner_ptr = &mut (*this).owner as *mut Owner; |
| 267 |
let dependent_ptr = &mut (*this).dependent as *mut Dependent; |
| 268 |
|
| 269 |
(owner_ptr, dependent_ptr) |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
/// Wrapper type that allows creating a self-referential type that holds a mutable borrow `&mut T`. |
| 274 |
/// |
| 275 |
/// Example usage: |
| 276 |
/// |
| 277 |
/// ``` |
| 278 |
/// use self_cell::{self_cell, MutBorrow}; |
| 279 |
/// |
| 280 |
/// type MutStringRef<'a> = &'a mut String; |
| 281 |
/// |
| 282 |
/// self_cell!( |
| 283 |
/// struct MutStringCell { |
| 284 |
/// owner: MutBorrow<String>, |
| 285 |
/// |
| 286 |
/// #[covariant] |
| 287 |
/// dependent: MutStringRef, |
| 288 |
/// } |
| 289 |
/// ); |
| 290 |
/// |
| 291 |
/// let mut cell = MutStringCell::new(MutBorrow::new("abc".into()), |owner| owner.borrow_mut()); |
| 292 |
/// cell.with_dependent_mut(|_owner, dependent| { |
| 293 |
/// assert_eq!(dependent, &"abc"); |
| 294 |
/// dependent.pop(); |
| 295 |
/// assert_eq!(dependent, &"ab"); |
| 296 |
/// }); |
| 297 |
/// |
| 298 |
/// let recovered_owner: String = cell.into_owner().into_inner(); |
| 299 |
/// assert_eq!(recovered_owner, "ab"); |
| 300 |
/// ``` |
| 301 |
pub struct MutBorrow<T> { |
| 302 |
// Private on purpose. |
| 303 |
is_locked: AtomicBool, |
| 304 |
value: UnsafeCell<T>, |
| 305 |
} |
| 306 |
|
| 307 |
impl<T> MutBorrow<T> { |
| 308 |
/// Constructs a new `MutBorrow`. |
| 309 |
pub fn new(value: T) -> Self { |
| 310 |
// Use the Rust type system to model an affine type that can only go from unlocked -> locked |
| 311 |
// but never the other way around. |
| 312 |
Self { |
| 313 |
is_locked: AtomicBool::new(false), |
| 314 |
value: UnsafeCell::new(value), |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
/// Obtains a mutable reference to the underlying data. |
| 319 |
/// |
| 320 |
/// This function can only sensibly be used in the builder function. Afterwards, it's impossible |
| 321 |
/// to access the inner value, with the exception of [`MutBorrow::into_inner`]. |
| 322 |
/// |
| 323 |
/// # Panics |
| 324 |
/// |
| 325 |
/// Will panic if called anywhere but in the dependent constructor. Will also panic if called |
| 326 |
/// more than once. |
| 327 |
#[allow(clippy::mut_from_ref)] |
| 328 |
pub fn borrow_mut(&self) -> &mut T { |
| 329 |
// Ensure this function can only be called once. |
| 330 |
// Relaxed should be fine, because only one thread could ever read `false` anyway, |
| 331 |
// so further synchronization is pointless. |
| 332 |
let was_locked = self.is_locked.swap(true, Ordering::Relaxed); |
| 333 |
|
| 334 |
if was_locked { |
| 335 |
panic!("Tried to access locked MutBorrow") |
| 336 |
} else { |
| 337 |
// SAFETY: `self.is_locked` starts out as locked and can never be unlocked again, which |
| 338 |
// guarantees that this function can only be called once. And the `self.value` being |
| 339 |
// private ensures that there are no other references to it. |
| 340 |
unsafe { &mut *self.value.get() } |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
/// Consumes `self` and returns the wrapped value. |
| 345 |
pub fn into_inner(self) -> T { |
| 346 |
self.value.into_inner() |
| 347 |
} |
| 348 |
} |
| 349 |
impl<T> From<T> for MutBorrow<T> { |
| 350 |
fn from(value: T) -> Self { |
| 351 |
Self::new(value) |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
// SAFETY: The reasoning why it is safe to share `MutBorrow` across threads is as follows: The |
| 356 |
// `AtomicBool` `is_locked` ensures that only ever exactly one thread can get access to the inner |
| 357 |
// value. In that sense it works like a critical section, that begins when `borrow_mut()` is called |
| 358 |
// and that ends when the outer `MutBorrow` is dropped. Once one thread acquired the unique |
| 359 |
// reference through `borrow_mut()` no other interaction with the inner value MUST ever be possible |
| 360 |
// while the outer `MutBorrow` is alive. |
| 361 |
unsafe impl<T: Send> Sync for MutBorrow<T> {} |