Skip to main content

pin_init/
__internal.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! This module contains library internal items.
4//!
5//! These items must not be used outside of this crate and the pin-init-internal crate located at
6//! `../internal`.
7
8#![expect(clippy::new_without_default, reason = "private API")]
9
10use core::marker::PhantomPinned;
11use core::ops::Deref;
12
13use super::*;
14
15/// Zero-sized type used to mark a type as invariant.
16///
17/// This is a polyfill for the [unstable type] in the standard library of the same name.
18///
19/// See the [nomicon] for what subtyping is. See also [this table].
20///
21/// [unstable type]: https://doc.rust-lang.org/nightly/std/marker/struct.PhantomInvariant.html
22/// [nomicon]: https://doc.rust-lang.org/nomicon/subtyping.html
23/// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
24#[repr(transparent)]
25pub struct PhantomInvariant<T: ?Sized>(PhantomData<fn(T) -> T>);
26
27impl<T: ?Sized> Clone for PhantomInvariant<T> {
28    #[inline(always)]
29    fn clone(&self) -> Self {
30        *self
31    }
32}
33
34impl<T: ?Sized> Copy for PhantomInvariant<T> {}
35
36impl<T: ?Sized> Default for PhantomInvariant<T> {
37    #[inline(always)]
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl<T: ?Sized> PhantomInvariant<T> {
44    #[inline(always)]
45    pub const fn new() -> Self {
46        Self(PhantomData)
47    }
48}
49
50/// Token type to signify successful initialization.
51///
52/// Can only be constructed via the unsafe [`Self::new`] function. The initializer macros use this
53/// token type to prevent returning `Ok` from an initializer without initializing all fields.
54pub struct InitOk(());
55
56impl InitOk {
57    /// Creates a new token.
58    ///
59    /// # Safety
60    ///
61    /// This function may only be called from the `init!` macro in `../internal/src/init.rs`.
62    #[inline(always)]
63    pub unsafe fn new() -> Self {
64        Self(())
65    }
66}
67
68/// This trait is only implemented via the `#[pin_data]` proc-macro. It is used to facilitate
69/// the pin projections within the initializers.
70///
71/// # Safety
72///
73/// `pin-init` relies on the correctness of the helper functions defined on `PinData`.
74/// Thus, only the `#[pin_data]` can implement this trait.
75#[diagnostic::on_unimplemented(
76    message = "`{Self}` cannot be used with `pin_init!` macro",
77    note = "did you forget to add `#[pin_data]` attribute to the struct?"
78)]
79pub unsafe trait HasPinData {
80    type PinData;
81
82    fn __pin_data(_: InitData<Self>) -> Self::PinData;
83}
84
85/// This trait is automatically implemented for every type.
86///
87/// It aims to provide type inference help; `PATH::__init_data()` would be able to retrieve an
88/// instance of `InitData<PATH<Generics>>` without having to mention the generics explicitly.
89pub trait HasInitData {
90    #[inline]
91    fn __init_data() -> InitData<Self> {
92        InitData(PhantomInvariant::new())
93    }
94}
95
96impl<T: ?Sized> HasInitData for T {}
97
98pub struct InitData<T: ?Sized>(PhantomInvariant<T>);
99
100impl<T: ?Sized> Clone for InitData<T> {
101    #[inline]
102    fn clone(&self) -> Self {
103        *self
104    }
105}
106
107impl<T: ?Sized> Copy for InitData<T> {}
108
109impl<T: ?Sized> InitData<T> {
110    /// Type inference helper function.
111    #[inline(always)]
112    pub fn __make_closure<F, E>(self, f: F) -> F
113    where
114        F: FnOnce(*mut T, Self) -> Result<InitOk, E>,
115    {
116        f
117    }
118
119    #[inline(always)]
120    pub fn __with_lt(self) -> Self {
121        self
122    }
123}
124
125/// Stack initializer helper type. Use [`stack_pin_init`] instead of this primitive.
126///
127/// # Invariants
128///
129/// If `self.is_init` is true, then `self.value` is initialized.
130///
131/// [`stack_pin_init`]: crate::stack_pin_init
132pub struct StackInit<T> {
133    value: MaybeUninit<T>,
134    is_init: bool,
135}
136
137impl<T> Drop for StackInit<T> {
138    #[inline]
139    fn drop(&mut self) {
140        if self.is_init {
141            // SAFETY: As we are being dropped, we only call this once. And since `self.is_init` is
142            // true, `self.value` is initialized.
143            unsafe { self.value.assume_init_drop() };
144        }
145    }
146}
147
148impl<T> StackInit<T> {
149    /// Creates a new [`StackInit<T>`] that is uninitialized. Use [`stack_pin_init`] instead of this
150    /// primitive.
151    ///
152    /// [`stack_pin_init`]: crate::stack_pin_init
153    #[inline]
154    pub fn uninit() -> Self {
155        Self {
156            value: MaybeUninit::uninit(),
157            is_init: false,
158        }
159    }
160
161    /// Initializes the contents and returns the result.
162    #[inline]
163    pub fn init<E>(self: Pin<&mut Self>, init: impl PinInit<T, E>) -> Result<Pin<&mut T>, E> {
164        // SAFETY: We never move out of `this`.
165        let this = unsafe { Pin::into_inner_unchecked(self) };
166        // The value is currently initialized, so it needs to be dropped before we can reuse
167        // the memory (this is a safety guarantee of `Pin`).
168        if this.is_init {
169            this.is_init = false;
170            // SAFETY: `this.is_init` was true and therefore `this.value` is initialized.
171            unsafe { this.value.assume_init_drop() };
172        }
173        // SAFETY: The memory slot is valid and this type ensures that it will stay pinned.
174        unsafe { init.__init(this.value.as_mut_ptr())? };
175        // INVARIANT: `this.value` is initialized above.
176        this.is_init = true;
177        // SAFETY: The slot is now pinned, since we will never give access to `&mut T`.
178        Ok(unsafe { Pin::new_unchecked(this.value.assume_init_mut()) })
179    }
180}
181
182#[test]
183#[cfg(feature = "std")]
184fn stack_init_reuse() {
185    use ::std::{borrow::ToOwned, println, string::String};
186    use core::pin::pin;
187
188    #[derive(Debug)]
189    struct Foo {
190        a: usize,
191        b: String,
192    }
193    let mut slot: Pin<&mut StackInit<Foo>> = pin!(StackInit::uninit());
194    let value: Result<Pin<&mut Foo>, core::convert::Infallible> =
195        slot.as_mut().init(crate::init!(Foo {
196            a: 42,
197            b: "Hello".to_owned(),
198        }));
199    let value = value.unwrap();
200    println!("{value:?}");
201    let value: Result<Pin<&mut Foo>, core::convert::Infallible> =
202        slot.as_mut().init(crate::init!(Foo {
203            a: 24,
204            b: "world!".to_owned(),
205        }));
206    let value = value.unwrap();
207    println!("{value:?}");
208}
209
210// Marker types that determines type of `DropGuard`'s let bindings.
211pub struct Pinned;
212pub struct Unpinned;
213
214/// Represent an uninitialized field.
215///
216/// # Invariants
217///
218/// - `ptr` is valid, properly aligned and points to uninitialized and exclusively accessed memory.
219/// - If `P` is `Pinned`, then `ptr` is structurally pinned.
220pub struct Slot<P, T: ?Sized> {
221    ptr: *mut T,
222    _phantom: PhantomData<P>,
223}
224
225impl<P, T: ?Sized> Slot<P, T> {
226    /// # Safety
227    ///
228    /// - `ptr` is valid, properly aligned and points to uninitialized and exclusively accessed
229    ///   memory.
230    /// - If `P` is `Pinned`, then `ptr` is structurally pinned.
231    #[inline(always)]
232    pub unsafe fn new(ptr: *mut T) -> Self {
233        // INVARIANT: Per safety requirement.
234        Self {
235            ptr,
236            _phantom: PhantomData,
237        }
238    }
239
240    /// Initialize the field by value.
241    #[inline(always)]
242    pub fn write(self, value: T) -> DropGuard<P, T>
243    where
244        T: Sized,
245    {
246        // SAFETY: `self.ptr` is a valid and aligned pointer for write.
247        unsafe { self.ptr.write(value) }
248        // SAFETY:
249        // - `self.ptr` is valid and properly aligned per type invariant.
250        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
251        // - If `P` is `Pinned`, `self.ptr` is pinned.
252        unsafe { DropGuard::new(self.ptr) }
253    }
254}
255
256impl<T: ?Sized> Slot<Unpinned, T> {
257    /// Initialize the field.
258    #[inline(always)]
259    pub fn init<E>(self, init: impl Init<T, E>) -> Result<DropGuard<Unpinned, T>, E> {
260        // SAFETY:
261        // - `self.ptr` is valid and properly aligned.
262        // - when `Err` is returned, we also propagate the error without touching `slot`;
263        //   also `self` is consumed so it cannot be touched further.
264        unsafe { init.__init(self.ptr)? };
265
266        // SAFETY:
267        // - `self.ptr` is valid and properly aligned per type invariant.
268        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
269        Ok(unsafe { DropGuard::new(self.ptr) })
270    }
271}
272
273impl<T: ?Sized> Slot<Pinned, T> {
274    /// Initialize the field.
275    #[inline(always)]
276    pub fn init<E>(self, init: impl PinInit<T, E>) -> Result<DropGuard<Pinned, T>, E> {
277        // SAFETY:
278        // - `self.ptr` is valid and properly aligned.
279        // - when `Err` is returned, we also propagate the error without touching `ptr`;
280        //   also `self` is consumed so it cannot be touched further.
281        // - the drop guard will not hand out `&mut` (only `Pin<&mut T>`).
282        unsafe { init.__init(self.ptr)? };
283
284        // SAFETY:
285        // - `self.ptr` is valid, properly aligned and pinned per type invariant.
286        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
287        Ok(unsafe { DropGuard::new(self.ptr) })
288    }
289}
290
291/// When a value of this type is dropped, it drops a `T`.
292///
293/// Can be forgotten to prevent the drop.
294///
295/// # Invariants
296///
297/// - `ptr` is valid and properly aligned.
298/// - `*ptr` is initialized and owned by this guard.
299/// - if `P` is `Pinned`, `ptr` is pinned.
300pub struct DropGuard<P, T: ?Sized> {
301    ptr: *mut T,
302    phantom: PhantomData<P>,
303}
304
305impl<P, T: ?Sized> DropGuard<P, T> {
306    /// Creates a drop guard and transfer the ownership of the pointer content.
307    ///
308    /// The ownership is only relinguished if the guard is forgotten via [`core::mem::forget`].
309    ///
310    /// # Safety
311    ///
312    /// - `ptr` is valid and properly aligned.
313    /// - `*ptr` is initialized, and the ownership is transferred to this guard.
314    /// - if `P` is `Pinned`, `ptr` is pinned.
315    #[inline]
316    pub unsafe fn new(ptr: *mut T) -> Self {
317        // INVARIANT: By safety requirement.
318        Self {
319            ptr,
320            phantom: PhantomData,
321        }
322    }
323}
324
325impl<T: ?Sized> DropGuard<Unpinned, T> {
326    /// Create a let binding for accessor use.
327    #[inline]
328    pub fn let_binding(&mut self) -> &mut T {
329        // SAFETY: Per type invariant.
330        unsafe { &mut *self.ptr }
331    }
332
333    /// Create a let binding for accessor use in dropck.
334    #[inline]
335    pub fn let_binding_in_dropck(&mut self) -> &mut T {
336        self.let_binding()
337    }
338}
339
340impl<T: ?Sized> DropGuard<Pinned, T> {
341    /// Create a let binding for accessor use.
342    #[inline]
343    pub fn let_binding(&mut self) -> Pin<&mut T> {
344        // SAFETY: `self.ptr` is valid, properly aligned, initialized, exclusively accessible and
345        // pinned per type invariant.
346        unsafe { Pin::new_unchecked(&mut *self.ptr) }
347    }
348
349    /// Create a let binding for accessor use in dropck.
350    #[inline]
351    pub fn let_binding_in_dropck(&mut self) -> Pin<&mut T> {
352        self.let_binding()
353    }
354}
355
356impl<P, T: ?Sized> Drop for DropGuard<P, T> {
357    #[inline]
358    fn drop(&mut self) {
359        // SAFETY: `self.ptr` is valid, properly aligned and `*self.ptr` is owned by this guard.
360        unsafe { ptr::drop_in_place(self.ptr) }
361    }
362}
363
364pub struct Shared;
365pub struct Mutable;
366
367/// Represent an uninitialized field in a pinned struct that will be referenced by other fields.
368///
369/// # Invariants
370///
371/// - `ptr` is valid, properly aligned and points to uninitialized and exclusively accessed memory
372///   and will live longer than `'a`.
373/// - If `P` is `Pinned`, then `ptr` is structurally pinned.
374pub struct SelfRefSlot<'a, M, P, T: ?Sized> {
375    ptr: *mut T,
376    _phantom: PhantomData<(M, P, &'a mut T)>,
377}
378
379impl<'a, M, P, T: ?Sized> SelfRefSlot<'a, M, P, T> {
380    /// # Safety
381    ///
382    /// - `ptr` is valid, properly aligned and points to uninitialized and exclusively accessed
383    ///   memory and will live longer than `'a`.
384    /// - If `P` is `Pinned`, then `ptr` is structurally pinned.
385    #[inline]
386    pub unsafe fn new(ptr: *mut T) -> Self {
387        // INVARIANT: Per safety requirement.
388        Self {
389            ptr,
390            _phantom: PhantomData,
391        }
392    }
393
394    /// Initialize the field by value.
395    #[inline]
396    pub fn write(self, value: T) -> SelfRefDropGuard<'a, M, P, T>
397    where
398        T: Sized,
399    {
400        // SAFETY: `self.ptr` is a valid and aligned pointer for write.
401        unsafe { self.ptr.write(value) }
402        // SAFETY:
403        // - `self.ptr` is valid, properly aligned and live longer than `'a` per type invariant.
404        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
405        // - If `P` is `Pinned`, `self.ptr` is pinned.
406        unsafe { SelfRefDropGuard::new(self.ptr) }
407    }
408}
409
410impl<'a, M, T: ?Sized> SelfRefSlot<'a, M, Unpinned, T> {
411    /// Initialize the field.
412    #[inline]
413    pub fn init<E>(self, init: impl Init<T, E>) -> Result<SelfRefDropGuard<'a, M, Unpinned, T>, E> {
414        // SAFETY:
415        // - `self.ptr` is valid and properly aligned.
416        // - when `Err` is returned, we also propagate the error without touching `ptr`;
417        //   also `self` is consumed so it cannot be touched further.
418        unsafe { init.__init(self.ptr)? };
419
420        // SAFETY:
421        // - `self.ptr` is valid, properly aligned and live longer than `'a` per type invariant.
422        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
423        Ok(unsafe { SelfRefDropGuard::new(self.ptr) })
424    }
425}
426
427impl<'a, M, T: ?Sized> SelfRefSlot<'a, M, Pinned, T> {
428    /// Initialize the field.
429    #[inline]
430    pub fn init<E>(
431        self,
432        init: impl PinInit<T, E>,
433    ) -> Result<SelfRefDropGuard<'a, M, Pinned, T>, E> {
434        // SAFETY:
435        // - `ptr` is valid
436        // - when `Err` is returned, we also propagate the error without touching `ptr`;
437        //   also `self` is consumed so it cannot be touched further.
438        // - the drop guard will not hand out `&mut` (only `Pin<&mut T>`).
439        unsafe { init.__init(self.ptr)? };
440
441        // SAFETY:
442        // - `self.ptr` is valid, properly aligned and live longer than `'a` per type invariant.
443        // - `*self.ptr` is initialized above and the ownership is transferred to the guard.
444        Ok(unsafe { SelfRefDropGuard::new(self.ptr) })
445    }
446}
447/// When a value of this type is dropped, it drops a `T`.
448///
449/// Can be forgotten to prevent the drop.
450///
451/// # Invariants
452///
453/// - `ptr` is valid, properly aligned and live longer than `'a`.
454/// - `*ptr` is initialized and owned by this guard.
455/// - if `P` is `Pinned`, `ptr` is pinned.
456pub struct SelfRefDropGuard<'a, M, P, T: ?Sized> {
457    ptr: *mut T,
458    phantom: PhantomData<(M, P, &'a mut T)>,
459}
460
461impl<'a, M, P, T: ?Sized> SelfRefDropGuard<'a, M, P, T> {
462    /// Creates a drop guard and transfer the ownership of the pointer content.
463    ///
464    /// The ownership is only relinquished if the guard is forgotten via [`core::mem::forget`].
465    ///
466    /// # Safety
467    ///
468    /// - `ptr` is valid, properly aligned and live longer than `'a`.
469    /// - `*ptr` is initialized, and the ownership is transferred to this guard.
470    /// - if `P` is `Pinned`, `ptr` is pinned.
471    #[inline]
472    pub unsafe fn new(ptr: *mut T) -> Self {
473        // INVARIANT: By safety requirement.
474        Self {
475            ptr,
476            phantom: PhantomData,
477        }
478    }
479}
480
481impl<'a, T: ?Sized> SelfRefDropGuard<'a, Shared, Unpinned, T> {
482    /// Create a let binding for accessor use.
483    #[inline]
484    pub fn let_binding(&mut self) -> &'a T {
485        // SAFETY: Per type invariant.
486        unsafe { &*self.ptr }
487    }
488
489    /// Create a let binding for accessor use in dropck.
490    #[inline]
491    pub fn let_binding_in_dropck(&mut self) -> &T {
492        self.let_binding()
493    }
494}
495
496impl<'a, T: ?Sized> SelfRefDropGuard<'a, Shared, Pinned, T> {
497    /// Create a let binding for accessor use.
498    #[inline]
499    pub fn let_binding(&mut self) -> Pin<&'a T> {
500        // SAFETY: `self.ptr` is valid, properly aligned, live longer than `'a`, initialized,
501        // exclusively accessible and pinned per type invariant.
502        unsafe { Pin::new_unchecked(&*self.ptr) }
503    }
504
505    /// Create a let binding for accessor use in dropck.
506    #[inline]
507    pub fn let_binding_in_dropck(&mut self) -> Pin<&T> {
508        self.let_binding()
509    }
510}
511
512impl<'a, T: ?Sized> SelfRefDropGuard<'a, Mutable, Unpinned, T> {
513    /// Create a let binding for accessor use.
514    #[inline]
515    pub fn let_binding(&mut self) -> &'a mut T {
516        // SAFETY: Per type invariant.
517        unsafe { &mut *self.ptr }
518    }
519
520    /// Create a let binding for accessor use in dropck.
521    #[inline]
522    pub fn let_binding_in_dropck(&mut self) -> &mut T {
523        self.let_binding()
524    }
525}
526
527impl<'a, T: ?Sized> SelfRefDropGuard<'a, Mutable, Pinned, T> {
528    /// Create a let binding for accessor use.
529    #[inline]
530    pub fn let_binding(&mut self) -> Pin<&'a mut T> {
531        // SAFETY: `self.ptr` is valid, properly aligned, live longer than `'a`, initialized,
532        // exclusively accessible and pinned per type invariant.
533        unsafe { Pin::new_unchecked(&mut *self.ptr) }
534    }
535
536    #[inline]
537    pub fn let_binding_in_dropck(&mut self) -> Pin<&mut T> {
538        self.let_binding()
539    }
540}
541
542impl<M, P, T: ?Sized> Drop for SelfRefDropGuard<'_, M, P, T> {
543    #[inline]
544    fn drop(&mut self) {
545        // SAFETY: `self.ptr` is valid, properly aligned and `*self.ptr` is owned by this guard.
546        unsafe { ptr::drop_in_place(self.ptr) }
547    }
548}
549
550/// Token used by `PinnedDrop` to prevent calling the function without creating this unsafely
551/// created struct. This is needed, because the `drop` function is safe, but should not be called
552/// manually.
553pub struct OnlyCallFromDrop(());
554
555impl OnlyCallFromDrop {
556    /// # Safety
557    ///
558    /// This function should only be called from the [`Drop::drop`] function and only be used to
559    /// delegate the destruction to the pinned destructor [`PinnedDrop::drop`] of the same type.
560    pub unsafe fn new() -> Self {
561        Self(())
562    }
563}
564
565/// Initializer that always fails.
566///
567/// Used by [`assert_pinned!`].
568///
569/// [`assert_pinned!`]: crate::assert_pinned
570pub struct AlwaysFail<T: ?Sized> {
571    _t: PhantomData<T>,
572}
573
574impl<T: ?Sized> AlwaysFail<T> {
575    /// Creates a new initializer that always fails.
576    #[inline]
577    pub fn new() -> Self {
578        Self { _t: PhantomData }
579    }
580}
581
582impl<T: ?Sized> Default for AlwaysFail<T> {
583    #[inline]
584    fn default() -> Self {
585        Self::new()
586    }
587}
588
589// SAFETY: `__init` always fails, which is always okay.
590unsafe impl<T: ?Sized> PinInit<T, ()> for AlwaysFail<T> {
591    #[inline]
592    unsafe fn __init(self, _slot: *mut T) -> Result<(), ()> {
593        Err(())
594    }
595}
596/// Polyfill of `FnOnce` trait to be able to reference output via associated type.
597pub trait FnOutput<Args> {
598    type Output;
599}
600
601macro_rules! impl_fn_output {
602    () => {};
603    ($ret:ident, $($arg:ident,)*) => {
604        impl<This, $ret, $($arg,)*> FnOutput<($($arg,)*)> for This
605        where
606            This: FnOnce($($arg,)*) -> $ret,
607        {
608            type Output = $ret;
609        }
610        impl_fn_output!($($arg,)*);
611    };
612}
613
614impl_fn_output!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U,);
615
616/// Lifetime erasure facility.
617///
618/// Say we have `exists<'a, 'b> Foo<'a, 'b>` and we want to store it. There's no concrete
619/// lifetimes we can use, so we want to erase the lifetime.
620///
621/// Such erasure can be encoded as
622/// `Erased<for<'a> fn(&'a ()) -> for<'b> fn(&'b()) -> (Foo<'a, 'b>,)`.
623///
624/// This can be considered the stable version of Rust's `unsafe_binder` feature, without the
625/// no-drop-glue requirement.
626#[repr(transparent)]
627#[allow(private_bounds)]
628pub struct Erase<F: EraseLt>(F::Erased);
629
630/// Helper trait to resolve the erased lifetime.
631trait EraseLt {
632    type Erased;
633}
634
635impl<T> EraseLt for (T,) {
636    type Erased = T;
637}
638
639impl<T> EraseLt for T
640where
641    T: for<'a> FnOutput<(&'a (),), Output: EraseLt>,
642{
643    type Erased = <<T as FnOutput<(&'static (),)>>::Output as EraseLt>::Erased;
644}
645
646// The default `Send` and `Sync` are not sufficient, because one can use lifetime specialization to
647// implement `Send` or `Sync` for a concrete instance of lifetime. Use HRTB to ensure that the type
648// will only implement `Send` or `Sync` if it's implemented for *all* erased lifetimes.
649
650// SAFETY: Trivial, no lifetime to erase.
651unsafe impl<T: Send> Send for Erase<(T,)> {}
652
653// SAFETY: If we erased a lifetime, then the type needs to be `Send` for across *all* that
654// lifetimes.
655unsafe impl<F: EraseLt> Send for Erase<F>
656where
657    F: for<'a> FnOutput<(&'a (),), Output: EraseLt>,
658    for<'a> Erase<<F as FnOutput<(&'a (),)>>::Output>: Send,
659{
660}
661
662// SAFETY: Trivial, no lifetime to erase.
663unsafe impl<T: Sync> Sync for Erase<(T,)> {}
664
665// SAFETY: If we erased a lifetime, then the type needs to be `Sync` for across *all* that
666// lifetimes.
667unsafe impl<F: EraseLt> Sync for Erase<F>
668where
669    F: for<'a> FnOutput<(&'a (),), Output: EraseLt>,
670    for<'a> Erase<<F as FnOutput<(&'a (),)>>::Output>: Sync,
671{
672}
673
674/// Wrapper for borrowed fields.
675///
676/// This should be switched to `UnsafePinned` when it is stable.
677/// NOTE: This type needs to be covariant; Rust's 1.89+'s `UnsafePinned` is invariant.
678#[repr(transparent)]
679pub struct Borrowed<T: ?Sized, P>(PhantomInvariant<P>, PhantomPinned, T);
680
681// Lifetimes not needed by drop glue are considered by Rust's drop check to be considered
682// `#[may_dangle]`. In case for a self-referential struct, we may have fields which need lifetime of
683// borrowed fields in their drop glue, so compiler's automatic check is insufficient.
684//
685// Code like this:
686// ```
687// #[pin_data]
688// struct SelfRef<'a> {
689//     borrow: PrintOnDrop<&'owner str>,
690//     owner: &'a str,
691// }
692// ```
693// may access `owner` during the drop, however Rust will determine that since `'a` only is used in
694// `owner`, the `'a` lifetime may dangle during drop.
695//
696// This is undesirable for pin-init self references, because `&'a str` could be coerecd to
697// `&'owner str` and this could further coerce if there're implied outlives, e.g.
698// `&'earlier_field &'owner ()` would allow `&'owner str` to further coerce to `&'earlier_field`.
699//
700// Thus, if any self-referential field require field lifetime access in `Drop` impl, we would need
701// to ensure that the all generic parameters visible by self-referential fields would strictly
702// outlive the struct. And this can be done by a simple `Drop` impl that does nothing. Without a
703// dropck eye patch, presence of `Drop` impl, albeit empty, tells the drop check that the strict
704// outlive relation is needed.
705impl<T: ?Sized, P> Drop for Borrowed<T, P> {
706    #[inline(always)]
707    fn drop(&mut self) {}
708}
709
710impl<T: ?Sized, P> Deref for Borrowed<T, P> {
711    type Target = T;
712
713    #[inline(always)]
714    fn deref(&self) -> &T {
715        &self.2
716    }
717}
718
719/// An alias of `PhantomData` but with a name to aid user in case of misuse.
720pub struct NotVisible<T: ?Sized>(PhantomData<T>);
721
722impl<T: ?Sized> NotVisible<T> {
723    #[inline(always)]
724    pub fn new() -> Self {
725        Self(PhantomData)
726    }
727}
728
729/// Marker type to capture outlive bounds coming from existential lifetimes.
730pub struct ExistLt<'a>(PhantomData<&'a ()>);
731
732// Dummy `Drop`, same reason as `Borrowed`.
733impl Drop for ExistLt<'_> {
734    #[inline(always)]
735    fn drop(&mut self) {}
736}
737
738/// Type that allows additional `PhantomData` to be attached.
739///
740/// This allows changing variance of types without introducing additional fields.
741#[repr(transparent)]
742pub struct WithPhantom<T, P>(PhantomData<P>, T);