1 | //! Primitive traits and types representing basic properties of types. |
2 | //! |
3 | //! Rust types can be classified in various useful ways according to |
4 | //! their intrinsic properties. These classifications are represented |
5 | //! as traits. |
6 | |
7 | #![stable (feature = "rust1" , since = "1.0.0" )] |
8 | |
9 | mod variance; |
10 | |
11 | #[unstable (feature = "phantom_variance_markers" , issue = "135806" )] |
12 | pub use self::variance::{ |
13 | PhantomContravariant, PhantomContravariantLifetime, PhantomCovariant, PhantomCovariantLifetime, |
14 | PhantomInvariant, PhantomInvariantLifetime, Variance, variance, |
15 | }; |
16 | use crate::cell::UnsafeCell; |
17 | use crate::cmp; |
18 | use crate::fmt::Debug; |
19 | use crate::hash::{Hash, Hasher}; |
20 | use crate::pin::UnsafePinned; |
21 | |
22 | /// Implements a given marker trait for multiple types at the same time. |
23 | /// |
24 | /// The basic syntax looks like this: |
25 | /// ```ignore private macro |
26 | /// marker_impls! { MarkerTrait for u8, i8 } |
27 | /// ``` |
28 | /// You can also implement `unsafe` traits |
29 | /// ```ignore private macro |
30 | /// marker_impls! { unsafe MarkerTrait for u8, i8 } |
31 | /// ``` |
32 | /// Add attributes to all impls: |
33 | /// ```ignore private macro |
34 | /// marker_impls! { |
35 | /// #[allow(lint)] |
36 | /// #[unstable(feature = "marker_trait" , issue = "none" )] |
37 | /// MarkerTrait for u8, i8 |
38 | /// } |
39 | /// ``` |
40 | /// And use generics: |
41 | /// ```ignore private macro |
42 | /// marker_impls! { |
43 | /// MarkerTrait for |
44 | /// u8, i8, |
45 | /// {T: ?Sized} *const T, |
46 | /// {T: ?Sized} *mut T, |
47 | /// {T: MarkerTrait} PhantomData<T>, |
48 | /// u32, |
49 | /// } |
50 | /// ``` |
51 | #[unstable (feature = "internal_impls_macro" , issue = "none" )] |
52 | // Allow implementations of `UnsizedConstParamTy` even though std cannot use that feature. |
53 | #[allow_internal_unstable (unsized_const_params)] |
54 | macro marker_impls { |
55 | ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => { |
56 | $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {} |
57 | marker_impls! { $(#[$($meta)*])* $Trait for $($($rest)*)? } |
58 | }, |
59 | ( $(#[$($meta:tt)*])* $Trait:ident for ) => {}, |
60 | |
61 | ( $(#[$($meta:tt)*])* unsafe $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => { |
62 | $(#[$($meta)*])* unsafe impl< $($($bounds)*)? > $Trait for $T {} |
63 | marker_impls! { $(#[$($meta)*])* unsafe $Trait for $($($rest)*)? } |
64 | }, |
65 | ( $(#[$($meta:tt)*])* unsafe $Trait:ident for ) => {}, |
66 | } |
67 | |
68 | /// Types that can be transferred across thread boundaries. |
69 | /// |
70 | /// This trait is automatically implemented when the compiler determines it's |
71 | /// appropriate. |
72 | /// |
73 | /// An example of a non-`Send` type is the reference-counting pointer |
74 | /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same |
75 | /// reference-counted value, they might try to update the reference count at the |
76 | /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic |
77 | /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring |
78 | /// some overhead) and thus is `Send`. |
79 | /// |
80 | /// See [the Nomicon](../../nomicon/send-and-sync.html) and the [`Sync`] trait for more details. |
81 | /// |
82 | /// [`Rc`]: ../../std/rc/struct.Rc.html |
83 | /// [arc]: ../../std/sync/struct.Arc.html |
84 | /// [ub]: ../../reference/behavior-considered-undefined.html |
85 | #[stable (feature = "rust1" , since = "1.0.0" )] |
86 | #[rustc_diagnostic_item = "Send" ] |
87 | #[diagnostic::on_unimplemented( |
88 | message = "`{Self}` cannot be sent between threads safely" , |
89 | label = "`{Self}` cannot be sent between threads safely" |
90 | )] |
91 | pub unsafe auto trait Send { |
92 | // empty. |
93 | } |
94 | |
95 | #[stable (feature = "rust1" , since = "1.0.0" )] |
96 | impl<T: ?Sized> !Send for *const T {} |
97 | #[stable (feature = "rust1" , since = "1.0.0" )] |
98 | impl<T: ?Sized> !Send for *mut T {} |
99 | |
100 | // Most instances arise automatically, but this instance is needed to link up `T: Sync` with |
101 | // `&T: Send` (and it also removes the unsound default instance `T Send` -> `&T: Send` that would |
102 | // otherwise exist). |
103 | #[stable (feature = "rust1" , since = "1.0.0" )] |
104 | unsafe impl<T: Sync + ?Sized> Send for &T {} |
105 | |
106 | /// Types with a constant size known at compile time. |
107 | /// |
108 | /// All type parameters have an implicit bound of `Sized`. The special syntax |
109 | /// `?Sized` can be used to remove this bound if it's not appropriate. |
110 | /// |
111 | /// ``` |
112 | /// # #![allow (dead_code)] |
113 | /// struct Foo<T>(T); |
114 | /// struct Bar<T: ?Sized>(T); |
115 | /// |
116 | /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32] |
117 | /// struct BarUse(Bar<[i32]>); // OK |
118 | /// ``` |
119 | /// |
120 | /// The one exception is the implicit `Self` type of a trait. A trait does not |
121 | /// have an implicit `Sized` bound as this is incompatible with [trait object]s |
122 | /// where, by definition, the trait needs to work with all possible implementors, |
123 | /// and thus could be any size. |
124 | /// |
125 | /// Although Rust will let you bind `Sized` to a trait, you won't |
126 | /// be able to use it to form a trait object later: |
127 | /// |
128 | /// ``` |
129 | /// # #![allow(unused_variables)] |
130 | /// trait Foo { } |
131 | /// trait Bar: Sized { } |
132 | /// |
133 | /// struct Impl; |
134 | /// impl Foo for Impl { } |
135 | /// impl Bar for Impl { } |
136 | /// |
137 | /// let x: &dyn Foo = &Impl; // OK |
138 | /// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot |
139 | /// // be made into an object |
140 | /// ``` |
141 | /// |
142 | /// [trait object]: ../../book/ch17-02-trait-objects.html |
143 | #[doc (alias = "?" , alias = "?Sized" )] |
144 | #[stable (feature = "rust1" , since = "1.0.0" )] |
145 | #[lang = "sized" ] |
146 | #[diagnostic::on_unimplemented( |
147 | message = "the size for values of type `{Self}` cannot be known at compilation time" , |
148 | label = "doesn't have a size known at compile-time" |
149 | )] |
150 | #[fundamental ] // for Default, for example, which requires that `[T]: !Default` be evaluatable |
151 | #[rustc_specialization_trait ] |
152 | #[rustc_deny_explicit_impl ] |
153 | #[rustc_do_not_implement_via_object] |
154 | #[rustc_coinductive ] |
155 | pub trait Sized { |
156 | // Empty. |
157 | } |
158 | |
159 | /// Types that can be "unsized" to a dynamically-sized type. |
160 | /// |
161 | /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and |
162 | /// `Unsize<dyn fmt::Debug>`. |
163 | /// |
164 | /// All implementations of `Unsize` are provided automatically by the compiler. |
165 | /// Those implementations are: |
166 | /// |
167 | /// - Arrays `[T; N]` implement `Unsize<[T]>`. |
168 | /// - A type implements `Unsize<dyn Trait + 'a>` if all of these conditions are met: |
169 | /// - The type implements `Trait`. |
170 | /// - `Trait` is dyn-compatible[^1]. |
171 | /// - The type is sized. |
172 | /// - The type outlives `'a`. |
173 | /// - Structs `Foo<..., T1, ..., Tn, ...>` implement `Unsize<Foo<..., U1, ..., Un, ...>>` |
174 | /// where any number of (type and const) parameters may be changed if all of these conditions |
175 | /// are met: |
176 | /// - Only the last field of `Foo` has a type involving the parameters `T1`, ..., `Tn`. |
177 | /// - All other parameters of the struct are equal. |
178 | /// - `Field<T1, ..., Tn>: Unsize<Field<U1, ..., Un>>`, where `Field<...>` stands for the actual |
179 | /// type of the struct's last field. |
180 | /// |
181 | /// `Unsize` is used along with [`ops::CoerceUnsized`] to allow |
182 | /// "user-defined" containers such as [`Rc`] to contain dynamically-sized |
183 | /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce] |
184 | /// for more details. |
185 | /// |
186 | /// [`ops::CoerceUnsized`]: crate::ops::CoerceUnsized |
187 | /// [`Rc`]: ../../std/rc/struct.Rc.html |
188 | /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md |
189 | /// [nomicon-coerce]: ../../nomicon/coercions.html |
190 | /// [^1]: Formerly known as *object safe*. |
191 | #[unstable (feature = "unsize" , issue = "18598" )] |
192 | #[lang = "unsize" ] |
193 | #[rustc_deny_explicit_impl ] |
194 | #[rustc_do_not_implement_via_object] |
195 | pub trait Unsize<T: ?Sized> { |
196 | // Empty. |
197 | } |
198 | |
199 | /// Required trait for constants used in pattern matches. |
200 | /// |
201 | /// Constants are only allowed as patterns if (a) their type implements |
202 | /// `PartialEq`, and (b) interpreting the value of the constant as a pattern |
203 | /// is equivalent to calling `PartialEq`. This ensures that constants used as |
204 | /// patterns cannot expose implementation details in an unexpected way or |
205 | /// cause semver hazards. |
206 | /// |
207 | /// This trait ensures point (b). |
208 | /// Any type that derives `PartialEq` automatically implements this trait. |
209 | /// |
210 | /// Implementing this trait (which is unstable) is a way for type authors to explicitly allow |
211 | /// comparing const values of this type; that operation will recursively compare all fields |
212 | /// (including private fields), even if that behavior differs from `PartialEq`. This can make it |
213 | /// semver-breaking to add further private fields to a type. |
214 | #[unstable (feature = "structural_match" , issue = "31434" )] |
215 | #[diagnostic::on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`" )] |
216 | #[lang = "structural_peq" ] |
217 | pub trait StructuralPartialEq { |
218 | // Empty. |
219 | } |
220 | |
221 | marker_impls! { |
222 | #[unstable (feature = "structural_match" , issue = "31434" )] |
223 | StructuralPartialEq for |
224 | usize, u8, u16, u32, u64, u128, |
225 | isize, i8, i16, i32, i64, i128, |
226 | bool, |
227 | char, |
228 | str /* Technically requires `[u8]: StructuralPartialEq` */, |
229 | (), |
230 | {T, const N: usize} [T; N], |
231 | {T} [T], |
232 | {T: ?Sized} &T, |
233 | } |
234 | |
235 | /// Types whose values can be duplicated simply by copying bits. |
236 | /// |
237 | /// By default, variable bindings have 'move semantics.' In other |
238 | /// words: |
239 | /// |
240 | /// ``` |
241 | /// #[derive(Debug)] |
242 | /// struct Foo; |
243 | /// |
244 | /// let x = Foo; |
245 | /// |
246 | /// let y = x; |
247 | /// |
248 | /// // `x` has moved into `y`, and so cannot be used |
249 | /// |
250 | /// // println!("{x:?}"); // error: use of moved value |
251 | /// ``` |
252 | /// |
253 | /// However, if a type implements `Copy`, it instead has 'copy semantics': |
254 | /// |
255 | /// ``` |
256 | /// // We can derive a `Copy` implementation. `Clone` is also required, as it's |
257 | /// // a supertrait of `Copy`. |
258 | /// #[derive(Debug, Copy, Clone)] |
259 | /// struct Foo; |
260 | /// |
261 | /// let x = Foo; |
262 | /// |
263 | /// let y = x; |
264 | /// |
265 | /// // `y` is a copy of `x` |
266 | /// |
267 | /// println!("{x:?}" ); // A-OK! |
268 | /// ``` |
269 | /// |
270 | /// It's important to note that in these two examples, the only difference is whether you |
271 | /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move |
272 | /// can result in bits being copied in memory, although this is sometimes optimized away. |
273 | /// |
274 | /// ## How can I implement `Copy`? |
275 | /// |
276 | /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`: |
277 | /// |
278 | /// ``` |
279 | /// #[derive(Copy, Clone)] |
280 | /// struct MyStruct; |
281 | /// ``` |
282 | /// |
283 | /// You can also implement `Copy` and `Clone` manually: |
284 | /// |
285 | /// ``` |
286 | /// struct MyStruct; |
287 | /// |
288 | /// impl Copy for MyStruct { } |
289 | /// |
290 | /// impl Clone for MyStruct { |
291 | /// fn clone(&self) -> MyStruct { |
292 | /// *self |
293 | /// } |
294 | /// } |
295 | /// ``` |
296 | /// |
297 | /// There is a small difference between the two. The `derive` strategy will also place a `Copy` |
298 | /// bound on type parameters: |
299 | /// |
300 | /// ``` |
301 | /// #[derive(Clone)] |
302 | /// struct MyStruct<T>(T); |
303 | /// |
304 | /// impl<T: Copy> Copy for MyStruct<T> { } |
305 | /// ``` |
306 | /// |
307 | /// This isn't always desired. For example, shared references (`&T`) can be copied regardless of |
308 | /// whether `T` is `Copy`. Likewise, a generic struct containing markers such as [`PhantomData`] |
309 | /// could potentially be duplicated with a bit-wise copy. |
310 | /// |
311 | /// ## What's the difference between `Copy` and `Clone`? |
312 | /// |
313 | /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of |
314 | /// `Copy` is not overloadable; it is always a simple bit-wise copy. |
315 | /// |
316 | /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can |
317 | /// provide any type-specific behavior necessary to duplicate values safely. For example, |
318 | /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string |
319 | /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the |
320 | /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`] |
321 | /// but not `Copy`. |
322 | /// |
323 | /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement |
324 | /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self` |
325 | /// (see the example above). |
326 | /// |
327 | /// ## When can my type be `Copy`? |
328 | /// |
329 | /// A type can implement `Copy` if all of its components implement `Copy`. For example, this |
330 | /// struct can be `Copy`: |
331 | /// |
332 | /// ``` |
333 | /// # #[allow (dead_code)] |
334 | /// #[derive(Copy, Clone)] |
335 | /// struct Point { |
336 | /// x: i32, |
337 | /// y: i32, |
338 | /// } |
339 | /// ``` |
340 | /// |
341 | /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`. |
342 | /// By contrast, consider |
343 | /// |
344 | /// ``` |
345 | /// # #![allow(dead_code)] |
346 | /// # struct Point; |
347 | /// struct PointList { |
348 | /// points: Vec<Point>, |
349 | /// } |
350 | /// ``` |
351 | /// |
352 | /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we |
353 | /// attempt to derive a `Copy` implementation, we'll get an error: |
354 | /// |
355 | /// ```text |
356 | /// the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy` |
357 | /// ``` |
358 | /// |
359 | /// Shared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds |
360 | /// shared references of types `T` that are *not* `Copy`. Consider the following struct, |
361 | /// which can implement `Copy`, because it only holds a *shared reference* to our non-`Copy` |
362 | /// type `PointList` from above: |
363 | /// |
364 | /// ``` |
365 | /// # #![allow(dead_code)] |
366 | /// # struct PointList; |
367 | /// #[derive(Copy, Clone)] |
368 | /// struct PointListWrapper<'a> { |
369 | /// point_list_ref: &'a PointList, |
370 | /// } |
371 | /// ``` |
372 | /// |
373 | /// ## When *can't* my type be `Copy`? |
374 | /// |
375 | /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased |
376 | /// mutable reference. Copying [`String`] would duplicate responsibility for managing the |
377 | /// [`String`]'s buffer, leading to a double free. |
378 | /// |
379 | /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's |
380 | /// managing some resource besides its own [`size_of::<T>`] bytes. |
381 | /// |
382 | /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get |
383 | /// the error [E0204]. |
384 | /// |
385 | /// [E0204]: ../../error_codes/E0204.html |
386 | /// |
387 | /// ## When *should* my type be `Copy`? |
388 | /// |
389 | /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though, |
390 | /// that implementing `Copy` is part of the public API of your type. If the type might become |
391 | /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to |
392 | /// avoid a breaking API change. |
393 | /// |
394 | /// ## Additional implementors |
395 | /// |
396 | /// In addition to the [implementors listed below][impls], |
397 | /// the following types also implement `Copy`: |
398 | /// |
399 | /// * Function item types (i.e., the distinct types defined for each function) |
400 | /// * Function pointer types (e.g., `fn() -> i32`) |
401 | /// * Closure types, if they capture no value from the environment |
402 | /// or if all such captured values implement `Copy` themselves. |
403 | /// Note that variables captured by shared reference always implement `Copy` |
404 | /// (even if the referent doesn't), |
405 | /// while variables captured by mutable reference never implement `Copy`. |
406 | /// |
407 | /// [`Vec<T>`]: ../../std/vec/struct.Vec.html |
408 | /// [`String`]: ../../std/string/struct.String.html |
409 | /// [`size_of::<T>`]: size_of |
410 | /// [impls]: #implementors |
411 | #[stable (feature = "rust1" , since = "1.0.0" )] |
412 | #[lang = "copy" ] |
413 | // FIXME(matthewjasper) This allows copying a type that doesn't implement |
414 | // `Copy` because of unsatisfied lifetime bounds (copying `A<'_>` when only |
415 | // `A<'static>: Copy` and `A<'_>: Clone`). |
416 | // We have this attribute here for now only because there are quite a few |
417 | // existing specializations on `Copy` that already exist in the standard |
418 | // library, and there's no way to safely have this behavior right now. |
419 | #[rustc_unsafe_specialization_marker ] |
420 | #[rustc_diagnostic_item = "Copy" ] |
421 | pub trait Copy: Clone { |
422 | // Empty. |
423 | } |
424 | |
425 | /// Derive macro generating an impl of the trait `Copy`. |
426 | #[rustc_builtin_macro ] |
427 | #[stable (feature = "builtin_macro_prelude" , since = "1.38.0" )] |
428 | #[allow_internal_unstable (core_intrinsics, derive_clone_copy)] |
429 | pub macro Copy($item:item) { |
430 | /* compiler built-in */ |
431 | } |
432 | |
433 | // Implementations of `Copy` for primitive types. |
434 | // |
435 | // Implementations that cannot be described in Rust |
436 | // are implemented in `traits::SelectionContext::copy_clone_conditions()` |
437 | // in `rustc_trait_selection`. |
438 | marker_impls! { |
439 | #[stable (feature = "rust1" , since = "1.0.0" )] |
440 | Copy for |
441 | usize, u8, u16, u32, u64, u128, |
442 | isize, i8, i16, i32, i64, i128, |
443 | f16, f32, f64, f128, |
444 | bool, char, |
445 | {T: ?Sized} *const T, |
446 | {T: ?Sized} *mut T, |
447 | |
448 | } |
449 | |
450 | #[unstable (feature = "never_type" , issue = "35121" )] |
451 | impl Copy for ! {} |
452 | |
453 | /// Shared references can be copied, but mutable references *cannot*! |
454 | #[stable (feature = "rust1" , since = "1.0.0" )] |
455 | impl<T: ?Sized> Copy for &T {} |
456 | |
457 | /// Marker trait for the types that are allowed in union fields and unsafe |
458 | /// binder types. |
459 | /// |
460 | /// Implemented for: |
461 | /// * `&T`, `&mut T` for all `T`, |
462 | /// * `ManuallyDrop<T>` for all `T`, |
463 | /// * tuples and arrays whose elements implement `BikeshedGuaranteedNoDrop`, |
464 | /// * or otherwise, all types that are `Copy`. |
465 | /// |
466 | /// Notably, this doesn't include all trivially-destructible types for semver |
467 | /// reasons. |
468 | /// |
469 | /// Bikeshed name for now. This trait does not do anything other than reflect the |
470 | /// set of types that are allowed within unions for field validity. |
471 | #[unstable (feature = "bikeshed_guaranteed_no_drop" , issue = "none" )] |
472 | #[lang = "bikeshed_guaranteed_no_drop" ] |
473 | #[rustc_deny_explicit_impl ] |
474 | #[rustc_do_not_implement_via_object] |
475 | #[doc (hidden)] |
476 | pub trait BikeshedGuaranteedNoDrop {} |
477 | |
478 | /// Types for which it is safe to share references between threads. |
479 | /// |
480 | /// This trait is automatically implemented when the compiler determines |
481 | /// it's appropriate. |
482 | /// |
483 | /// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is |
484 | /// [`Send`]. In other words, if there is no possibility of |
485 | /// [undefined behavior][ub] (including data races) when passing |
486 | /// `&T` references between threads. |
487 | /// |
488 | /// As one would expect, primitive types like [`u8`] and [`f64`] |
489 | /// are all [`Sync`], and so are simple aggregate types containing them, |
490 | /// like tuples, structs and enums. More examples of basic [`Sync`] |
491 | /// types include "immutable" types like `&T`, and those with simple |
492 | /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and |
493 | /// most other collection types. (Generic parameters need to be [`Sync`] |
494 | /// for their container to be [`Sync`].) |
495 | /// |
496 | /// A somewhat surprising consequence of the definition is that `&mut T` |
497 | /// is `Sync` (if `T` is `Sync`) even though it seems like that might |
498 | /// provide unsynchronized mutation. The trick is that a mutable |
499 | /// reference behind a shared reference (that is, `& &mut T`) |
500 | /// becomes read-only, as if it were a `& &T`. Hence there is no risk |
501 | /// of a data race. |
502 | /// |
503 | /// A shorter overview of how [`Sync`] and [`Send`] relate to referencing: |
504 | /// * `&T` is [`Send`] if and only if `T` is [`Sync`] |
505 | /// * `&mut T` is [`Send`] if and only if `T` is [`Send`] |
506 | /// * `&T` and `&mut T` are [`Sync`] if and only if `T` is [`Sync`] |
507 | /// |
508 | /// Types that are not `Sync` are those that have "interior |
509 | /// mutability" in a non-thread-safe form, such as [`Cell`][cell] |
510 | /// and [`RefCell`][refcell]. These types allow for mutation of |
511 | /// their contents even through an immutable, shared reference. For |
512 | /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires |
513 | /// only a shared reference [`&Cell<T>`][cell]. The method performs no |
514 | /// synchronization, thus [`Cell`][cell] cannot be `Sync`. |
515 | /// |
516 | /// Another example of a non-`Sync` type is the reference-counting |
517 | /// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone |
518 | /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way. |
519 | /// |
520 | /// For cases when one does need thread-safe interior mutability, |
521 | /// Rust provides [atomic data types], as well as explicit locking via |
522 | /// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types |
523 | /// ensure that any mutation cannot cause data races, hence the types |
524 | /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe |
525 | /// analogue of [`Rc`][rc]. |
526 | /// |
527 | /// Any types with interior mutability must also use the |
528 | /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which |
529 | /// can be mutated through a shared reference. Failing to doing this is |
530 | /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing |
531 | /// from `&T` to `&mut T` is invalid. |
532 | /// |
533 | /// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`. |
534 | /// |
535 | /// [box]: ../../std/boxed/struct.Box.html |
536 | /// [vec]: ../../std/vec/struct.Vec.html |
537 | /// [cell]: crate::cell::Cell |
538 | /// [refcell]: crate::cell::RefCell |
539 | /// [rc]: ../../std/rc/struct.Rc.html |
540 | /// [arc]: ../../std/sync/struct.Arc.html |
541 | /// [atomic data types]: crate::sync::atomic |
542 | /// [mutex]: ../../std/sync/struct.Mutex.html |
543 | /// [rwlock]: ../../std/sync/struct.RwLock.html |
544 | /// [unsafecell]: crate::cell::UnsafeCell |
545 | /// [ub]: ../../reference/behavior-considered-undefined.html |
546 | /// [transmute]: crate::mem::transmute |
547 | /// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html |
548 | #[stable (feature = "rust1" , since = "1.0.0" )] |
549 | #[rustc_diagnostic_item = "Sync" ] |
550 | #[lang = "sync" ] |
551 | #[rustc_on_unimplemented ( |
552 | on( |
553 | Self = "core::cell::once::OnceCell<T>" , |
554 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead" |
555 | ), |
556 | on( |
557 | Self = "core::cell::Cell<u8>" , |
558 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead" , |
559 | ), |
560 | on( |
561 | Self = "core::cell::Cell<u16>" , |
562 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead" , |
563 | ), |
564 | on( |
565 | Self = "core::cell::Cell<u32>" , |
566 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead" , |
567 | ), |
568 | on( |
569 | Self = "core::cell::Cell<u64>" , |
570 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead" , |
571 | ), |
572 | on( |
573 | Self = "core::cell::Cell<usize>" , |
574 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead" , |
575 | ), |
576 | on( |
577 | Self = "core::cell::Cell<i8>" , |
578 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead" , |
579 | ), |
580 | on( |
581 | Self = "core::cell::Cell<i16>" , |
582 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead" , |
583 | ), |
584 | on( |
585 | Self = "core::cell::Cell<i32>" , |
586 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead" , |
587 | ), |
588 | on( |
589 | Self = "core::cell::Cell<i64>" , |
590 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead" , |
591 | ), |
592 | on( |
593 | Self = "core::cell::Cell<isize>" , |
594 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead" , |
595 | ), |
596 | on( |
597 | Self = "core::cell::Cell<bool>" , |
598 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead" , |
599 | ), |
600 | on( |
601 | all( |
602 | Self = "core::cell::Cell<T>" , |
603 | not(Self = "core::cell::Cell<u8>" ), |
604 | not(Self = "core::cell::Cell<u16>" ), |
605 | not(Self = "core::cell::Cell<u32>" ), |
606 | not(Self = "core::cell::Cell<u64>" ), |
607 | not(Self = "core::cell::Cell<usize>" ), |
608 | not(Self = "core::cell::Cell<i8>" ), |
609 | not(Self = "core::cell::Cell<i16>" ), |
610 | not(Self = "core::cell::Cell<i32>" ), |
611 | not(Self = "core::cell::Cell<i64>" ), |
612 | not(Self = "core::cell::Cell<isize>" ), |
613 | not(Self = "core::cell::Cell<bool>" ) |
614 | ), |
615 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`" , |
616 | ), |
617 | on( |
618 | Self = "core::cell::RefCell<T>" , |
619 | note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead" , |
620 | ), |
621 | message = "`{Self}` cannot be shared between threads safely" , |
622 | label = "`{Self}` cannot be shared between threads safely" |
623 | )] |
624 | pub unsafe auto trait Sync { |
625 | // FIXME(estebank): once support to add notes in `rustc_on_unimplemented` |
626 | // lands in beta, and it has been extended to check whether a closure is |
627 | // anywhere in the requirement chain, extend it as such (#48534): |
628 | // ``` |
629 | // on( |
630 | // closure, |
631 | // note="`{Self}` cannot be shared safely, consider marking the closure `move`" |
632 | // ), |
633 | // ``` |
634 | |
635 | // Empty |
636 | } |
637 | |
638 | #[stable (feature = "rust1" , since = "1.0.0" )] |
639 | impl<T: ?Sized> !Sync for *const T {} |
640 | #[stable (feature = "rust1" , since = "1.0.0" )] |
641 | impl<T: ?Sized> !Sync for *mut T {} |
642 | |
643 | /// Zero-sized type used to mark things that "act like" they own a `T`. |
644 | /// |
645 | /// Adding a `PhantomData<T>` field to your type tells the compiler that your |
646 | /// type acts as though it stores a value of type `T`, even though it doesn't |
647 | /// really. This information is used when computing certain safety properties. |
648 | /// |
649 | /// For a more in-depth explanation of how to use `PhantomData<T>`, please see |
650 | /// [the Nomicon](../../nomicon/phantom-data.html). |
651 | /// |
652 | /// # A ghastly note 👻👻👻 |
653 | /// |
654 | /// Though they both have scary names, `PhantomData` and 'phantom types' are |
655 | /// related, but not identical. A phantom type parameter is simply a type |
656 | /// parameter which is never used. In Rust, this often causes the compiler to |
657 | /// complain, and the solution is to add a "dummy" use by way of `PhantomData`. |
658 | /// |
659 | /// # Examples |
660 | /// |
661 | /// ## Unused lifetime parameters |
662 | /// |
663 | /// Perhaps the most common use case for `PhantomData` is a struct that has an |
664 | /// unused lifetime parameter, typically as part of some unsafe code. For |
665 | /// example, here is a struct `Slice` that has two pointers of type `*const T`, |
666 | /// presumably pointing into an array somewhere: |
667 | /// |
668 | /// ```compile_fail,E0392 |
669 | /// struct Slice<'a, T> { |
670 | /// start: *const T, |
671 | /// end: *const T, |
672 | /// } |
673 | /// ``` |
674 | /// |
675 | /// The intention is that the underlying data is only valid for the |
676 | /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this |
677 | /// intent is not expressed in the code, since there are no uses of |
678 | /// the lifetime `'a` and hence it is not clear what data it applies |
679 | /// to. We can correct this by telling the compiler to act *as if* the |
680 | /// `Slice` struct contained a reference `&'a T`: |
681 | /// |
682 | /// ``` |
683 | /// use std::marker::PhantomData; |
684 | /// |
685 | /// # #[allow (dead_code)] |
686 | /// struct Slice<'a, T> { |
687 | /// start: *const T, |
688 | /// end: *const T, |
689 | /// phantom: PhantomData<&'a T>, |
690 | /// } |
691 | /// ``` |
692 | /// |
693 | /// This also in turn infers the lifetime bound `T: 'a`, indicating |
694 | /// that any references in `T` are valid over the lifetime `'a`. |
695 | /// |
696 | /// When initializing a `Slice` you simply provide the value |
697 | /// `PhantomData` for the field `phantom`: |
698 | /// |
699 | /// ``` |
700 | /// # #![allow(dead_code)] |
701 | /// # use std::marker::PhantomData; |
702 | /// # struct Slice<'a, T> { |
703 | /// # start: *const T, |
704 | /// # end: *const T, |
705 | /// # phantom: PhantomData<&'a T>, |
706 | /// # } |
707 | /// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> { |
708 | /// let ptr = vec.as_ptr(); |
709 | /// Slice { |
710 | /// start: ptr, |
711 | /// end: unsafe { ptr.add(vec.len()) }, |
712 | /// phantom: PhantomData, |
713 | /// } |
714 | /// } |
715 | /// ``` |
716 | /// |
717 | /// ## Unused type parameters |
718 | /// |
719 | /// It sometimes happens that you have unused type parameters which |
720 | /// indicate what type of data a struct is "tied" to, even though that |
721 | /// data is not actually found in the struct itself. Here is an |
722 | /// example where this arises with [FFI]. The foreign interface uses |
723 | /// handles of type `*mut ()` to refer to Rust values of different |
724 | /// types. We track the Rust type using a phantom type parameter on |
725 | /// the struct `ExternalResource` which wraps a handle. |
726 | /// |
727 | /// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code |
728 | /// |
729 | /// ``` |
730 | /// # #![allow(dead_code)] |
731 | /// # trait ResType { } |
732 | /// # struct ParamType; |
733 | /// # mod foreign_lib { |
734 | /// # pub fn new(_: usize) -> *mut () { 42 as *mut () } |
735 | /// # pub fn do_stuff(_: *mut (), _: usize) {} |
736 | /// # } |
737 | /// # fn convert_params(_: ParamType) -> usize { 42 } |
738 | /// use std::marker::PhantomData; |
739 | /// |
740 | /// struct ExternalResource<R> { |
741 | /// resource_handle: *mut (), |
742 | /// resource_type: PhantomData<R>, |
743 | /// } |
744 | /// |
745 | /// impl<R: ResType> ExternalResource<R> { |
746 | /// fn new() -> Self { |
747 | /// let size_of_res = size_of::<R>(); |
748 | /// Self { |
749 | /// resource_handle: foreign_lib::new(size_of_res), |
750 | /// resource_type: PhantomData, |
751 | /// } |
752 | /// } |
753 | /// |
754 | /// fn do_stuff(&self, param: ParamType) { |
755 | /// let foreign_params = convert_params(param); |
756 | /// foreign_lib::do_stuff(self.resource_handle, foreign_params); |
757 | /// } |
758 | /// } |
759 | /// ``` |
760 | /// |
761 | /// ## Ownership and the drop check |
762 | /// |
763 | /// The exact interaction of `PhantomData` with drop check **may change in the future**. |
764 | /// |
765 | /// Currently, adding a field of type `PhantomData<T>` indicates that your type *owns* data of type |
766 | /// `T` in very rare circumstances. This in turn has effects on the Rust compiler's [drop check] |
767 | /// analysis. For the exact rules, see the [drop check] documentation. |
768 | /// |
769 | /// ## Layout |
770 | /// |
771 | /// For all `T`, the following are guaranteed: |
772 | /// * `size_of::<PhantomData<T>>() == 0` |
773 | /// * `align_of::<PhantomData<T>>() == 1` |
774 | /// |
775 | /// [drop check]: Drop#drop-check |
776 | #[lang = "phantom_data" ] |
777 | #[stable (feature = "rust1" , since = "1.0.0" )] |
778 | pub struct PhantomData<T: ?Sized>; |
779 | |
780 | #[stable (feature = "rust1" , since = "1.0.0" )] |
781 | impl<T: ?Sized> Hash for PhantomData<T> { |
782 | #[inline ] |
783 | fn hash<H: Hasher>(&self, _: &mut H) {} |
784 | } |
785 | |
786 | #[stable (feature = "rust1" , since = "1.0.0" )] |
787 | impl<T: ?Sized> cmp::PartialEq for PhantomData<T> { |
788 | fn eq(&self, _other: &PhantomData<T>) -> bool { |
789 | true |
790 | } |
791 | } |
792 | |
793 | #[stable (feature = "rust1" , since = "1.0.0" )] |
794 | impl<T: ?Sized> cmp::Eq for PhantomData<T> {} |
795 | |
796 | #[stable (feature = "rust1" , since = "1.0.0" )] |
797 | impl<T: ?Sized> cmp::PartialOrd for PhantomData<T> { |
798 | fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<cmp::Ordering> { |
799 | Option::Some(cmp::Ordering::Equal) |
800 | } |
801 | } |
802 | |
803 | #[stable (feature = "rust1" , since = "1.0.0" )] |
804 | impl<T: ?Sized> cmp::Ord for PhantomData<T> { |
805 | fn cmp(&self, _other: &PhantomData<T>) -> cmp::Ordering { |
806 | cmp::Ordering::Equal |
807 | } |
808 | } |
809 | |
810 | #[stable (feature = "rust1" , since = "1.0.0" )] |
811 | impl<T: ?Sized> Copy for PhantomData<T> {} |
812 | |
813 | #[stable (feature = "rust1" , since = "1.0.0" )] |
814 | impl<T: ?Sized> Clone for PhantomData<T> { |
815 | fn clone(&self) -> Self { |
816 | Self |
817 | } |
818 | } |
819 | |
820 | #[stable (feature = "rust1" , since = "1.0.0" )] |
821 | impl<T: ?Sized> Default for PhantomData<T> { |
822 | fn default() -> Self { |
823 | Self |
824 | } |
825 | } |
826 | |
827 | #[unstable (feature = "structural_match" , issue = "31434" )] |
828 | impl<T: ?Sized> StructuralPartialEq for PhantomData<T> {} |
829 | |
830 | /// Compiler-internal trait used to indicate the type of enum discriminants. |
831 | /// |
832 | /// This trait is automatically implemented for every type and does not add any |
833 | /// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute |
834 | /// between `DiscriminantKind::Discriminant` and `mem::Discriminant`. |
835 | /// |
836 | /// [`mem::Discriminant`]: crate::mem::Discriminant |
837 | #[unstable ( |
838 | feature = "discriminant_kind" , |
839 | issue = "none" , |
840 | reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead" |
841 | )] |
842 | #[lang = "discriminant_kind" ] |
843 | #[rustc_deny_explicit_impl ] |
844 | #[rustc_do_not_implement_via_object] |
845 | pub trait DiscriminantKind { |
846 | /// The type of the discriminant, which must satisfy the trait |
847 | /// bounds required by `mem::Discriminant`. |
848 | #[lang = "discriminant_type" ] |
849 | type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin; |
850 | } |
851 | |
852 | /// Used to determine whether a type contains |
853 | /// any `UnsafeCell` internally, but not through an indirection. |
854 | /// This affects, for example, whether a `static` of that type is |
855 | /// placed in read-only static memory or writable static memory. |
856 | /// This can be used to declare that a constant with a generic type |
857 | /// will not contain interior mutability, and subsequently allow |
858 | /// placing the constant behind references. |
859 | /// |
860 | /// # Safety |
861 | /// |
862 | /// This trait is a core part of the language, it is just expressed as a trait in libcore for |
863 | /// convenience. Do *not* implement it for other types. |
864 | // FIXME: Eventually this trait should become `#[rustc_deny_explicit_impl]`. |
865 | // That requires porting the impls below to native internal impls. |
866 | #[lang = "freeze" ] |
867 | #[unstable (feature = "freeze" , issue = "121675" )] |
868 | pub unsafe auto trait Freeze {} |
869 | |
870 | #[unstable (feature = "freeze" , issue = "121675" )] |
871 | impl<T: ?Sized> !Freeze for UnsafeCell<T> {} |
872 | marker_impls! { |
873 | #[unstable (feature = "freeze" , issue = "121675" )] |
874 | unsafe Freeze for |
875 | {T: ?Sized} PhantomData<T>, |
876 | {T: ?Sized} *const T, |
877 | {T: ?Sized} *mut T, |
878 | {T: ?Sized} &T, |
879 | {T: ?Sized} &mut T, |
880 | } |
881 | |
882 | /// Used to determine whether a type contains any `UnsafePinned` (or `PhantomPinned`) internally, |
883 | /// but not through an indirection. This affects, for example, whether we emit `noalias` metadata |
884 | /// for `&mut T` or not. |
885 | /// |
886 | /// This is part of [RFC 3467](https://rust-lang.github.io/rfcs/3467-unsafe-pinned.html), and is |
887 | /// tracked by [#125735](https://github.com/rust-lang/rust/issues/125735). |
888 | #[lang = "unsafe_unpin" ] |
889 | pub(crate) unsafe auto trait UnsafeUnpin {} |
890 | |
891 | impl<T: ?Sized> !UnsafeUnpin for UnsafePinned<T> {} |
892 | unsafe impl<T: ?Sized> UnsafeUnpin for PhantomData<T> {} |
893 | unsafe impl<T: ?Sized> UnsafeUnpin for *const T {} |
894 | unsafe impl<T: ?Sized> UnsafeUnpin for *mut T {} |
895 | unsafe impl<T: ?Sized> UnsafeUnpin for &T {} |
896 | unsafe impl<T: ?Sized> UnsafeUnpin for &mut T {} |
897 | |
898 | /// Types that do not require any pinning guarantees. |
899 | /// |
900 | /// For information on what "pinning" is, see the [`pin` module] documentation. |
901 | /// |
902 | /// Implementing the `Unpin` trait for `T` expresses the fact that `T` is pinning-agnostic: |
903 | /// it shall not expose nor rely on any pinning guarantees. This, in turn, means that a |
904 | /// `Pin`-wrapped pointer to such a type can feature a *fully unrestricted* API. |
905 | /// In other words, if `T: Unpin`, a value of type `T` will *not* be bound by the invariants |
906 | /// which pinning otherwise offers, even when "pinned" by a [`Pin<Ptr>`] pointing at it. |
907 | /// When a value of type `T` is pointed at by a [`Pin<Ptr>`], [`Pin`] will not restrict access |
908 | /// to the pointee value like it normally would, thus allowing the user to do anything that they |
909 | /// normally could with a non-[`Pin`]-wrapped `Ptr` to that value. |
910 | /// |
911 | /// The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use |
912 | /// of [`Pin`] for soundness for some types, but which also want to be used by other types that |
913 | /// don't care about pinning. The prime example of such an API is [`Future::poll`]. There are many |
914 | /// [`Future`] types that don't care about pinning. These futures can implement `Unpin` and |
915 | /// therefore get around the pinning related restrictions in the API, while still allowing the |
916 | /// subset of [`Future`]s which *do* require pinning to be implemented soundly. |
917 | /// |
918 | /// For more discussion on the consequences of [`Unpin`] within the wider scope of the pinning |
919 | /// system, see the [section about `Unpin`] in the [`pin` module]. |
920 | /// |
921 | /// `Unpin` has no consequence at all for non-pinned data. In particular, [`mem::replace`] happily |
922 | /// moves `!Unpin` data, which would be immovable when pinned ([`mem::replace`] works for any |
923 | /// `&mut T`, not just when `T: Unpin`). |
924 | /// |
925 | /// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped |
926 | /// inside a [`Pin<Ptr>`] pointing at it. This is because you cannot (safely) use a |
927 | /// [`Pin<Ptr>`] to get a `&mut T` to its pointee value, which you would need to call |
928 | /// [`mem::replace`], and *that* is what makes this system work. |
929 | /// |
930 | /// So this, for example, can only be done on types implementing `Unpin`: |
931 | /// |
932 | /// ```rust |
933 | /// # #![allow (unused_must_use)] |
934 | /// use std::mem; |
935 | /// use std::pin::Pin; |
936 | /// |
937 | /// let mut string = "this" .to_string(); |
938 | /// let mut pinned_string = Pin::new(&mut string); |
939 | /// |
940 | /// // We need a mutable reference to call `mem::replace`. |
941 | /// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`, |
942 | /// // but that is only possible because `String` implements `Unpin`. |
943 | /// mem::replace(&mut *pinned_string, "other" .to_string()); |
944 | /// ``` |
945 | /// |
946 | /// This trait is automatically implemented for almost every type. The compiler is free |
947 | /// to take the conservative stance of marking types as [`Unpin`] so long as all of the types that |
948 | /// compose its fields are also [`Unpin`]. This is because if a type implements [`Unpin`], then it |
949 | /// is unsound for that type's implementation to rely on pinning-related guarantees for soundness, |
950 | /// *even* when viewed through a "pinning" pointer! It is the responsibility of the implementor of |
951 | /// a type that relies upon pinning for soundness to ensure that type is *not* marked as [`Unpin`] |
952 | /// by adding [`PhantomPinned`] field. For more details, see the [`pin` module] docs. |
953 | /// |
954 | /// [`mem::replace`]: crate::mem::replace "mem replace" |
955 | /// [`Future`]: crate::future::Future "Future" |
956 | /// [`Future::poll`]: crate::future::Future::poll "Future poll" |
957 | /// [`Pin`]: crate::pin::Pin "Pin" |
958 | /// [`Pin<Ptr>`]: crate::pin::Pin "Pin" |
959 | /// [`pin` module]: crate::pin "pin module" |
960 | /// [section about `Unpin`]: crate::pin#unpin "pin module docs about unpin" |
961 | /// [`unsafe`]: ../../std/keyword.unsafe.html "keyword unsafe" |
962 | #[stable (feature = "pin" , since = "1.33.0" )] |
963 | #[diagnostic::on_unimplemented( |
964 | note = "consider using the `pin!` macro \nconsider using `Box::pin` if you need to access the pinned value outside of the current scope" , |
965 | message = "`{Self}` cannot be unpinned" |
966 | )] |
967 | #[lang = "unpin" ] |
968 | pub auto trait Unpin {} |
969 | |
970 | /// A marker type which does not implement `Unpin`. |
971 | /// |
972 | /// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default. |
973 | // |
974 | // FIXME(unsafe_pinned): This is *not* a stable guarantee we want to make, at least not yet. |
975 | // Note that for backwards compatibility with the new [`UnsafePinned`] wrapper type, placing this |
976 | // marker in your struct acts as if you wrapped the entire struct in an `UnsafePinned`. This type |
977 | // will likely eventually be deprecated, and all new code should be using `UnsafePinned` instead. |
978 | #[stable (feature = "pin" , since = "1.33.0" )] |
979 | #[derive (Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] |
980 | pub struct PhantomPinned; |
981 | |
982 | #[stable (feature = "pin" , since = "1.33.0" )] |
983 | impl !Unpin for PhantomPinned {} |
984 | |
985 | // This is a small hack to allow existing code which uses PhantomPinned to opt-out of noalias to |
986 | // continue working. Ideally PhantomPinned could just wrap an `UnsafePinned<()>` to get the same |
987 | // effect, but we can't add a new field to an already stable unit struct -- that would be a breaking |
988 | // change. |
989 | impl !UnsafeUnpin for PhantomPinned {} |
990 | |
991 | marker_impls! { |
992 | #[stable (feature = "pin" , since = "1.33.0" )] |
993 | Unpin for |
994 | {T: ?Sized} &T, |
995 | {T: ?Sized} &mut T, |
996 | } |
997 | |
998 | marker_impls! { |
999 | #[stable (feature = "pin_raw" , since = "1.38.0" )] |
1000 | Unpin for |
1001 | {T: ?Sized} *const T, |
1002 | {T: ?Sized} *mut T, |
1003 | } |
1004 | |
1005 | /// A marker for types that can be dropped. |
1006 | /// |
1007 | /// This should be used for `~const` bounds, |
1008 | /// as non-const bounds will always hold for every type. |
1009 | #[unstable (feature = "const_destruct" , issue = "133214" )] |
1010 | #[rustc_const_unstable (feature = "const_destruct" , issue = "133214" )] |
1011 | #[lang = "destruct" ] |
1012 | #[rustc_on_unimplemented (message = "can't drop `{Self}`" , append_const_msg)] |
1013 | #[rustc_deny_explicit_impl ] |
1014 | #[rustc_do_not_implement_via_object] |
1015 | #[const_trait ] |
1016 | pub trait Destruct {} |
1017 | |
1018 | /// A marker for tuple types. |
1019 | /// |
1020 | /// The implementation of this trait is built-in and cannot be implemented |
1021 | /// for any user type. |
1022 | #[unstable (feature = "tuple_trait" , issue = "none" )] |
1023 | #[lang = "tuple_trait" ] |
1024 | #[diagnostic::on_unimplemented(message = "`{Self}` is not a tuple" )] |
1025 | #[rustc_deny_explicit_impl ] |
1026 | #[rustc_do_not_implement_via_object] |
1027 | pub trait Tuple {} |
1028 | |
1029 | /// A marker for pointer-like types. |
1030 | /// |
1031 | /// This trait can only be implemented for types that are certain to have |
1032 | /// the same size and alignment as a [`usize`] or [`*const ()`](pointer). |
1033 | /// To ensure this, there are special requirements on implementations |
1034 | /// of `PointerLike` (other than the already-provided implementations |
1035 | /// for built-in types): |
1036 | /// |
1037 | /// * The type must have `#[repr(transparent)]`. |
1038 | /// * The type’s sole non-zero-sized field must itself implement `PointerLike`. |
1039 | #[unstable (feature = "pointer_like_trait" , issue = "none" )] |
1040 | #[lang = "pointer_like" ] |
1041 | #[diagnostic::on_unimplemented( |
1042 | message = "`{Self}` needs to have the same ABI as a pointer" , |
1043 | label = "`{Self}` needs to be a pointer-like type" |
1044 | )] |
1045 | #[rustc_do_not_implement_via_object] |
1046 | pub trait PointerLike {} |
1047 | |
1048 | marker_impls! { |
1049 | #[unstable (feature = "pointer_like_trait" , issue = "none" )] |
1050 | PointerLike for |
1051 | isize, |
1052 | usize, |
1053 | {T} &T, |
1054 | {T} &mut T, |
1055 | {T} *const T, |
1056 | {T} *mut T, |
1057 | {T: PointerLike} crate::pin::Pin<T>, |
1058 | } |
1059 | |
1060 | /// A marker for types which can be used as types of `const` generic parameters. |
1061 | /// |
1062 | /// These types must have a proper equivalence relation (`Eq`) and it must be automatically |
1063 | /// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring |
1064 | /// that all fields are also `ConstParamTy`, which implies that recursively, all fields |
1065 | /// are `StructuralPartialEq`. |
1066 | #[lang = "const_param_ty" ] |
1067 | #[unstable (feature = "unsized_const_params" , issue = "95174" )] |
1068 | #[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type" )] |
1069 | #[allow (multiple_supertrait_upcastable)] |
1070 | // We name this differently than the derive macro so that the `adt_const_params` can |
1071 | // be used independently of `unsized_const_params` without requiring a full path |
1072 | // to the derive macro every time it is used. This should be renamed on stabilization. |
1073 | pub trait ConstParamTy_: UnsizedConstParamTy + StructuralPartialEq + Eq {} |
1074 | |
1075 | /// Derive macro generating an impl of the trait `ConstParamTy`. |
1076 | #[rustc_builtin_macro ] |
1077 | #[allow_internal_unstable (unsized_const_params)] |
1078 | #[unstable (feature = "adt_const_params" , issue = "95174" )] |
1079 | pub macro ConstParamTy($item:item) { |
1080 | /* compiler built-in */ |
1081 | } |
1082 | |
1083 | #[lang = "unsized_const_param_ty" ] |
1084 | #[unstable (feature = "unsized_const_params" , issue = "95174" )] |
1085 | #[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type" )] |
1086 | /// A marker for types which can be used as types of `const` generic parameters. |
1087 | /// |
1088 | /// Equivalent to [`ConstParamTy_`] except that this is used by |
1089 | /// the `unsized_const_params` to allow for fake unstable impls. |
1090 | pub trait UnsizedConstParamTy: StructuralPartialEq + Eq {} |
1091 | |
1092 | /// Derive macro generating an impl of the trait `ConstParamTy`. |
1093 | #[rustc_builtin_macro ] |
1094 | #[allow_internal_unstable (unsized_const_params)] |
1095 | #[unstable (feature = "unsized_const_params" , issue = "95174" )] |
1096 | pub macro UnsizedConstParamTy($item:item) { |
1097 | /* compiler built-in */ |
1098 | } |
1099 | |
1100 | // FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure` |
1101 | marker_impls! { |
1102 | #[unstable (feature = "adt_const_params" , issue = "95174" )] |
1103 | ConstParamTy_ for |
1104 | usize, u8, u16, u32, u64, u128, |
1105 | isize, i8, i16, i32, i64, i128, |
1106 | bool, |
1107 | char, |
1108 | (), |
1109 | {T: ConstParamTy_, const N: usize} [T; N], |
1110 | } |
1111 | |
1112 | marker_impls! { |
1113 | #[unstable (feature = "unsized_const_params" , issue = "95174" )] |
1114 | UnsizedConstParamTy for |
1115 | usize, u8, u16, u32, u64, u128, |
1116 | isize, i8, i16, i32, i64, i128, |
1117 | bool, |
1118 | char, |
1119 | (), |
1120 | {T: UnsizedConstParamTy, const N: usize} [T; N], |
1121 | |
1122 | str, |
1123 | {T: UnsizedConstParamTy} [T], |
1124 | {T: UnsizedConstParamTy + ?Sized} &T, |
1125 | } |
1126 | |
1127 | /// A common trait implemented by all function pointers. |
1128 | // |
1129 | // Note that while the trait is internal and unstable it is nevertheless |
1130 | // exposed as a public bound of the stable `core::ptr::fn_addr_eq` function. |
1131 | #[unstable ( |
1132 | feature = "fn_ptr_trait" , |
1133 | issue = "none" , |
1134 | reason = "internal trait for implementing various traits for all function pointers" |
1135 | )] |
1136 | #[lang = "fn_ptr_trait" ] |
1137 | #[rustc_deny_explicit_impl ] |
1138 | #[rustc_do_not_implement_via_object] |
1139 | pub trait FnPtr: Copy + Clone { |
1140 | /// Returns the address of the function pointer. |
1141 | #[lang = "fn_ptr_addr" ] |
1142 | fn addr(self) -> *const (); |
1143 | } |
1144 | |
1145 | /// Derive macro that makes a smart pointer usable with trait objects. |
1146 | /// |
1147 | /// # What this macro does |
1148 | /// |
1149 | /// This macro is intended to be used with user-defined pointer types, and makes it possible to |
1150 | /// perform coercions on the pointee of the user-defined pointer. There are two aspects to this: |
1151 | /// |
1152 | /// ## Unsizing coercions of the pointee |
1153 | /// |
1154 | /// By using the macro, the following example will compile: |
1155 | /// ``` |
1156 | /// #![feature(derive_coerce_pointee)] |
1157 | /// use std::marker::CoercePointee; |
1158 | /// use std::ops::Deref; |
1159 | /// |
1160 | /// #[derive(CoercePointee)] |
1161 | /// #[repr(transparent)] |
1162 | /// struct MySmartPointer<T: ?Sized>(Box<T>); |
1163 | /// |
1164 | /// impl<T: ?Sized> Deref for MySmartPointer<T> { |
1165 | /// type Target = T; |
1166 | /// fn deref(&self) -> &T { |
1167 | /// &self.0 |
1168 | /// } |
1169 | /// } |
1170 | /// |
1171 | /// trait MyTrait {} |
1172 | /// |
1173 | /// impl MyTrait for i32 {} |
1174 | /// |
1175 | /// fn main() { |
1176 | /// let ptr: MySmartPointer<i32> = MySmartPointer(Box::new(4)); |
1177 | /// |
1178 | /// // This coercion would be an error without the derive. |
1179 | /// let ptr: MySmartPointer<dyn MyTrait> = ptr; |
1180 | /// } |
1181 | /// ``` |
1182 | /// Without the `#[derive(CoercePointee)]` macro, this example would fail with the following error: |
1183 | /// ```text |
1184 | /// error[E0308]: mismatched types |
1185 | /// --> src/main.rs:11:44 |
1186 | /// | |
1187 | /// 11 | let ptr: MySmartPointer<dyn MyTrait> = ptr; |
1188 | /// | --------------------------- ^^^ expected `MySmartPointer<dyn MyTrait>`, found `MySmartPointer<i32>` |
1189 | /// | | |
1190 | /// | expected due to this |
1191 | /// | |
1192 | /// = note: expected struct `MySmartPointer<dyn MyTrait>` |
1193 | /// found struct `MySmartPointer<i32>` |
1194 | /// = help: `i32` implements `MyTrait` so you could box the found value and coerce it to the trait object `Box<dyn MyTrait>`, you will have to change the expected type as well |
1195 | /// ``` |
1196 | /// |
1197 | /// ## Dyn compatibility |
1198 | /// |
1199 | /// This macro allows you to dispatch on the user-defined pointer type. That is, traits using the |
1200 | /// type as a receiver are dyn-compatible. For example, this compiles: |
1201 | /// |
1202 | /// ``` |
1203 | /// #![feature(arbitrary_self_types, derive_coerce_pointee)] |
1204 | /// use std::marker::CoercePointee; |
1205 | /// use std::ops::Deref; |
1206 | /// |
1207 | /// #[derive(CoercePointee)] |
1208 | /// #[repr(transparent)] |
1209 | /// struct MySmartPointer<T: ?Sized>(Box<T>); |
1210 | /// |
1211 | /// impl<T: ?Sized> Deref for MySmartPointer<T> { |
1212 | /// type Target = T; |
1213 | /// fn deref(&self) -> &T { |
1214 | /// &self.0 |
1215 | /// } |
1216 | /// } |
1217 | /// |
1218 | /// // You can always define this trait. (as long as you have #![feature(arbitrary_self_types)]) |
1219 | /// trait MyTrait { |
1220 | /// fn func(self: MySmartPointer<Self>); |
1221 | /// } |
1222 | /// |
1223 | /// // But using `dyn MyTrait` requires #[derive(CoercePointee)]. |
1224 | /// fn call_func(value: MySmartPointer<dyn MyTrait>) { |
1225 | /// value.func(); |
1226 | /// } |
1227 | /// ``` |
1228 | /// If you remove the `#[derive(CoercePointee)]` annotation from the struct, then the above example |
1229 | /// will fail with this error message: |
1230 | /// ```text |
1231 | /// error[E0038]: the trait `MyTrait` is not dyn compatible |
1232 | /// --> src/lib.rs:21:36 |
1233 | /// | |
1234 | /// 17 | fn func(self: MySmartPointer<Self>); |
1235 | /// | -------------------- help: consider changing method `func`'s `self` parameter to be `&self`: `&Self` |
1236 | /// ... |
1237 | /// 21 | fn call_func(value: MySmartPointer<dyn MyTrait>) { |
1238 | /// | ^^^^^^^^^^^ `MyTrait` is not dyn compatible |
1239 | /// | |
1240 | /// note: for a trait to be dyn compatible it needs to allow building a vtable |
1241 | /// for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety> |
1242 | /// --> src/lib.rs:17:19 |
1243 | /// | |
1244 | /// 16 | trait MyTrait { |
1245 | /// | ------- this trait is not dyn compatible... |
1246 | /// 17 | fn func(self: MySmartPointer<Self>); |
1247 | /// | ^^^^^^^^^^^^^^^^^^^^ ...because method `func`'s `self` parameter cannot be dispatched on |
1248 | /// ``` |
1249 | /// |
1250 | /// # Requirements for using the macro |
1251 | /// |
1252 | /// This macro can only be used if: |
1253 | /// * The type is a `#[repr(transparent)]` struct. |
1254 | /// * The type of its non-zero-sized field must either be a standard library pointer type |
1255 | /// (reference, raw pointer, `NonNull`, `Box`, `Rc`, `Arc`, etc.) or another user-defined type |
1256 | /// also using the `#[derive(CoercePointee)]` macro. |
1257 | /// * Zero-sized fields must not mention any generic parameters unless the zero-sized field has |
1258 | /// type [`PhantomData`]. |
1259 | /// |
1260 | /// ## Multiple type parameters |
1261 | /// |
1262 | /// If the type has multiple type parameters, then you must explicitly specify which one should be |
1263 | /// used for dynamic dispatch. For example: |
1264 | /// ``` |
1265 | /// # #![feature(derive_coerce_pointee)] |
1266 | /// # use std::marker::{CoercePointee, PhantomData}; |
1267 | /// #[derive(CoercePointee)] |
1268 | /// #[repr(transparent)] |
1269 | /// struct MySmartPointer<#[pointee] T: ?Sized, U> { |
1270 | /// ptr: Box<T>, |
1271 | /// _phantom: PhantomData<U>, |
1272 | /// } |
1273 | /// ``` |
1274 | /// Specifying `#[pointee]` when the struct has only one type parameter is allowed, but not required. |
1275 | /// |
1276 | /// # Examples |
1277 | /// |
1278 | /// A custom implementation of the `Rc` type: |
1279 | /// ``` |
1280 | /// #![feature(derive_coerce_pointee)] |
1281 | /// use std::marker::CoercePointee; |
1282 | /// use std::ops::Deref; |
1283 | /// use std::ptr::NonNull; |
1284 | /// |
1285 | /// #[derive(CoercePointee)] |
1286 | /// #[repr(transparent)] |
1287 | /// pub struct Rc<T: ?Sized> { |
1288 | /// inner: NonNull<RcInner<T>>, |
1289 | /// } |
1290 | /// |
1291 | /// struct RcInner<T: ?Sized> { |
1292 | /// refcount: usize, |
1293 | /// value: T, |
1294 | /// } |
1295 | /// |
1296 | /// impl<T: ?Sized> Deref for Rc<T> { |
1297 | /// type Target = T; |
1298 | /// fn deref(&self) -> &T { |
1299 | /// let ptr = self.inner.as_ptr(); |
1300 | /// unsafe { &(*ptr).value } |
1301 | /// } |
1302 | /// } |
1303 | /// |
1304 | /// impl<T> Rc<T> { |
1305 | /// pub fn new(value: T) -> Self { |
1306 | /// let inner = Box::new(RcInner { |
1307 | /// refcount: 1, |
1308 | /// value, |
1309 | /// }); |
1310 | /// Self { |
1311 | /// inner: NonNull::from(Box::leak(inner)), |
1312 | /// } |
1313 | /// } |
1314 | /// } |
1315 | /// |
1316 | /// impl<T: ?Sized> Clone for Rc<T> { |
1317 | /// fn clone(&self) -> Self { |
1318 | /// // A real implementation would handle overflow here. |
1319 | /// unsafe { (*self.inner.as_ptr()).refcount += 1 }; |
1320 | /// Self { inner: self.inner } |
1321 | /// } |
1322 | /// } |
1323 | /// |
1324 | /// impl<T: ?Sized> Drop for Rc<T> { |
1325 | /// fn drop(&mut self) { |
1326 | /// let ptr = self.inner.as_ptr(); |
1327 | /// unsafe { (*ptr).refcount -= 1 }; |
1328 | /// if unsafe { (*ptr).refcount } == 0 { |
1329 | /// drop(unsafe { Box::from_raw(ptr) }); |
1330 | /// } |
1331 | /// } |
1332 | /// } |
1333 | /// ``` |
1334 | #[rustc_builtin_macro (CoercePointee, attributes(pointee))] |
1335 | #[allow_internal_unstable (dispatch_from_dyn, coerce_unsized, unsize, coerce_pointee_validated)] |
1336 | #[rustc_diagnostic_item = "CoercePointee" ] |
1337 | #[unstable (feature = "derive_coerce_pointee" , issue = "123430" )] |
1338 | pub macro CoercePointee($item:item) { |
1339 | /* compiler built-in */ |
1340 | } |
1341 | |
1342 | /// A trait that is implemented for ADTs with `derive(CoercePointee)` so that |
1343 | /// the compiler can enforce the derive impls are valid post-expansion, since |
1344 | /// the derive has stricter requirements than if the impls were written by hand. |
1345 | /// |
1346 | /// This trait is not intended to be implemented by users or used other than |
1347 | /// validation, so it should never be stabilized. |
1348 | #[lang = "coerce_pointee_validated" ] |
1349 | #[unstable (feature = "coerce_pointee_validated" , issue = "none" )] |
1350 | #[doc (hidden)] |
1351 | pub trait CoercePointeeValidated { |
1352 | /* compiler built-in */ |
1353 | } |
1354 | |