| 1 |
//! # Overview |
| 2 |
//! |
| 3 |
//! `self_cell` provides one macro-rules macro: [`self_cell`]. With this macro |
| 4 |
//! you can create self-referential structs that are safe-to-use in stable Rust, |
| 5 |
//! without leaking the struct internal lifetime. |
| 6 |
//! |
| 7 |
//! In a nutshell, the API looks *roughly* like this: |
| 8 |
//! |
| 9 |
//! ```ignore |
| 10 |
//! // User code: |
| 11 |
//! |
| 12 |
//! self_cell!( |
| 13 |
//! struct NewStructName { |
| 14 |
//! owner: Owner, |
| 15 |
//! |
| 16 |
//! #[covariant] |
| 17 |
//! dependent: Dependent, |
| 18 |
//! } |
| 19 |
//! |
| 20 |
//! impl {Debug} |
| 21 |
//! ); |
| 22 |
//! |
| 23 |
//! // Generated by macro: |
| 24 |
//! |
| 25 |
//! struct NewStructName(...); |
| 26 |
//! |
| 27 |
//! impl NewStructName { |
| 28 |
//! fn new( |
| 29 |
//! owner: Owner, |
| 30 |
//! dependent_builder: impl for<'a> FnOnce(&'a Owner) -> Dependent<'a> |
| 31 |
//! ) -> NewStructName { ... } |
| 32 |
//! fn borrow_owner<'a>(&'a self) -> &'a Owner { ... } |
| 33 |
//! fn borrow_dependent<'a>(&'a self) -> &'a Dependent<'a> { ... } |
| 34 |
//! } |
| 35 |
//! |
| 36 |
//! impl Debug for NewStructName { ... } |
| 37 |
//! ``` |
| 38 |
//! |
| 39 |
//! Self-referential structs are currently not supported with safe vanilla Rust. |
| 40 |
//! The only reasonable safe alternative is to have the user juggle 2 separate |
| 41 |
//! data structures which is a mess. The library solution ouroboros is really |
| 42 |
//! expensive to compile due to its use of procedural macros. |
| 43 |
//! |
| 44 |
//! This alternative is `no_std`, uses no proc-macros, some self contained |
| 45 |
//! unsafe and works on stable Rust, and is miri tested. With a total of less |
| 46 |
//! than 300 lines of implementation code, which consists mostly of type and |
| 47 |
//! trait implementations, this crate aims to be a good minimal solution to the |
| 48 |
//! problem of self-referential structs. |
| 49 |
//! |
| 50 |
//! It has undergone [community code |
| 51 |
//! review](https://users.rust-lang.org/t/experimental-safe-to-use-proc-macro-free-self-referential-structs-in-stable-rust/52775) |
| 52 |
//! from experienced Rust users. |
| 53 |
//! |
| 54 |
//! ### Fast compile times |
| 55 |
//! |
| 56 |
//! ```txt |
| 57 |
//! $ rm -rf target && cargo +nightly build -Z timings |
| 58 |
//! |
| 59 |
//! Compiling self_cell v0.7.0 |
| 60 |
//! Completed self_cell v0.7.0 in 0.2s |
| 61 |
//! ``` |
| 62 |
//! |
| 63 |
//! Because it does **not** use proc-macros, and has 0 dependencies |
| 64 |
//! compile-times are fast. |
| 65 |
//! |
| 66 |
//! Measurements done on a slow laptop. |
| 67 |
//! |
| 68 |
//! ### A motivating use case |
| 69 |
//! |
| 70 |
//! ```rust |
| 71 |
//! use self_cell::self_cell; |
| 72 |
//! |
| 73 |
//! #[derive(Debug, Eq, PartialEq)] |
| 74 |
//! struct Ast<'a>(pub Vec<&'a str>); |
| 75 |
//! |
| 76 |
//! self_cell!( |
| 77 |
//! struct AstCell { |
| 78 |
//! owner: String, |
| 79 |
//! |
| 80 |
//! #[covariant] |
| 81 |
//! dependent: Ast, |
| 82 |
//! } |
| 83 |
//! |
| 84 |
//! impl {Debug, Eq, PartialEq} |
| 85 |
//! ); |
| 86 |
//! |
| 87 |
//! fn build_ast_cell(code: &str) -> AstCell { |
| 88 |
//! // Create owning String on stack. |
| 89 |
//! let pre_processed_code = code.trim().to_string(); |
| 90 |
//! |
| 91 |
//! // Move String into AstCell, then build Ast inplace. |
| 92 |
//! AstCell::new( |
| 93 |
//! pre_processed_code, |
| 94 |
//! |code| Ast(code.split(' ').filter(|word| word.len() > 1).collect()) |
| 95 |
//! ) |
| 96 |
//! } |
| 97 |
//! |
| 98 |
//! fn main() { |
| 99 |
//! let ast_cell = build_ast_cell("fox = cat + dog"); |
| 100 |
//! |
| 101 |
//! println!("ast_cell -> {:?}", &ast_cell); |
| 102 |
//! println!("ast_cell.borrow_owner() -> {:?}", ast_cell.borrow_owner()); |
| 103 |
//! println!("ast_cell.borrow_dependent().0[1] -> {:?}", ast_cell.borrow_dependent().0[1]); |
| 104 |
//! } |
| 105 |
//! ``` |
| 106 |
//! |
| 107 |
//! ```txt |
| 108 |
//! $ cargo run |
| 109 |
//! |
| 110 |
//! ast_cell -> AstCell { owner: "fox = cat + dog", dependent: Ast(["fox", "cat", "dog"]) } |
| 111 |
//! ast_cell.borrow_owner() -> "fox = cat + dog" |
| 112 |
//! ast_cell.borrow_dependent().0[1] -> "cat" |
| 113 |
//! ``` |
| 114 |
//! |
| 115 |
//! There is no way in safe Rust to have an API like `build_ast_cell`, as soon |
| 116 |
//! as `Ast` depends on stack variables like `pre_processed_code` you can't |
| 117 |
//! return the value out of the function anymore. You could move the |
| 118 |
//! pre-processing into the caller but that gets ugly quickly because you can't |
| 119 |
//! encapsulate things anymore. Note this is a somewhat niche use case, |
| 120 |
//! self-referential structs should only be used when there is no good |
| 121 |
//! alternative. |
| 122 |
//! |
| 123 |
//! Under the hood, it heap allocates a struct which it initializes first by |
| 124 |
//! moving the owner value to it and then using the reference to this now |
| 125 |
//! Pin/Immovable owner to construct the dependent inplace next to it. This |
| 126 |
//! makes it safe to move the generated SelfCell but you have to pay for the |
| 127 |
//! heap allocation. |
| 128 |
//! |
| 129 |
//! See the documentation for [`self_cell`] to dive further into the details. |
| 130 |
//! |
| 131 |
//! Or take a look at the advanced examples: |
| 132 |
//! - [Example how to handle dependent construction that can |
| 133 |
//! fail](https://github.com/Voultapher/self_cell/tree/main/examples/fallible_dependent_construction) |
| 134 |
//! |
| 135 |
//! - [How to build a lazy AST with |
| 136 |
//! self_cell](https://github.com/Voultapher/self_cell/tree/main/examples/lazy_ast) |
| 137 |
//! |
| 138 |
//! - [How to use an owner type with |
| 139 |
//! lifetime](https://github.com/Voultapher/self_cell/tree/main/examples/owner_with_lifetime) |
| 140 |
//! |
| 141 |
//! ### Min required rustc version |
| 142 |
//! |
| 143 |
//! By default the minimum required rustc version is 1.51. |
| 144 |
//! |
| 145 |
//! There is an optional feature you can enable called "old_rust" that enables |
| 146 |
//! support down to rustc version 1.36. However this requires polyfilling std |
| 147 |
//! library functionality for older rustc with technically UB versions. Testing |
| 148 |
//! does not show older rustc versions (ab)using this. Use at your own risk. |
| 149 |
//! |
| 150 |
//! The minimum versions are a best effor and may change with any new major |
| 151 |
//! release. |
| 152 |
|
| 153 |
#![no_std] |
| 154 |
|
| 155 |
#[doc(hidden)] |
| 156 |
pub extern crate alloc; |
| 157 |
|
| 158 |
#[doc(hidden)] |
| 159 |
pub mod unsafe_self_cell; |
| 160 |
|
| 161 |
/// This macro declares a new struct of `$StructName` and implements traits |
| 162 |
/// based on `$AutomaticDerive`. |
| 163 |
/// |
| 164 |
/// ### Example: |
| 165 |
/// |
| 166 |
/// ```rust |
| 167 |
/// use self_cell::self_cell; |
| 168 |
/// |
| 169 |
/// #[derive(Debug, Eq, PartialEq)] |
| 170 |
/// struct Ast<'a>(Vec<&'a str>); |
| 171 |
/// |
| 172 |
/// self_cell!( |
| 173 |
/// #[doc(hidden)] |
| 174 |
/// struct PackedAstCell { |
| 175 |
/// owner: String, |
| 176 |
/// |
| 177 |
/// #[covariant] |
| 178 |
/// dependent: Ast, |
| 179 |
/// } |
| 180 |
/// |
| 181 |
/// impl {Debug, PartialEq, Eq, Hash} |
| 182 |
/// ); |
| 183 |
/// ``` |
| 184 |
/// |
| 185 |
/// See the crate overview to get a get an overview and a motivating example. |
| 186 |
/// |
| 187 |
/// ### Generated API: |
| 188 |
/// |
| 189 |
/// The macro implements these constructors: |
| 190 |
/// |
| 191 |
/// ```ignore |
| 192 |
/// fn new( |
| 193 |
/// owner: $Owner, |
| 194 |
/// dependent_builder: impl for<'a> FnOnce(&'a $Owner) -> $Dependent<'a> |
| 195 |
/// ) -> Self |
| 196 |
/// ``` |
| 197 |
/// |
| 198 |
/// ```ignore |
| 199 |
/// fn try_new<Err>( |
| 200 |
/// owner: $Owner, |
| 201 |
/// dependent_builder: impl for<'a> FnOnce(&'a $Owner) -> Result<$Dependent<'a>, Err> |
| 202 |
/// ) -> Result<Self, Err> |
| 203 |
/// ``` |
| 204 |
/// |
| 205 |
/// ```ignore |
| 206 |
/// fn try_new_or_recover<Err>( |
| 207 |
/// owner: $Owner, |
| 208 |
/// dependent_builder: impl for<'a> FnOnce(&'a $Owner) -> Result<$Dependent<'a>, Err> |
| 209 |
/// ) -> Result<Self, ($Owner, Err)> |
| 210 |
/// ``` |
| 211 |
/// |
| 212 |
/// The macro implements these methods: |
| 213 |
/// |
| 214 |
/// ```ignore |
| 215 |
/// fn borrow_owner<'a>(&'a self) -> &'a $Owner |
| 216 |
/// ``` |
| 217 |
/// |
| 218 |
/// ```ignore |
| 219 |
/// // Only available if dependent is covariant. |
| 220 |
/// fn borrow_dependent<'a>(&'a self) -> &'a $Dependent<'a> |
| 221 |
/// ``` |
| 222 |
/// |
| 223 |
/// ```ignore |
| 224 |
/// fn with_dependent<'outer_fn, Ret>( |
| 225 |
/// &'outer_fn self, |
| 226 |
/// func: impl for<'a> FnOnce(&'a $Owner, &'outer_fn $Dependent<'a> |
| 227 |
/// ) -> Ret) -> Ret |
| 228 |
/// ``` |
| 229 |
/// |
| 230 |
/// ```ignore |
| 231 |
/// fn with_dependent_mut<'outer_fn, Ret>( |
| 232 |
/// &'outer_fn mut self, |
| 233 |
/// func: impl for<'a> FnOnce(&'a $Owner, &'outer_fn mut $Dependent<'a>) -> Ret |
| 234 |
/// ) -> Ret |
| 235 |
/// ``` |
| 236 |
/// |
| 237 |
/// ```ignore |
| 238 |
/// fn into_owner(self) -> $Owner |
| 239 |
/// ``` |
| 240 |
/// |
| 241 |
/// |
| 242 |
/// ### Parameters: |
| 243 |
/// |
| 244 |
/// - `$Vis:vis struct $StructName:ident` Name of the struct that will be |
| 245 |
/// declared, this needs to be unique for the relevant scope. Example: `struct |
| 246 |
/// AstCell` or `pub struct AstCell`. `$Vis` can be used to mark the struct |
| 247 |
/// and all functions implemented by the macro as public. |
| 248 |
/// |
| 249 |
/// `$(#[$StructMeta:meta])*` allows you specify further meta items for this |
| 250 |
/// struct, eg. `#[doc(hidden)] struct AstCell`. |
| 251 |
/// |
| 252 |
/// - `$Owner:ty` Type of owner. This has to have a `'static` lifetime. Example: |
| 253 |
/// `String`. |
| 254 |
/// |
| 255 |
/// - `$Dependent:ident` Name of the dependent type without specified lifetime. |
| 256 |
/// This can't be a nested type name. As workaround either create a type alias |
| 257 |
/// `type Dep<'a> = Option<Vec<&'a str>>;` or create a new-type `struct |
| 258 |
/// Dep<'a>(Option<Vec<&'a str>>);`. Example: `Ast`. |
| 259 |
/// |
| 260 |
/// `$Covariance:ident` Marker declaring if `$Dependent` is |
| 261 |
/// [covariant](https://doc.rust-lang.org/nightly/nomicon/subtyping.html). |
| 262 |
/// Possible Values: |
| 263 |
/// |
| 264 |
/// * **covariant**: This generates the direct reference accessor function |
| 265 |
/// `borrow_dependent`. This is only safe to do if this compiles `fn |
| 266 |
/// _assert_covariance<'x: 'y, 'y>(x: $Dependent<'x>) -> $Dependent<'y> |
| 267 |
/// {x}`. Otherwise you could choose a lifetime that is too short for types |
| 268 |
/// with interior mutability like `Cell`, which can lead to UB in safe code. |
| 269 |
/// Which would violate the promise of this library that it is safe-to-use. |
| 270 |
/// If you accidentally mark a type that is not covariant as covariant, you |
| 271 |
/// will get a compile time error. |
| 272 |
/// |
| 273 |
/// * **not_covariant**: This generates no additional code but you can use the |
| 274 |
/// `with_dependent` function. See [How to build a lazy AST with |
| 275 |
/// self_cell](https://github.com/Voultapher/self_cell/tree/main/examples/lazy_ast) |
| 276 |
/// for a usage example. |
| 277 |
/// |
| 278 |
/// In both cases you can use the `with_dependent_mut` function to mutate the |
| 279 |
/// dependent value. This is safe to do because notionally you are replacing |
| 280 |
/// pointers to a value not the other way around. |
| 281 |
/// |
| 282 |
/// - `impl {$($AutomaticDerive:ident),*},` Optional comma separated list of |
| 283 |
/// optional automatic trait implementations. Possible Values: |
| 284 |
/// |
| 285 |
/// * **Debug**: Prints the debug representation of owner and dependent. |
| 286 |
/// Example: `AstCell { owner: "fox = cat + dog", dependent: Ast(["fox", |
| 287 |
/// "cat", "dog"]) }` |
| 288 |
/// |
| 289 |
/// * **PartialEq**: Logic `*self.borrow_owner() == *other.borrow_owner()`, |
| 290 |
/// this assumes that `Dependent<'a>::From<&'a Owner>` is deterministic, so |
| 291 |
/// that only comparing owner is enough. |
| 292 |
/// |
| 293 |
/// * **Eq**: Will implement the trait marker `Eq` for `$StructName`. Beware |
| 294 |
/// if you select this `Eq` will be implemented regardless if `$Owner` |
| 295 |
/// implements `Eq`, that's an unfortunate technical limitation. |
| 296 |
/// |
| 297 |
/// * **Hash**: Logic `self.borrow_owner().hash(state);`, this assumes that |
| 298 |
/// `Dependent<'a>::From<&'a Owner>` is deterministic, so that only hashing |
| 299 |
/// owner is enough. |
| 300 |
/// |
| 301 |
/// All `AutomaticDerive` are optional and you can implement you own version |
| 302 |
/// of these traits. The declared struct is part of your module and you are |
| 303 |
/// free to implement any trait in any way you want. Access to the unsafe |
| 304 |
/// internals is only possible via unsafe functions, so you can't accidentally |
| 305 |
/// use them in safe code. |
| 306 |
/// |
| 307 |
/// There is limited nested cell support. Eg, having an owner with non static |
| 308 |
/// references. Eg `struct ChildCell<'a> { owner: &'a String, ...`. You can |
| 309 |
/// use any lifetime name you want, except `_q` and only a single lifetime is |
| 310 |
/// supported, and can only be used in the owner. Due to macro_rules |
| 311 |
/// limitations, no `AutomaticDerive` are supported if an owner lifetime is |
| 312 |
/// provided. |
| 313 |
/// |
| 314 |
#[macro_export] |
| 315 |
macro_rules! self_cell { |
| 316 |
( |
| 317 |
$(#[$StructMeta:meta])* |
| 318 |
$Vis:vis struct $StructName:ident $(<$OwnerLifetime:lifetime>)? { |
| 319 |
owner: $Owner:ty, |
| 320 |
|
| 321 |
#[$Covariance:ident] |
| 322 |
dependent: $Dependent:ident, |
| 323 |
} |
| 324 |
|
| 325 |
$(impl {$($AutomaticDerive:ident),*})? |
| 326 |
) => { |
| 327 |
#[repr(transparent)] |
| 328 |
$(#[$StructMeta])* |
| 329 |
$Vis struct $StructName $(<$OwnerLifetime>)? { |
| 330 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell< |
| 331 |
$StructName$(<$OwnerLifetime>)?, |
| 332 |
$Owner, |
| 333 |
$Dependent<'static> |
| 334 |
>, |
| 335 |
|
| 336 |
$(owner_marker: $crate::_covariant_owner_marker!($Covariance, $OwnerLifetime) ,)? |
| 337 |
} |
| 338 |
|
| 339 |
impl $(<$OwnerLifetime>)? $StructName $(<$OwnerLifetime>)? { |
| 340 |
$Vis fn new( |
| 341 |
owner: $Owner, |
| 342 |
dependent_builder: impl for<'_q> FnOnce(&'_q $Owner) -> $Dependent<'_q> |
| 343 |
) -> Self { |
| 344 |
use core::ptr::NonNull; |
| 345 |
|
| 346 |
unsafe { |
| 347 |
// All this has to happen here, because there is not good way |
| 348 |
// of passing the appropriate logic into UnsafeSelfCell::new |
| 349 |
// short of assuming Dependent<'static> is the same as |
| 350 |
// Dependent<'_q>, which I'm not confident is safe. |
| 351 |
|
| 352 |
// For this API to be safe there has to be no safe way to |
| 353 |
// capture additional references in `dependent_builder` and then |
| 354 |
// return them as part of Dependent. Eg. it should be impossible |
| 355 |
// to express: '_q should outlive 'x here `fn |
| 356 |
// bad<'_q>(outside_ref: &'_q String) -> impl for<'x> FnOnce(&'x |
| 357 |
// Owner) -> Dependent<'x>`. |
| 358 |
|
| 359 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 360 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 361 |
|
| 362 |
let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
| 363 |
assert!(layout.size() != 0); |
| 364 |
|
| 365 |
let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
| 366 |
|
| 367 |
let mut joined_ptr = core::mem::transmute::<NonNull<u8>, NonNull<JoinedCell>>( |
| 368 |
joined_void_ptr |
| 369 |
); |
| 370 |
|
| 371 |
let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
| 372 |
|
| 373 |
// Move owner into newly allocated space. |
| 374 |
owner_ptr.write(owner); |
| 375 |
|
| 376 |
// Drop guard that cleans up should building the dependent panic. |
| 377 |
let drop_guard = |
| 378 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 379 |
|
| 380 |
// Initialize dependent with owner reference in final place. |
| 381 |
dependent_ptr.write(dependent_builder(&*owner_ptr)); |
| 382 |
core::mem::forget(drop_guard); |
| 383 |
|
| 384 |
Self { |
| 385 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 386 |
joined_void_ptr, |
| 387 |
), |
| 388 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
$Vis fn try_new<Err>( |
| 394 |
owner: $Owner, |
| 395 |
dependent_builder: |
| 396 |
impl for<'_q> FnOnce(&'_q $Owner) -> core::result::Result<$Dependent<'_q>, Err> |
| 397 |
) -> core::result::Result<Self, Err> { |
| 398 |
use core::ptr::NonNull; |
| 399 |
|
| 400 |
unsafe { |
| 401 |
// See fn new for more explanation. |
| 402 |
|
| 403 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 404 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 405 |
|
| 406 |
let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
| 407 |
assert!(layout.size() != 0); |
| 408 |
|
| 409 |
let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
| 410 |
|
| 411 |
let mut joined_ptr = core::mem::transmute::<NonNull<u8>, NonNull<JoinedCell>>( |
| 412 |
joined_void_ptr |
| 413 |
); |
| 414 |
|
| 415 |
let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
| 416 |
|
| 417 |
// Move owner into newly allocated space. |
| 418 |
owner_ptr.write(owner); |
| 419 |
|
| 420 |
// Drop guard that cleans up should building the dependent panic. |
| 421 |
let mut drop_guard = |
| 422 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 423 |
|
| 424 |
match dependent_builder(&*owner_ptr) { |
| 425 |
Ok(dependent) => { |
| 426 |
dependent_ptr.write(dependent); |
| 427 |
core::mem::forget(drop_guard); |
| 428 |
|
| 429 |
Ok(Self { |
| 430 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 431 |
joined_void_ptr, |
| 432 |
), |
| 433 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 434 |
}) |
| 435 |
} |
| 436 |
Err(err) => Err(err) |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
$Vis fn try_new_or_recover<Err>( |
| 442 |
owner: $Owner, |
| 443 |
dependent_builder: |
| 444 |
impl for<'_q> FnOnce(&'_q $Owner) -> core::result::Result<$Dependent<'_q>, Err> |
| 445 |
) -> core::result::Result<Self, ($Owner, Err)> { |
| 446 |
use core::ptr::NonNull; |
| 447 |
|
| 448 |
unsafe { |
| 449 |
// See fn new for more explanation. |
| 450 |
|
| 451 |
type JoinedCell<'_q $(, $OwnerLifetime)?> = |
| 452 |
$crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
| 453 |
|
| 454 |
let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
| 455 |
assert!(layout.size() != 0); |
| 456 |
|
| 457 |
let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
| 458 |
|
| 459 |
let mut joined_ptr = core::mem::transmute::<NonNull<u8>, NonNull<JoinedCell>>( |
| 460 |
joined_void_ptr |
| 461 |
); |
| 462 |
|
| 463 |
let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
| 464 |
|
| 465 |
// Move owner into newly allocated space. |
| 466 |
owner_ptr.write(owner); |
| 467 |
|
| 468 |
// Drop guard that cleans up should building the dependent panic. |
| 469 |
let mut drop_guard = |
| 470 |
$crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
| 471 |
|
| 472 |
match dependent_builder(&*owner_ptr) { |
| 473 |
Ok(dependent) => { |
| 474 |
dependent_ptr.write(dependent); |
| 475 |
core::mem::forget(drop_guard); |
| 476 |
|
| 477 |
Ok(Self { |
| 478 |
unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
| 479 |
joined_void_ptr, |
| 480 |
), |
| 481 |
$(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
| 482 |
}) |
| 483 |
} |
| 484 |
Err(err) => { |
| 485 |
// In contrast to into_owner ptr::read, here no dependent |
| 486 |
// ever existed in this function and so we are sure its |
| 487 |
// drop impl can't access owner after the read. |
| 488 |
// And err can't return a reference to owner. |
| 489 |
let owner_on_err = core::ptr::read(owner_ptr); |
| 490 |
|
| 491 |
// Allowing drop_guard to finish would let it double free owner. |
| 492 |
// So we dealloc the JoinedCell here manually. |
| 493 |
core::mem::forget(drop_guard); |
| 494 |
$crate::alloc::alloc::dealloc(joined_void_ptr.as_ptr(), layout); |
| 495 |
|
| 496 |
Err((owner_on_err, err)) |
| 497 |
} |
| 498 |
} |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
$Vis fn borrow_owner<'_q>(&'_q self) -> &'_q $Owner { |
| 503 |
unsafe { self.unsafe_self_cell.borrow_owner::<$Dependent<'_q>>() } |
| 504 |
} |
| 505 |
|
| 506 |
$Vis fn with_dependent<'outer_fn, Ret>( |
| 507 |
&'outer_fn self, |
| 508 |
func: impl for<'_q> FnOnce(&'_q $Owner, &'outer_fn $Dependent<'_q> |
| 509 |
) -> Ret) -> Ret { |
| 510 |
unsafe { |
| 511 |
func( |
| 512 |
self.unsafe_self_cell.borrow_owner::<$Dependent>(), |
| 513 |
self.unsafe_self_cell.borrow_dependent() |
| 514 |
) |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
$Vis fn with_dependent_mut<'outer_fn, Ret>( |
| 519 |
&'outer_fn mut self, |
| 520 |
func: impl for<'_q> FnOnce(&'_q $Owner, &'outer_fn mut $Dependent<'_q>) -> Ret |
| 521 |
) -> Ret { |
| 522 |
let (owner, dependent) = unsafe { |
| 523 |
self.unsafe_self_cell.borrow_mut() |
| 524 |
}; |
| 525 |
|
| 526 |
func(owner, dependent) |
| 527 |
} |
| 528 |
|
| 529 |
$crate::_covariant_access!($Covariance, $Vis, $Dependent); |
| 530 |
|
| 531 |
$Vis fn into_owner(self) -> $Owner { |
| 532 |
// This is only safe to do with repr(transparent). |
| 533 |
let unsafe_self_cell = unsafe { core::mem::transmute::< |
| 534 |
Self, |
| 535 |
$crate::unsafe_self_cell::UnsafeSelfCell< |
| 536 |
$StructName$(<$OwnerLifetime>)?, |
| 537 |
$Owner, |
| 538 |
$Dependent<'static> |
| 539 |
> |
| 540 |
>(self) }; |
| 541 |
|
| 542 |
let owner = unsafe { unsafe_self_cell.into_owner::<$Dependent>() }; |
| 543 |
|
| 544 |
owner |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
impl $(<$OwnerLifetime>)? Drop for $StructName $(<$OwnerLifetime>)? { |
| 549 |
fn drop(&mut self) { |
| 550 |
unsafe { |
| 551 |
self.unsafe_self_cell.drop_joined::<$Dependent>(); |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
// The user has to choose which traits can and should be automatically |
| 557 |
// implemented for the cell. |
| 558 |
$($( |
| 559 |
$crate::_impl_automatic_derive!($AutomaticDerive, $StructName); |
| 560 |
)*)* |
| 561 |
}; |
| 562 |
} |
| 563 |
|
| 564 |
#[doc(hidden)] |
| 565 |
#[macro_export] |
| 566 |
macro_rules! _covariant_access { |
| 567 |
(covariant, $Vis:vis, $Dependent:ident) => { |
| 568 |
$Vis fn borrow_dependent<'_q>(&'_q self) -> &'_q $Dependent<'_q> { |
| 569 |
fn _assert_covariance<'x: 'y, 'y>(x: $Dependent<'x>) -> $Dependent<'y> { |
| 570 |
// This function only compiles for covariant types. |
| 571 |
x // Change the macro invocation to not_covariant. |
| 572 |
} |
| 573 |
|
| 574 |
unsafe { self.unsafe_self_cell.borrow_dependent() } |
| 575 |
} |
| 576 |
}; |
| 577 |
(not_covariant, $Vis:vis, $Dependent:ident) => { |
| 578 |
// For types that are not covariant it's unsafe to allow |
| 579 |
// returning direct references. |
| 580 |
// For example a lifetime that is too short could be chosen: |
| 581 |
// See https://github.com/Voultapher/self_cell/issues/5 |
| 582 |
}; |
| 583 |
($x:ident, $Vis:vis, $Dependent:ident) => { |
| 584 |
compile_error!("This macro only accepts `covariant` or `not_covariant`"); |
| 585 |
}; |
| 586 |
} |
| 587 |
|
| 588 |
#[doc(hidden)] |
| 589 |
#[macro_export] |
| 590 |
macro_rules! _covariant_owner_marker { |
| 591 |
(covariant, $OwnerLifetime:lifetime) => { |
| 592 |
// Ensure that contravariant owners don't imply covariance |
| 593 |
// over the dependent. See issue https://github.com/Voultapher/self_cell/issues/18 |
| 594 |
core::marker::PhantomData<&$OwnerLifetime ()> |
| 595 |
}; |
| 596 |
(not_covariant, $OwnerLifetime:lifetime) => { |
| 597 |
// See the discussion in https://github.com/Voultapher/self_cell/pull/29 |
| 598 |
// |
| 599 |
// If the dependent is non_covariant, mark the owner as invariant over its |
| 600 |
// lifetime. Otherwise unsound use is possible. |
| 601 |
core::marker::PhantomData<fn(&$OwnerLifetime ()) -> &$OwnerLifetime ()> |
| 602 |
}; |
| 603 |
($x:ident, $OwnerLifetime:lifetime) => { |
| 604 |
compile_error!("This macro only accepts `covariant` or `not_covariant`"); |
| 605 |
}; |
| 606 |
} |
| 607 |
|
| 608 |
#[doc(hidden)] |
| 609 |
#[macro_export] |
| 610 |
macro_rules! _covariant_owner_marker_ctor { |
| 611 |
($OwnerLifetime:lifetime) => { |
| 612 |
// Helper to optionally expand into PhantomData for construction. |
| 613 |
core::marker::PhantomData |
| 614 |
}; |
| 615 |
} |
| 616 |
|
| 617 |
#[doc(hidden)] |
| 618 |
#[macro_export] |
| 619 |
macro_rules! _impl_automatic_derive { |
| 620 |
(Debug, $StructName:ident) => { |
| 621 |
impl core::fmt::Debug for $StructName { |
| 622 |
fn fmt( |
| 623 |
&self, |
| 624 |
fmt: &mut core::fmt::Formatter, |
| 625 |
) -> core::result::Result<(), core::fmt::Error> { |
| 626 |
self.with_dependent(|owner, dependent| { |
| 627 |
fmt.debug_struct(stringify!($StructName)) |
| 628 |
.field("owner", owner) |
| 629 |
.field("dependent", dependent) |
| 630 |
.finish() |
| 631 |
}) |
| 632 |
} |
| 633 |
} |
| 634 |
}; |
| 635 |
(PartialEq, $StructName:ident) => { |
| 636 |
impl core::cmp::PartialEq for $StructName { |
| 637 |
fn eq(&self, other: &Self) -> bool { |
| 638 |
*self.borrow_owner() == *other.borrow_owner() |
| 639 |
} |
| 640 |
} |
| 641 |
}; |
| 642 |
(Eq, $StructName:ident) => { |
| 643 |
// TODO this should only be allowed if owner is Eq. |
| 644 |
impl core::cmp::Eq for $StructName {} |
| 645 |
}; |
| 646 |
(Hash, $StructName:ident) => { |
| 647 |
impl core::hash::Hash for $StructName { |
| 648 |
fn hash<H: core::hash::Hasher>(&self, state: &mut H) { |
| 649 |
self.borrow_owner().hash(state); |
| 650 |
} |
| 651 |
} |
| 652 |
}; |
| 653 |
($x:ident, $StructName:ident) => { |
| 654 |
compile_error!(concat!( |
| 655 |
"No automatic trait impl for trait: ", |
| 656 |
stringify!($x) |
| 657 |
)); |
| 658 |
}; |
| 659 |
} |