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: &'y $Dependent<'x>) -> &'y $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 | /// Constructs a new self-referential struct. |
341 | /// |
342 | /// The provided `owner` will be moved into a heap allocated box. |
343 | /// Followed by construction of the dependent value, by calling |
344 | /// `dependent_builder` with a shared reference to the owner that |
345 | /// remains valid for the lifetime of the constructed struct. |
346 | $Vis fn new( |
347 | owner: $Owner, |
348 | dependent_builder: impl for<'_q> FnOnce(&'_q $Owner) -> $Dependent<'_q> |
349 | ) -> Self { |
350 | use core::ptr::NonNull; |
351 | |
352 | unsafe { |
353 | // All this has to happen here, because there is not good way |
354 | // of passing the appropriate logic into UnsafeSelfCell::new |
355 | // short of assuming Dependent<'static> is the same as |
356 | // Dependent<'_q>, which I'm not confident is safe. |
357 | |
358 | // For this API to be safe there has to be no safe way to |
359 | // capture additional references in `dependent_builder` and then |
360 | // return them as part of Dependent. Eg. it should be impossible |
361 | // to express: '_q should outlive 'x here `fn |
362 | // bad<'_q>(outside_ref: &'_q String) -> impl for<'x> FnOnce(&'x |
363 | // Owner) -> Dependent<'x>`. |
364 | |
365 | type JoinedCell<'_q $(, $OwnerLifetime)?> = |
366 | $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
367 | |
368 | let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
369 | assert!(layout.size() != 0); |
370 | |
371 | let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
372 | |
373 | let mut joined_ptr = joined_void_ptr.cast::<JoinedCell>(); |
374 | |
375 | let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
376 | |
377 | // Move owner into newly allocated space. |
378 | owner_ptr.write(owner); |
379 | |
380 | // Drop guard that cleans up should building the dependent panic. |
381 | let drop_guard = |
382 | $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
383 | |
384 | // Initialize dependent with owner reference in final place. |
385 | dependent_ptr.write(dependent_builder(&*owner_ptr)); |
386 | core::mem::forget(drop_guard); |
387 | |
388 | Self { |
389 | unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
390 | joined_void_ptr, |
391 | ), |
392 | $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
393 | } |
394 | } |
395 | } |
396 | |
397 | /// Tries to create a new structure with a given dependent builder. |
398 | /// |
399 | /// Consumes owner on error. |
400 | $Vis fn try_new<Err>( |
401 | owner: $Owner, |
402 | dependent_builder: |
403 | impl for<'_q> FnOnce(&'_q $Owner) -> core::result::Result<$Dependent<'_q>, Err> |
404 | ) -> core::result::Result<Self, Err> { |
405 | use core::ptr::NonNull; |
406 | |
407 | unsafe { |
408 | // See fn new for more explanation. |
409 | |
410 | type JoinedCell<'_q $(, $OwnerLifetime)?> = |
411 | $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
412 | |
413 | let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
414 | assert!(layout.size() != 0); |
415 | |
416 | let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
417 | |
418 | let mut joined_ptr = joined_void_ptr.cast::<JoinedCell>(); |
419 | |
420 | let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
421 | |
422 | // Move owner into newly allocated space. |
423 | owner_ptr.write(owner); |
424 | |
425 | // Drop guard that cleans up should building the dependent panic. |
426 | let mut drop_guard = |
427 | $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
428 | |
429 | match dependent_builder(&*owner_ptr) { |
430 | Ok(dependent) => { |
431 | dependent_ptr.write(dependent); |
432 | core::mem::forget(drop_guard); |
433 | |
434 | Ok(Self { |
435 | unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
436 | joined_void_ptr, |
437 | ), |
438 | $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
439 | }) |
440 | } |
441 | Err(err) => Err(err) |
442 | } |
443 | } |
444 | } |
445 | |
446 | /// Tries to create a new structure with a given dependent builder. |
447 | /// |
448 | /// Returns owner on error. |
449 | $Vis fn try_new_or_recover<Err>( |
450 | owner: $Owner, |
451 | dependent_builder: |
452 | impl for<'_q> FnOnce(&'_q $Owner) -> core::result::Result<$Dependent<'_q>, Err> |
453 | ) -> core::result::Result<Self, ($Owner, Err)> { |
454 | use core::ptr::NonNull; |
455 | |
456 | unsafe { |
457 | // See fn new for more explanation. |
458 | |
459 | type JoinedCell<'_q $(, $OwnerLifetime)?> = |
460 | $crate::unsafe_self_cell::JoinedCell<$Owner, $Dependent<'_q>>; |
461 | |
462 | let layout = $crate::alloc::alloc::Layout::new::<JoinedCell>(); |
463 | assert!(layout.size() != 0); |
464 | |
465 | let joined_void_ptr = NonNull::new($crate::alloc::alloc::alloc(layout)).unwrap(); |
466 | |
467 | let mut joined_ptr = joined_void_ptr.cast::<JoinedCell>(); |
468 | |
469 | let (owner_ptr, dependent_ptr) = JoinedCell::_field_pointers(joined_ptr.as_ptr()); |
470 | |
471 | // Move owner into newly allocated space. |
472 | owner_ptr.write(owner); |
473 | |
474 | // Drop guard that cleans up should building the dependent panic. |
475 | let mut drop_guard = |
476 | $crate::unsafe_self_cell::OwnerAndCellDropGuard::new(joined_ptr); |
477 | |
478 | match dependent_builder(&*owner_ptr) { |
479 | Ok(dependent) => { |
480 | dependent_ptr.write(dependent); |
481 | core::mem::forget(drop_guard); |
482 | |
483 | Ok(Self { |
484 | unsafe_self_cell: $crate::unsafe_self_cell::UnsafeSelfCell::new( |
485 | joined_void_ptr, |
486 | ), |
487 | $(owner_marker: $crate::_covariant_owner_marker_ctor!($OwnerLifetime) ,)? |
488 | }) |
489 | } |
490 | Err(err) => { |
491 | // In contrast to into_owner ptr::read, here no dependent |
492 | // ever existed in this function and so we are sure its |
493 | // drop impl can't access owner after the read. |
494 | // And err can't return a reference to owner. |
495 | let owner_on_err = core::ptr::read(owner_ptr); |
496 | |
497 | // Allowing drop_guard to finish would let it double free owner. |
498 | // So we dealloc the JoinedCell here manually. |
499 | core::mem::forget(drop_guard); |
500 | $crate::alloc::alloc::dealloc(joined_void_ptr.as_ptr(), layout); |
501 | |
502 | Err((owner_on_err, err)) |
503 | } |
504 | } |
505 | } |
506 | } |
507 | |
508 | /// Borrows owner. |
509 | $Vis fn borrow_owner<'_q>(&'_q self) -> &'_q $Owner { |
510 | unsafe { self.unsafe_self_cell.borrow_owner::<$Dependent<'_q>>() } |
511 | } |
512 | |
513 | /// Calls given closure `func` with a shared reference to dependent. |
514 | $Vis fn with_dependent<'outer_fn, Ret>( |
515 | &'outer_fn self, |
516 | func: impl for<'_q> FnOnce(&'_q $Owner, &'outer_fn $Dependent<'_q> |
517 | ) -> Ret) -> Ret { |
518 | unsafe { |
519 | func( |
520 | self.unsafe_self_cell.borrow_owner::<$Dependent>(), |
521 | self.unsafe_self_cell.borrow_dependent() |
522 | ) |
523 | } |
524 | } |
525 | |
526 | /// Calls given closure `func` with an unique reference to dependent. |
527 | $Vis fn with_dependent_mut<'outer_fn, Ret>( |
528 | &'outer_fn mut self, |
529 | func: impl for<'_q> FnOnce(&'_q $Owner, &'outer_fn mut $Dependent<'_q>) -> Ret |
530 | ) -> Ret { |
531 | let (owner, dependent) = unsafe { |
532 | self.unsafe_self_cell.borrow_mut() |
533 | }; |
534 | |
535 | func(owner, dependent) |
536 | } |
537 | |
538 | $crate::_covariant_access!($Covariance, $Vis, $Dependent); |
539 | |
540 | /// Consumes `self` and returns the the owner. |
541 | $Vis fn into_owner(self) -> $Owner { |
542 | // This is only safe to do with repr(transparent). |
543 | let unsafe_self_cell = unsafe { core::mem::transmute::< |
544 | Self, |
545 | $crate::unsafe_self_cell::UnsafeSelfCell< |
546 | $StructName$(<$OwnerLifetime>)?, |
547 | $Owner, |
548 | $Dependent<'static> |
549 | > |
550 | >(self) }; |
551 | |
552 | let owner = unsafe { unsafe_self_cell.into_owner::<$Dependent>() }; |
553 | |
554 | owner |
555 | } |
556 | } |
557 | |
558 | impl $(<$OwnerLifetime>)? Drop for $StructName $(<$OwnerLifetime>)? { |
559 | fn drop(&mut self) { |
560 | unsafe { |
561 | self.unsafe_self_cell.drop_joined::<$Dependent>(); |
562 | } |
563 | } |
564 | } |
565 | |
566 | // The user has to choose which traits can and should be automatically |
567 | // implemented for the cell. |
568 | $($( |
569 | $crate::_impl_automatic_derive!($AutomaticDerive, $StructName); |
570 | )*)* |
571 | }; |
572 | } |
573 | |
574 | #[doc (hidden)] |
575 | #[macro_export ] |
576 | macro_rules! _covariant_access { |
577 | (covariant, $Vis:vis, $Dependent:ident) => { |
578 | /// Borrows dependent. |
579 | $Vis fn borrow_dependent<'_q>(&'_q self) -> &'_q $Dependent<'_q> { |
580 | fn _assert_covariance<'x: 'y, 'y>(x: &'y $Dependent<'x>) -> &'y $Dependent<'y> { |
581 | // This function only compiles for covariant types. |
582 | x // Change the macro invocation to not_covariant. |
583 | } |
584 | |
585 | unsafe { self.unsafe_self_cell.borrow_dependent() } |
586 | } |
587 | }; |
588 | (not_covariant, $Vis:vis, $Dependent:ident) => { |
589 | // For types that are not covariant it's unsafe to allow |
590 | // returning direct references. |
591 | // For example a lifetime that is too short could be chosen: |
592 | // See https://github.com/Voultapher/self_cell/issues/5 |
593 | }; |
594 | ($x:ident, $Vis:vis, $Dependent:ident) => { |
595 | compile_error!("This macro only accepts `covariant` or `not_covariant`" ); |
596 | }; |
597 | } |
598 | |
599 | #[doc (hidden)] |
600 | #[macro_export ] |
601 | macro_rules! _covariant_owner_marker { |
602 | (covariant, $OwnerLifetime:lifetime) => { |
603 | // Ensure that contravariant owners don't imply covariance |
604 | // over the dependent. See issue https://github.com/Voultapher/self_cell/issues/18 |
605 | core::marker::PhantomData<&$OwnerLifetime ()> |
606 | }; |
607 | (not_covariant, $OwnerLifetime:lifetime) => { |
608 | // See the discussion in https://github.com/Voultapher/self_cell/pull/29 |
609 | // |
610 | // If the dependent is non_covariant, mark the owner as invariant over its |
611 | // lifetime. Otherwise unsound use is possible. |
612 | core::marker::PhantomData<fn(&$OwnerLifetime ()) -> &$OwnerLifetime ()> |
613 | }; |
614 | ($x:ident, $OwnerLifetime:lifetime) => { |
615 | compile_error!("This macro only accepts `covariant` or `not_covariant`" ); |
616 | }; |
617 | } |
618 | |
619 | #[doc (hidden)] |
620 | #[macro_export ] |
621 | macro_rules! _covariant_owner_marker_ctor { |
622 | ($OwnerLifetime:lifetime) => { |
623 | // Helper to optionally expand into PhantomData for construction. |
624 | core::marker::PhantomData |
625 | }; |
626 | } |
627 | |
628 | #[doc (hidden)] |
629 | #[macro_export ] |
630 | macro_rules! _impl_automatic_derive { |
631 | (Debug, $StructName:ident) => { |
632 | impl core::fmt::Debug for $StructName { |
633 | fn fmt( |
634 | &self, |
635 | fmt: &mut core::fmt::Formatter, |
636 | ) -> core::result::Result<(), core::fmt::Error> { |
637 | self.with_dependent(|owner, dependent| { |
638 | fmt.debug_struct(stringify!($StructName)) |
639 | .field("owner" , owner) |
640 | .field("dependent" , dependent) |
641 | .finish() |
642 | }) |
643 | } |
644 | } |
645 | }; |
646 | (PartialEq, $StructName:ident) => { |
647 | impl core::cmp::PartialEq for $StructName { |
648 | fn eq(&self, other: &Self) -> bool { |
649 | *self.borrow_owner() == *other.borrow_owner() |
650 | } |
651 | } |
652 | }; |
653 | (Eq, $StructName:ident) => { |
654 | // TODO this should only be allowed if owner is Eq. |
655 | impl core::cmp::Eq for $StructName {} |
656 | }; |
657 | (Hash, $StructName:ident) => { |
658 | impl core::hash::Hash for $StructName { |
659 | fn hash<H: core::hash::Hasher>(&self, state: &mut H) { |
660 | self.borrow_owner().hash(state); |
661 | } |
662 | } |
663 | }; |
664 | ($x:ident, $StructName:ident) => { |
665 | compile_error!(concat!( |
666 | "No automatic trait impl for trait: " , |
667 | stringify!($x) |
668 | )); |
669 | }; |
670 | } |
671 | |