Skip to content

Commit 154acf0

Browse files
authored
Rollup merge of rust-lang#77726 - fusion-engineering-forks:static-pin, r=dtolnay
Add Pin::static_ref, static_mut. This adds `Pin::static_ref` and `Pin::static_mut`, which convert a static reference to a pinned static reference. Static references are effectively already pinned, as what they refer to has to live forever and can never be moved. --- Context: I want to update the `sys` and `sys_common` mutexes/rwlocks/condvars to use `Pin<&self>` in their functions, instead of only warning in the unsafety comments that they may not be moved. That should make them a little bit less dangerous to use. Putting such an object in a `static` (e.g. through `sys_common::StaticMutex`) fulfills the requirements about never moving it, but right now there's no safe way to get a `Pin<&T>` to a `static`. This solves that.
2 parents f965120 + df95dce commit 154acf0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

library/core/src/pin.rs

+28
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,34 @@ impl<'a, T: ?Sized> Pin<&'a mut T> {
781781
}
782782
}
783783

784+
impl<T: ?Sized> Pin<&'static T> {
785+
/// Get a pinned reference from a static reference.
786+
///
787+
/// This is safe, because `T` is borrowed for the `'static` lifetime, which
788+
/// never ends.
789+
#[unstable(feature = "pin_static_ref", issue = "none")]
790+
#[rustc_const_unstable(feature = "const_pin", issue = "76654")]
791+
pub const fn static_ref(r: &'static T) -> Pin<&'static T> {
792+
// SAFETY: The 'static borrow guarantees the data will not be
793+
// moved/invalidated until it gets dropped (which is never).
794+
unsafe { Pin::new_unchecked(r) }
795+
}
796+
}
797+
798+
impl<T: ?Sized> Pin<&'static mut T> {
799+
/// Get a pinned mutable reference from a static mutable reference.
800+
///
801+
/// This is safe, because `T` is borrowed for the `'static` lifetime, which
802+
/// never ends.
803+
#[unstable(feature = "pin_static_ref", issue = "none")]
804+
#[rustc_const_unstable(feature = "const_pin", issue = "76654")]
805+
pub const fn static_mut(r: &'static mut T) -> Pin<&'static mut T> {
806+
// SAFETY: The 'static borrow guarantees the data will not be
807+
// moved/invalidated until it gets dropped (which is never).
808+
unsafe { Pin::new_unchecked(r) }
809+
}
810+
}
811+
784812
#[stable(feature = "pin", since = "1.33.0")]
785813
impl<P: Deref> Deref for Pin<P> {
786814
type Target = P::Target;

0 commit comments

Comments
 (0)