selfie 0.0.3

Experimental, macro-free and allocation-free self-referential structs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! This internal module contains the implementation details for Selfie and SelfieMut.
//!
//! **Do not make any change here without adding new regression, compile-fail and/or MIRI tests!**
//!
//! I do not trust myself in here, and neither should you.

#![allow(unsafe_code)] // I'll be glad to remove this the day self-referential structs can be implemented in Safe Rust

use crate::refs::*;
use crate::utils::*;
use crate::SelfieError;
use core::ops::DerefMut;
use core::pin::Pin;
use stable_deref_trait::{CloneStableDeref, StableDeref};

/// A self-referential struct with a shared reference (`R`) to an object owned by a pinned pointer (`P`).
///
/// If you need a self-referential struct with an exclusive (mutable) reference to the data behind `P`, see [`SelfieMut`].
///
/// This struct is a simple wrapper containing both the pinned pointer `P` and the shared reference to it `R` alongside it.
/// It does not perform any additional kind of boxing or allocation.
///
/// A [`Selfie`] is constructed by using the [`new`](Selfie::new) constructor, which requires the pinned pointer `P`,
/// and a function to create the reference type `R` from a shared reference to the data behind `P`.
///
/// Because `R` references the data behind `P` for as long as this struct exists, the data behind `P`
/// has to be considered to be borrowed for the lifetime of the [`Selfie`].
///
/// Therefore, you can only access the data behind `P` through shared references (`&T`) using [`owned`](Selfie::owned), or by
/// using [`into_owned`](Selfie::into_owned), which drops `R` and returns `P` as it was given to
/// the constructor.
///
/// Note that the referential type `R` is not accessible outside of the [`Selfie`] either, and can
/// only be accessed by temporarily borrowing it through the [`with_referential`](Selfie::with_referential)
/// and [`with_referential_mut`](Selfie::with_referential_mut) methods, which hide its true lifetime.
///
/// This is done because `R` actually has a self-referential lifetime, which cannot be named
/// in Rust's current lifetime system.
///
/// Also because of the non-nameable self-referential lifetime, `R` is not the referential type
/// itself, but a stand-in that implements [`RefType`] (e.g. [`Ref<T>`](Ref) instead of `&T`).
/// See the [`refs`](crate::refs) module for some reference type stand-ins this library provides, or see
/// the [`RefType`] trait documentation for how to implement your own.
///
/// # Example
///
/// This example stores both an owned `String` and a [`str`] slice pointing
/// into it.
///
/// ```
/// use core::pin::Pin;
/// use selfie::{refs::Ref, Selfie};
///
/// let data: Pin<String> = Pin::new("Hello, world!".to_owned());
/// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |s| &s[0..5]);
///
/// assert_eq!("Hello", selfie.with_referential(|r| *r));
/// assert_eq!("Hello, world!", selfie.owned());
/// ```
pub struct Selfie<'a, P, R>
where
    P: 'a,
    R: for<'this> RefType<'this>,
{
    // SAFETY: enforce drop order!
    // SAFETY: Note that Ref's lifetime isn't actually ever 'a: it is the unnameable 'this instead.
    // Marking it as 'a is a trick to be able to store it and still name the whole type.
    // It is *absolutely* unsound to ever use this field as 'a, it should immediately be casted
    // to and from 'this instead.
    referential: <R as RefType<'a>>::Ref,
    owned: Pin<P>,
}

impl<'a, P, R> Selfie<'a, P, R>
where
    P: StableDeref + 'a,
    R: for<'this> RefType<'this>,
    P::Target: 'a,
{
    /// Creates a new [`Selfie`] from a pinned pointer `P`, and a closure to create the reference
    /// type `R` from a shared reference to the data behind `P`.
    ///
    /// Note the closure cannot expect to be called with a specific lifetime, as it will handle
    /// the unnameable `'this` lifetime instead.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Ref;
    /// use selfie::Selfie;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |s| &s[0..5]);
    ///
    /// // The selfie now contains both the String buffer and a subslice to "Hello"
    /// assert_eq!("Hello", selfie.with_referential(|r| *r));
    /// ```
    #[inline]
    pub fn new<F>(owned: Pin<P>, handler: F) -> Self
    where
        F: for<'this> FnOnce(&'this P::Target) -> <R as RefType<'this>>::Ref,
    {
        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();

        Self {
            referential: handler(detached),
            owned,
        }
    }

    /// Creates a new [`Selfie`] from a pinned pointer `P`, and a fallible closure to create the
    /// reference type `R` from a shared reference to the data behind `P`.
    ///
    /// Note the closure cannot expect to be called with a specific lifetime, as it will handle
    /// the unnameable `'this` lifetime instead.
    ///
    /// # Errors
    ///
    /// The closure can return a [`Result`] containing either the referential type, or any error type.
    /// If the closure returns an `Err`, it will be returned in a [`SelfieError`] alongside the original
    /// owned pointer type.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Ref;
    /// use selfie::{Selfie, SelfieError};
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Result<Selfie<String, Ref<str>>, SelfieError<String, ()>>
    ///     = Selfie::try_new(data, |s| Ok(&s[0..5]));
    ///
    /// assert_eq!("Hello", selfie.unwrap().with_referential(|r| *r));
    /// ```
    #[inline]
    pub fn try_new<E, F>(owned: Pin<P>, handler: F) -> Result<Self, SelfieError<P, E>>
    where
        F: for<'this> FnOnce(&'this P::Target) -> Result<<R as RefType<'this>>::Ref, E>,
    {
        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();

        let referential = match handler(detached) {
            Ok(r) => r,
            Err(error) => return Err(SelfieError { owned, error }),
        };

        Ok(Self { referential, owned })
    }

    /// Returns a shared reference to the owned type by de-referencing `P`.
    ///
    /// # Example
    ///
    /// ```
    /// use core::pin::Pin;
    /// use selfie::{refs::Ref, Selfie};
    ///
    /// let data: Pin<Box<u32>> = Box::pin(42);
    /// let selfie: Selfie<Box<u32>, Ref<u32>> = Selfie::new(data, |i| i);
    ///
    /// assert_eq!(&42, selfie.owned());
    /// ```
    #[inline]
    pub fn owned(&self) -> &P::Target {
        self.owned.as_ref().get_ref()
    }

    /// Performs an operation borrowing the referential type `R`, and returns its result.
    ///
    /// # Example
    ///
    /// ```
    /// use core::pin::Pin;
    /// use selfie::{refs::Ref, Selfie};
    ///
    /// let data: Pin<Box<u32>> = Box::pin(42);
    /// let selfie: Selfie<Box<u32>, Ref<u32>> = Selfie::new(data, |i| i);
    ///
    /// assert_eq!(50, selfie.with_referential(|r| *r + 8));
    /// ```
    #[inline]
    pub fn with_referential<'s, F, T>(&'s self, handler: F) -> T
    where
        F: for<'this> FnOnce(&'s <R as RefType<'this>>::Ref) -> T,
    {
        // SAFETY: Down-casting is safe here, because Ref is actually 's, not 'a
        let referential = unsafe { downcast_ref::<'s, 'a, R>(&self.referential) };
        handler(referential)
    }

    /// Performs an operation mutably borrowing the referential type `R`, and returns its result.
    ///
    /// Note that this operation *cannot* mutably access the data behind `P`, it only mutates the
    /// referential type `R` itself.
    ///
    /// # Example
    ///
    /// ```
    /// use core::pin::Pin;
    /// use selfie::{refs::Ref, Selfie};
    ///
    /// let data: Pin<String> = Pin::new("Hello, world!".to_owned());
    /// let mut selfie: Selfie<String, Ref<str>> = Selfie::new(data, |s| &s[0..5]);
    ///
    /// assert_eq!("Hello", selfie.with_referential(|r| *r));
    /// assert_eq!("Hello, world!", selfie.owned());
    ///
    /// selfie.with_referential_mut(|s| *s = &s[0..2]);
    ///
    /// assert_eq!("He", selfie.with_referential(|r| *r));
    /// assert_eq!("Hello, world!", selfie.owned());
    #[inline]
    pub fn with_referential_mut<'s, F, T>(&'s mut self, handler: F) -> T
    where
        F: for<'this> FnOnce(&'s mut <R as RefType<'this>>::Ref) -> T,
    {
        // SAFETY: Down-casting is safe here, because Ref is actually 's, not 'a
        let referential = unsafe { downcast_mut::<'s, 'a, R>(&mut self.referential) };
        handler(referential)
    }

    /// Unwraps the [`Selfie`] by dropping the reference type `R`, and returning the owned pointer
    /// type `P`, as it was passed to the constructor.
    ///
    /// # Example
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Ref;
    /// use selfie::Selfie;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |str| &str[0..5]);
    ///
    /// let original_data: Pin<String> = selfie.into_owned();
    /// assert_eq!("Hello, world!", original_data.as_ref().get_ref());
    /// ```
    #[inline]
    pub fn into_owned(self) -> Pin<P> {
        self.owned
    }

    /// Creates a new [`Selfie`] by consuming this [`Selfie`]'s reference type `R` and producing another
    /// (`R2`), using a given closure.
    ///
    /// The owned pointer type `P` is left unchanged, and a shared reference to the data behind it
    /// is also provided to the closure for convenience.
    ///
    /// This method consumes the [`Selfie`]. If you need to keep it intact, see
    /// [`map_cloned`](Selfie::map_cloned).
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Ref;
    /// use selfie::Selfie;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |str| &str[0..5]);
    /// assert_eq!("Hello", selfie.with_referential(|r| *r));
    ///
    /// let selfie = selfie.map::<Ref<str>, _>(|str, _| &str[3..]);
    /// assert_eq!("lo", selfie.with_referential(|r| *r));
    ///
    /// let selfie: Selfie<String, Ref<str>> = selfie.map(|_, owned| &owned[7..]);
    /// assert_eq!("world!", selfie.with_referential(|r| *r));
    /// ```
    #[inline]
    pub fn map<R2: for<'this> RefType<'this>, F>(self, mapper: F) -> Selfie<'a, P, R2>
    where
        F: for<'this> FnOnce(
            <R as RefType<'this>>::Ref,
            &'this P::Target,
        ) -> <R2 as RefType<'this>>::Ref,
    {
        // SAFETY: here we break the lifetime guarantees: we must be very careful to not drop owned before referential
        let Self { owned, referential } = self;

        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();
        let referential = mapper(referential, detached);

        Selfie { owned, referential }
    }

    /// Creates a new [`Selfie`] by consuming this [`Selfie`]'s reference type `R` and producing another
    /// (`R2`), using a given fallible closure.
    ///
    /// The owned pointer type `P` is left unchanged, and a shared reference to the data behind it
    /// is also provided to the closure for convenience.
    ///
    /// This method consumes the [`Selfie`]. If you need to keep it intact, see
    /// [`try_map_cloned`](Selfie::try_map_cloned).
    ///
    /// # Errors
    ///
    /// The closure can return a [`Result`] containing either the referential type, or any error type.
    /// If the closure returns an `Err`, it will be returned in a [`SelfieError`] alongside the original
    /// owned pointer type.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Ref;
    /// use selfie::{Selfie, SelfieError};
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |str| &str[0..5]);
    /// assert_eq!("Hello", selfie.with_referential(|r| *r));
    ///
    /// let selfie = selfie.try_map::<Ref<str>, (), _>(|str, _| Ok(&str[3..])).unwrap();
    /// assert_eq!("lo", selfie.with_referential(|r| *r));
    ///
    /// let selfie: Result<Selfie<String, Ref<str>>, SelfieError<String,()>> = selfie.try_map(|_, owned| Ok(&owned[7..]));
    /// assert_eq!("world!", selfie.unwrap().with_referential(|r| *r));
    /// ```
    #[inline]
    pub fn try_map<R2: for<'this> RefType<'this>, E, F>(
        self,
        mapper: F,
    ) -> Result<Selfie<'a, P, R2>, SelfieError<P, E>>
    where
        F: for<'this> FnOnce(
            <R as RefType<'this>>::Ref,
            &'this P::Target,
        ) -> Result<<R2 as RefType<'this>>::Ref, E>,
    {
        // SAFETY: here we break the lifetime guarantees: we must be very careful to not drop owned before referential
        let Self { owned, referential } = self;

        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();
        let referential = match mapper(referential, detached) {
            Ok(r) => r,
            Err(error) => return Err(SelfieError { owned, error }),
        };

        Ok(Selfie { owned, referential })
    }

    /// Creates a new [`Selfie`] by cloning this [`Selfie`]'s reference pointer `P` and producing
    /// a new reference (`R2`), using a given closure.
    ///
    /// The owned pointer type `P` needs to be [`CloneStableDeref`](stable_deref_trait::CloneStableDeref),
    /// as only the pointer itself is going to be cloned, not the data behind it. Both the current
    /// reference `R` and the new `R2` will refer to the data behind `P`.
    ///
    /// This method keeps the original [`Selfie`] unchanged, as only its owned pointer is cloned.
    ///
    /// # Example
    ///
    /// ```
    /// use std::rc::Rc;
    /// use selfie::refs::Ref;
    /// use selfie::Selfie;
    ///
    /// let data = Rc::pin("Hello, world!".to_owned());
    /// let selfie: Selfie<Rc<String>, Ref<str>> = Selfie::new(data, |str| &str[0..5]);
    /// selfie.with_referential(|s| assert_eq!("Hello", *s));
    ///
    /// let second_selfie = selfie.map_cloned::<Ref<str>, _>(|str, _| &str[3..]);
    /// second_selfie.with_referential(|s| assert_eq!("lo", *s));
    /// selfie.with_referential(|s| assert_eq!("Hello", *s)); // Old one still works
    ///
    /// drop(selfie);
    /// second_selfie.with_referential(|s| assert_eq!("lo", *s)); // New one still works
    /// ```
    #[inline]
    pub fn map_cloned<R2: for<'this> RefType<'this>, F>(&self, mapper: F) -> Selfie<'a, P, R2>
    where
        F: for<'this> FnOnce(
            &<R as RefType<'this>>::Ref,
            &'this P::Target,
        ) -> <R2 as RefType<'this>>::Ref,
        P: CloneStableDeref,
    {
        let owned = self.owned.clone();

        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();
        let referential = mapper(&self.referential, detached);

        Selfie { owned, referential }
    }

    /// Creates a new [`Selfie`] by cloning this [`Selfie`]'s reference pointer `P` and producing
    /// a new reference (`R2`), using a given fallible closure.
    ///
    /// The owned pointer type `P` needs to be [`CloneStableDeref`](stable_deref_trait::CloneStableDeref),
    /// as only the pointer itself is going to be cloned, not the data behind it. Both the current
    /// reference `R` and the new `R2` will refer to the data behind `P`.
    ///
    /// This method keeps the original [`Selfie`] unchanged, as only its owned pointer is cloned.
    ///
    /// # Errors
    ///
    /// The closure can return a [`Result`] containing either the referential type, or any error type.
    /// If the closure returns an `Err`, it will be returned right away.
    ///
    /// # Example
    ///
    /// ```
    /// use std::rc::Rc;
    /// use selfie::refs::Ref;
    /// use selfie::Selfie;
    ///
    /// let data = Rc::pin("Hello, world!".to_owned());
    /// let selfie: Selfie<Rc<String>, Ref<str>> = Selfie::new(data, |str| &str[0..5]);
    /// selfie.with_referential(|s| assert_eq!("Hello", *s));
    ///
    /// let second_selfie = selfie.try_map_cloned::<Ref<str>, (), _>(|str, _| Ok(&str[3..])).unwrap();
    /// second_selfie.with_referential(|s| assert_eq!("lo", *s));
    /// selfie.with_referential(|s| assert_eq!("Hello", *s)); // Old one still works
    ///
    /// drop(selfie);
    /// second_selfie.with_referential(|s| assert_eq!("lo", *s)); // New one still works
    /// ```
    #[inline]
    pub fn try_map_cloned<R2: for<'this> RefType<'this>, E, F>(
        &self,
        mapper: F,
    ) -> Result<Selfie<'a, P, R2>, E>
    where
        F: for<'this> FnOnce(
            &<R as RefType<'this>>::Ref,
            &'this P::Target,
        ) -> Result<<R2 as RefType<'this>>::Ref, E>,
        P: CloneStableDeref,
    {
        let owned = self.owned.clone();

        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime(owned.as_ref()) }.get_ref();
        let referential = mapper(&self.referential, detached)?;

        Ok(Selfie { owned, referential })
    }
}

/// A self-referential struct with a mutable reference (`R`) to an object owned by a pinned pointer (`P`).
///
/// If you only need a self-referential struct with an shared reference to the data behind `P`, see [`Selfie`].
///
/// This struct is a simple wrapper containing both the pinned pointer `P` and the mutable reference to it `R` alongside it.
/// It does not perform any additional kind of boxing or allocation.
///
/// A [`SelfieMut`] is constructed by using the [`new`](SelfieMut::new) constructor, which requires the pinned pointer `P`,
/// and a function to create the reference type `R` from a pinned mutable reference to the data behind `P`.
///
/// Because `R` references the data behind `P` for as long as this struct exists, the data behind `P`
/// has to be considered to be exclusively borrowed for the lifetime of the [`SelfieMut`].
///
/// Therefore, you cannot access the data behind `P` at all, until
/// using [`into_owned`](SelfieMut::into_owned), which drops `R` and returns `P` as it was given to
/// the constructor.
///
/// Note that the referential type `R` is not accessible outside of the [`Selfie`] either, and can
/// only be accessed by temporarily borrowing it through the [`with_referential`](SelfieMut::with_referential)
/// and [`with_referential_mut`](SelfieMut::with_referential_mut) methods, which hide its true lifetime.
///
/// This is done because `R` actually has a self-referential lifetime, which cannot be named
/// in Rust's current lifetime system.
///
/// Also because of the non-nameable self-referential lifetime, `R` is not the referential type
/// itself, but a stand-in that implements [`RefType`] (e.g. [`Ref<T>`](Ref) instead of `&T`).
/// See the [`refs`](crate::refs) module for some reference type stand-ins this library provides, or see
/// the [`RefType`] trait documentation for how to implement your own.
///
/// # Example
///
/// This example stores both an owned `String` and a [`str`] slice pointing
/// into it.
///
/// ```
/// use core::pin::Pin;
/// use selfie::{refs::Ref, Selfie};
///
/// let data: Pin<String> = Pin::new("Hello, world!".to_owned());
/// let selfie: Selfie<String, Ref<str>> = Selfie::new(data, |s| &s[0..5]);
///
/// assert_eq!("Hello", selfie.with_referential(|r| *r));
/// assert_eq!("Hello, world!", selfie.owned());
/// ```
pub struct SelfieMut<'a, P, R>
where
    P: 'a,
    R: for<'this> RefType<'this>,
{
    // SAFETY: enforce drop order!
    referential: <R as RefType<'a>>::Ref,
    owned: Pin<P>,
}

impl<'a, P, R> SelfieMut<'a, P, R>
where
    P: StableDeref + DerefMut + 'a,
    R: for<'this> RefType<'this>,
{
    /// Creates a new [`SelfieMut`] from a pinned pointer `P`, and a closure to create the reference
    /// type `R` from a pinned, exclusive reference to the data behind `P`.
    ///
    /// Note the closure cannot expect to be called with a specific lifetime, as it will handle
    /// the unnameable `'this` lifetime instead.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Mut;
    /// use selfie::SelfieMut;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: SelfieMut<String, Mut<str>> = SelfieMut::new(data, |s| &mut Pin::into_inner(s)[0..5]);
    ///
    /// // The selfie now contains both the String buffer and a subslice to "Hello"
    /// selfie.with_referential(|r| assert_eq!("Hello", *r));
    /// ```
    pub fn new<F>(mut owned: Pin<P>, handler: F) -> Self
    where
        F: for<'this> FnOnce(Pin<&'this mut P::Target>) -> <R as RefType<'this>>::Ref,
    {
        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime_mut(owned.as_mut()) };

        Self {
            referential: handler(detached),
            owned,
        }
    }

    /// Creates a new [`SelfieMut`] from a pinned pointer `P`, and a fallible closure to create the
    /// reference type `R` from a pinned, exclusive reference to the data behind `P`.
    ///
    /// Note the closure cannot expect to be called with a specific lifetime, as it will handle
    /// the unnameable `'this` lifetime instead.
    ///
    /// # Errors
    ///
    /// The closure can return a [`Result`] containing either the referential type, or any error type.
    /// If the closure returns an `Err`, it will be returned in a [`SelfieError`] alongside the original
    /// owned pointer type.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Mut;
    /// use selfie::{SelfieError, SelfieMut};
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: Result<SelfieMut<String, Mut<str>>, SelfieError<String, ()>> =
    ///     SelfieMut::try_new(data, |s| Ok(&mut Pin::into_inner(s)[0..5]));
    ///
    /// selfie.unwrap().with_referential(|r| assert_eq!("Hello", *r));
    /// ```
    #[inline]
    pub fn try_new<E, F>(mut owned: Pin<P>, handler: F) -> Result<Self, SelfieError<P, E>>
    where
        F: for<'this> FnOnce(Pin<&'this mut P::Target>) -> Result<<R as RefType<'this>>::Ref, E>,
    {
        // SAFETY: This type does not expose anything that could expose referential longer than owned exists
        let detached = unsafe { detach_lifetime_mut(owned.as_mut()) };

        let referential = match handler(detached) {
            Ok(r) => r,
            Err(error) => return Err(SelfieError { owned, error }),
        };

        Ok(Self { referential, owned })
    }

    /// Performs an operation borrowing the referential type `R`, and returns its result.
    ///
    /// # Example
    ///
    /// ```
    /// use core::pin::Pin;
    /// use selfie::{refs::Mut, SelfieMut};
    ///
    /// let data: Pin<Box<u32>> = Box::pin(42);
    /// let selfie: SelfieMut<Box<u32>, Mut<u32>> = SelfieMut::new(data, |i| Pin::into_inner(i));
    ///
    /// assert_eq!(50, selfie.with_referential(|r| **r + 8));
    /// ```
    #[inline]
    pub fn with_referential<'s, F, T>(&'s self, handler: F) -> T
    where
        F: for<'this> FnOnce(&'s <R as RefType<'this>>::Ref) -> T,
    {
        // SAFETY: Down-casting is safe here, because Ref is actually 's, not 'a
        let referential = unsafe { downcast_ref::<'s, 'a, R>(&self.referential) };
        handler(referential)
    }

    /// Performs an operation mutably borrowing the referential type `R`, and returns its result.
    ///
    /// Note that this operation *can* mutably access the data behind `P`.
    ///
    /// # Example
    ///
    /// ```
    /// use core::pin::Pin;
    /// use selfie::{refs::Mut, SelfieMut};
    ///
    /// let data: Pin<String> = Pin::new("Hello, world!".to_owned());
    /// let mut selfie: SelfieMut<String, Mut<str>> = SelfieMut::new(data, |s| &mut Pin::into_inner(s)[0..5]);
    ///
    /// selfie.with_referential_mut(|s| s.make_ascii_uppercase());
    /// selfie.with_referential(|s| assert_eq!("HELLO", *s));
    ///
    /// let data = Pin::into_inner(selfie.into_owned());
    /// assert_eq!("HELLO, world!", &data);
    /// ```
    #[inline]
    pub fn with_referential_mut<'s, F, T>(&'s mut self, handler: F) -> T
    where
        F: for<'this> FnOnce(&'s mut <R as RefType<'this>>::Ref) -> T,
    {
        // SAFETY: Down-casting is safe here, because Ref is actually 's, not 'a
        let referential = unsafe { downcast_mut::<'s, 'a, R>(&mut self.referential) };
        handler(referential)
    }

    /// Unwraps the [`SelfieMut`] by dropping the reference type `R`, and returning the owned pointer
    /// type `P`, as it was passed to the constructor.
    ///
    /// # Example
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Mut;
    /// use selfie::SelfieMut;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: SelfieMut<String, Mut<str>> = SelfieMut::new(data, |str| &mut Pin::into_inner(str)[0..5]);
    ///
    /// let original_data: Pin<String> = selfie.into_owned();
    /// assert_eq!("Hello, world!", original_data.as_ref().get_ref());
    /// ```
    #[inline]
    pub fn into_owned(self) -> Pin<P> {
        self.owned
    }

    /// Creates a new [`SelfieMut`] by consuming this [`SelfieMut`]'s reference type `R` and producing another
    /// (`R2`), using a given closure.
    ///
    /// The owned pointer type `P` is left unchanged.
    ///
    /// This method consumes the [`SelfieMut`].
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Mut;
    /// use selfie::SelfieMut;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: SelfieMut<String, Mut<str>> = SelfieMut::new(data, |str| &mut Pin::into_inner(str)[0..5]);
    /// selfie.with_referential(|s| assert_eq!("Hello", *s));
    ///
    /// let selfie = selfie.map::<Mut<str>, _>(|str, _| &mut str[3..]);
    /// selfie.with_referential(|s| assert_eq!("lo", *s));
    /// ```
    #[inline]
    pub fn map<R2: for<'this> RefType<'this>, F>(self, mapper: F) -> Selfie<'a, P, R2>
    where
        F: for<'this> FnOnce(
            <R as RefType<'this>>::Ref,
            &'this (), // This is needed to constrain the lifetime TODO: find a way to remove this
        ) -> <R2 as RefType<'this>>::Ref,
    {
        // SAFETY: here we break the lifetime guarantees: we must be very careful to not drop owned before referential
        let Self { owned, referential } = self;

        let referential = mapper(referential, &());

        Selfie { owned, referential }
    }

    /// Creates a new [`SelfieMut`] by consuming this [`SelfieMut`]'s reference type `R` and producing another
    /// (`R2`), using a given fallible closure.
    ///
    /// The owned pointer type `P` is left unchanged.
    ///
    /// This method consumes the [`SelfieMut`].
    ///
    /// # Errors
    ///
    /// The closure can return a [`Result`] containing either the referential type, or any error type.
    /// If the closure returns an `Err`, it will be returned in a [`SelfieError`] alongside the original
    /// owned pointer type.
    ///
    /// # Example
    ///
    /// ```
    /// use std::pin::Pin;
    /// use selfie::refs::Mut;
    /// use selfie::SelfieMut;
    ///
    /// let data = Pin::new("Hello, world!".to_owned());
    /// let selfie: SelfieMut<String, Mut<str>> = SelfieMut::new(data, |str| &mut Pin::into_inner(str)[0..5]);
    /// selfie.with_referential(|s| assert_eq!("Hello", *s));
    ///
    /// let selfie = selfie.try_map::<Mut<str>, (), _>(|str, _| Ok(&mut str[3..])).unwrap();
    /// selfie.with_referential(|s| assert_eq!("lo", *s));
    /// ```
    #[inline]
    pub fn try_map<R2: for<'this> RefType<'this>, E, F>(
        self,
        mapper: F,
    ) -> Result<Selfie<'a, P, R2>, SelfieError<P, E>>
    where
        F: for<'this> FnOnce(
            <R as RefType<'this>>::Ref,
            &'this (), // This is needed to constrain the lifetime TODO: find a way to remove this
        ) -> Result<<R2 as RefType<'this>>::Ref, E>,
    {
        // SAFETY: here we break the lifetime guarantees: we must be very careful to not drop owned before referential
        let Self { owned, referential } = self;

        let referential = match mapper(referential, &()) {
            Ok(r) => r,
            Err(error) => return Err(SelfieError { owned, error }),
        };

        Ok(Selfie { owned, referential })
    }
}