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