Debian Codegraph @

third_party/rust/pin-project/src/lib.rs

raw
1 /*!
2 <!-- tidy:crate-doc:start -->
3 A crate for safe and ergonomic [pin-projection].
4
5 ## Usage
6
7 Add this to your `Cargo.toml`:
8
9 ```toml
10 [dependencies]
11 pin-project = "1"
12 ```
13
14 *Compiler support: requires rustc 1.56+*
15
16 ## Examples
17
18 [`#[pin_project]`][`pin_project`] attribute creates projection types
19 covering all the fields of struct or enum.
20
21 ```rust
22 use std::pin::Pin;
23
24 use pin_project::pin_project;
25
26 #[pin_project]
27 struct Struct<T, U> {
28 #[pin]
29 pinned: T,
30 unpinned: U,
31 }
32
33 impl<T, U> Struct<T, U> {
34 fn method(self: Pin<&mut Self>) {
35 let this = self.project();
36 let _: Pin<&mut T> = this.pinned; // Pinned reference to the field
37 let _: &mut U = this.unpinned; // Normal reference to the field
38 }
39 }
40 ```
41
42 [*code like this will be generated*][struct-default-expanded]
43
44 To use `#[pin_project]` on enums, you need to name the projection type
45 returned from the method.
46
47 ```rust
48 use std::pin::Pin;
49
50 use pin_project::pin_project;
51
52 #[pin_project(project = EnumProj)]
53 enum Enum<T, U> {
54 Pinned(#[pin] T),
55 Unpinned(U),
56 }
57
58 impl<T, U> Enum<T, U> {
59 fn method(self: Pin<&mut Self>) {
60 match self.project() {
61 EnumProj::Pinned(x) => {
62 let _: Pin<&mut T> = x;
63 }
64 EnumProj::Unpinned(y) => {
65 let _: &mut U = y;
66 }
67 }
68 }
69 }
70 ```
71
72 [*code like this will be generated*][enum-default-expanded]
73
74 See [`#[pin_project]`][`pin_project`] attribute for more details, and
75 see [examples] directory for more examples and generated code.
76
77 ## Related Projects
78
79 - [pin-project-lite]: A lightweight version of pin-project written with declarative macros.
80
81 [enum-default-expanded]: https://github.com/taiki-e/pin-project/blob/HEAD/examples/enum-default-expanded.rs
82 [examples]: https://github.com/taiki-e/pin-project/blob/HEAD/examples/README.md
83 [pin-project-lite]: https://github.com/taiki-e/pin-project-lite
84 [pin-projection]: https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning
85 [struct-default-expanded]: https://github.com/taiki-e/pin-project/blob/HEAD/examples/struct-default-expanded.rs
86
87 <!-- tidy:crate-doc:end -->
88 */
89
90 #![no_std]
91 #![doc(test(
92 no_crate_inject,
93 attr(
94 deny(warnings, rust_2018_idioms, single_use_lifetimes),
95 allow(dead_code, unused_variables)
96 )
97 ))]
98 #![warn(missing_docs, rust_2018_idioms, single_use_lifetimes, unreachable_pub)]
99 #![warn(
100 clippy::pedantic,
101 // lints for public library
102 clippy::alloc_instead_of_core,
103 clippy::exhaustive_enums,
104 clippy::exhaustive_structs,
105 clippy::std_instead_of_alloc,
106 clippy::std_instead_of_core,
107 // lints that help writing unsafe code
108 clippy::as_ptr_cast_mut,
109 clippy::default_union_representation,
110 clippy::trailing_empty_array,
111 clippy::transmute_undefined_repr,
112 clippy::undocumented_unsafe_blocks,
113 )]
114 #![allow(clippy::needless_doctest_main)]
115
116 #[doc(inline)]
117 pub use pin_project_internal::pin_project;
118 #[doc(inline)]
119 pub use pin_project_internal::pinned_drop;
120
121 /// A trait used for custom implementations of [`Unpin`].
122 ///
123 /// This trait is used in conjunction with the `UnsafeUnpin` argument to
124 /// the [`#[pin_project]`][macro@pin_project] attribute.
125 ///
126 /// # Safety
127 ///
128 /// The Rust [`Unpin`] trait is safe to implement - by itself,
129 /// implementing it cannot lead to [undefined behavior][undefined-behavior].
130 /// Undefined behavior can only occur when other unsafe code is used.
131 ///
132 /// It turns out that using pin projections, which requires unsafe code,
133 /// imposes additional requirements on an [`Unpin`] impl. Normally, all of this
134 /// unsafety is contained within this crate, ensuring that it's impossible for
135 /// you to violate any of the guarantees required by pin projection.
136 ///
137 /// However, things change if you want to provide a custom [`Unpin`] impl
138 /// for your `#[pin_project]` type. As stated in [the Rust
139 /// documentation][pin-projection], you must be sure to only implement [`Unpin`]
140 /// when all of your `#[pin]` fields (i.e. structurally pinned fields) are also
141 /// [`Unpin`].
142 ///
143 /// To help highlight this unsafety, the `UnsafeUnpin` trait is provided.
144 /// Implementing this trait is logically equivalent to implementing [`Unpin`] -
145 /// this crate will generate an [`Unpin`] impl for your type that 'forwards' to
146 /// your `UnsafeUnpin` impl. However, this trait is `unsafe` - since your type
147 /// uses structural pinning (otherwise, you wouldn't be using this crate!),
148 /// you must be sure that your `UnsafeUnpin` impls follows all of
149 /// the requirements for an [`Unpin`] impl of a structurally-pinned type.
150 ///
151 /// Note that if you specify `#[pin_project(UnsafeUnpin)]`, but do *not*
152 /// provide an impl of `UnsafeUnpin`, your type will never implement [`Unpin`].
153 /// This is effectively the same thing as adding a [`PhantomPinned`] to your
154 /// type.
155 ///
156 /// Since this trait is `unsafe`, impls of it will be detected by the
157 /// `unsafe_code` lint, and by tools like [`cargo geiger`][cargo-geiger].
158 ///
159 /// # Examples
160 ///
161 /// An `UnsafeUnpin` impl which, in addition to requiring that structurally
162 /// pinned fields be [`Unpin`], imposes an additional requirement:
163 ///
164 /// ```rust
165 /// use pin_project::{pin_project, UnsafeUnpin};
166 ///
167 /// #[pin_project(UnsafeUnpin)]
168 /// struct Struct<K, V> {
169 /// #[pin]
170 /// field_1: K,
171 /// field_2: V,
172 /// }
173 ///
174 /// unsafe impl<K, V> UnsafeUnpin for Struct<K, V> where K: Unpin + Clone {}
175 /// ```
176 ///
177 /// [`PhantomPinned`]: core::marker::PhantomPinned
178 /// [cargo-geiger]: https://github.com/rust-secure-code/cargo-geiger
179 /// [pin-projection]: core::pin#projections-and-structural-pinning
180 /// [undefined-behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
181 pub unsafe trait UnsafeUnpin {}
182
183 // Not public API.
184 #[doc(hidden)]
185 pub mod __private {
186 use core::mem::ManuallyDrop;
187 #[doc(hidden)]
188 pub use core::{
189 marker::{PhantomData, PhantomPinned, Unpin},
190 ops::Drop,
191 pin::Pin,
192 ptr,
193 };
194
195 #[doc(hidden)]
196 pub use pin_project_internal::__PinProjectInternalDerive;
197
198 use super::UnsafeUnpin;
199
200 // An internal trait used for custom implementations of [`Drop`].
201 //
202 // **Do not call or implement this trait directly.**
203 //
204 // # Why this trait is private and `#[pinned_drop]` attribute is needed?
205 //
206 // Implementing `PinnedDrop::drop` is safe, but calling it is not safe.
207 // This is because destructors can be called multiple times in safe code and
208 // [double dropping is unsound][rust-lang/rust#62360].
209 //
210 // Ideally, it would be desirable to be able to forbid manual calls in
211 // the same way as [`Drop::drop`], but the library cannot do it. So, by using
212 // macros and replacing them with private traits,
213 // this crate prevent users from calling `PinnedDrop::drop` in safe code.
214 //
215 // This allows implementing [`Drop`] safely using `#[pinned_drop]`.
216 // Also by using the [`drop`] function just like dropping a type that directly
217 // implements [`Drop`], can drop safely a type that implements `PinnedDrop`.
218 //
219 // [rust-lang/rust#62360]: https://github.com/rust-lang/rust/pull/62360
220 #[doc(hidden)]
221 pub trait PinnedDrop {
222 #[doc(hidden)]
223 unsafe fn drop(self: Pin<&mut Self>);
224 }
225
226 // This is an internal helper struct used by `pin-project-internal`.
227 // This allows us to force an error if the user tries to provide
228 // a regular `Unpin` impl when they specify the `UnsafeUnpin` argument.
229 // This is why we need Wrapper:
230 //
231 // Supposed we have the following code:
232 //
233 // ```rust
234 // #[pin_project(UnsafeUnpin)]
235 // struct MyStruct<T> {
236 // #[pin] field: T
237 // }
238 //
239 // impl<T> Unpin for MyStruct<T> where MyStruct<T>: UnsafeUnpin {} // generated by pin-project-internal
240 // impl<T> Unpin for MyStruct<T> where T: Copy // written by the user
241 // ```
242 //
243 // We want this code to be rejected - the user is completely bypassing
244 // `UnsafeUnpin`, and providing an unsound Unpin impl in safe code!
245 //
246 // Unfortunately, the Rust compiler will accept the above code.
247 // Because MyStruct is declared in the same crate as the user-provided impl,
248 // the compiler will notice that `MyStruct<T>: UnsafeUnpin` never holds.
249 //
250 // The solution is to introduce the `Wrapper` struct, which is defined
251 // in the `pin-project` crate.
252 //
253 // We now have code that looks like this:
254 //
255 // ```rust
256 // impl<T> Unpin for MyStruct<T> where Wrapper<MyStruct<T>>: UnsafeUnpin {} // generated by pin-project-internal
257 // impl<T> Unpin for MyStruct<T> where T: Copy // written by the user
258 // ```
259 //
260 // We also have `unsafe impl<T> UnsafeUnpin for Wrapper<T> where T: UnsafeUnpin {}`
261 // in the `pin-project` crate.
262 //
263 // Now, our generated impl has a bound involving a type defined in another
264 // crate - Wrapper. This will cause rust to conservatively assume that
265 // `Wrapper<MyStruct<T>>: UnsafeUnpin` holds, in the interest of preserving
266 // forwards compatibility (in case such an impl is added for Wrapper<T> in
267 // a new version of the crate).
268 //
269 // This will cause rust to reject any other `Unpin` impls for MyStruct<T>,
270 // since it will assume that our generated impl could potentially apply in
271 // any situation.
272 //
273 // This achieves the desired effect - when the user writes
274 // `#[pin_project(UnsafeUnpin)]`, the user must either provide no impl of
275 // `UnsafeUnpin` (which is equivalent to making the type never implement
276 // Unpin), or provide an impl of `UnsafeUnpin`. It is impossible for them to
277 // provide an impl of `Unpin`
278 #[doc(hidden)]
279 pub struct Wrapper<'a, T: ?Sized>(PhantomData<&'a ()>, T);
280
281 // SAFETY: `T` implements UnsafeUnpin.
282 unsafe impl<T: ?Sized + UnsafeUnpin> UnsafeUnpin for Wrapper<'_, T> {}
283
284 // This is an internal helper struct used by `pin-project-internal`.
285 //
286 // See https://github.com/taiki-e/pin-project/pull/53 for more details.
287 #[doc(hidden)]
288 pub struct AlwaysUnpin<'a, T>(PhantomData<&'a ()>, PhantomData<T>);
289
290 impl<T> Unpin for AlwaysUnpin<'_, T> {}
291
292 // This is an internal helper used to ensure a value is dropped.
293 #[doc(hidden)]
294 pub struct UnsafeDropInPlaceGuard<T: ?Sized>(*mut T);
295
296 impl<T: ?Sized> UnsafeDropInPlaceGuard<T> {
297 #[doc(hidden)]
298 pub unsafe fn new(ptr: *mut T) -> Self {
299 Self(ptr)
300 }
301 }
302
303 impl<T: ?Sized> Drop for UnsafeDropInPlaceGuard<T> {
304 fn drop(&mut self) {
305 // SAFETY: the caller of `UnsafeDropInPlaceGuard::new` must guarantee
306 // that `ptr` is valid for drop when this guard is destructed.
307 unsafe {
308 ptr::drop_in_place(self.0);
309 }
310 }
311 }
312
313 // This is an internal helper used to ensure a value is overwritten without
314 // its destructor being called.
315 #[doc(hidden)]
316 pub struct UnsafeOverwriteGuard<T> {
317 target: *mut T,
318 value: ManuallyDrop<T>,
319 }
320
321 impl<T> UnsafeOverwriteGuard<T> {
322 #[doc(hidden)]
323 pub unsafe fn new(target: *mut T, value: T) -> Self {
324 Self { target, value: ManuallyDrop::new(value) }
325 }
326 }
327
328 impl<T> Drop for UnsafeOverwriteGuard<T> {
329 fn drop(&mut self) {
330 // SAFETY: the caller of `UnsafeOverwriteGuard::new` must guarantee
331 // that `target` is valid for writes when this guard is destructed.
332 unsafe {
333 ptr::write(self.target, ptr::read(&*self.value));
334 }
335 }
336 }
337 }