Rust standard library

library/core/src/marker.rs

This is Rust standard-library source from the compiler version used in the run.

Download Rust file

1 //! Primitive traits and types representing basic properties of types.2 //!3 //! Rust types can be classified in various useful ways according to4 //! their intrinsic properties. These classifications are represented5 //! 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::clone::TrivialClone;18 use crate::cmp;19 use crate::fmt::Debug;20 use crate::hash::{Hash, Hasher};21 use crate::pin::UnsafePinned;22 23 // NOTE: for consistent error messages between `core` and `minicore`, all `diagnostic` attributes24 // should be replicated exactly in `minicore` (if `minicore` defines the item).25 26 /// Implements a given marker trait for multiple types at the same time.27 ///28 /// The basic syntax looks like this:29 /// ```ignore private macro30 /// marker_impls! { MarkerTrait for u8, i8 }31 /// ```32 /// You can also implement `unsafe` traits33 /// ```ignore private macro34 /// marker_impls! { unsafe MarkerTrait for u8, i8 }35 /// ```36 /// Add attributes to all impls:37 /// ```ignore private macro38 /// marker_impls! {39 ///     #[allow(lint)]40 ///     #[unstable(feature = "marker_trait", issue = "none")]41 ///     MarkerTrait for u8, i842 /// }43 /// ```44 /// And use generics:45 /// ```ignore private macro46 /// marker_impls! {47 ///     MarkerTrait for48 ///         u8, i8,49 ///         {T: PointeeSized} *const T,50 ///         {T: PointeeSized} *mut T,51 ///         {T: MarkerTrait} PhantomData<T>,52 ///         u32,53 /// }54 /// ```55 macro marker_impls {56     ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {57         $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {}58         marker_impls! { $(#[$($meta)*])* $Trait for $($($rest)*)? }59     },60     ( $(#[$($meta:tt)*])* $Trait:ident for ) => {},61 62     ( $(#[$($meta:tt)*])* unsafe $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {63         $(#[$($meta)*])* unsafe impl< $($($bounds)*)? > $Trait for $T {}64         marker_impls! { $(#[$($meta)*])* unsafe $Trait for $($($rest)*)? }65     },66     ( $(#[$($meta:tt)*])* unsafe $Trait:ident for ) => {},67 }68 69 /// Types that can be transferred across thread boundaries.70 ///71 /// This trait is automatically implemented when the compiler determines it's72 /// appropriate.73 ///74 /// An example of a non-`Send` type is the reference-counting pointer75 /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same76 /// reference-counted value, they might try to update the reference count at the77 /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic78 /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring79 /// some overhead) and thus is `Send`.80 ///81 /// See [the Nomicon](../../nomicon/send-and-sync.html) and the [`Sync`] trait for more details.82 ///83 /// [`Rc`]: ../../std/rc/struct.Rc.html84 /// [arc]: ../../std/sync/struct.Arc.html85 /// [ub]: ../../reference/behavior-considered-undefined.html86 #[stable(feature = "rust1", since = "1.0.0")]87 #[rustc_diagnostic_item = "Send"]88 #[diagnostic::on_unimplemented(89     message = "`{Self}` cannot be sent between threads safely",90     label = "`{Self}` cannot be sent between threads safely"91 )]92 pub unsafe auto trait Send {93     // empty.94 }95 96 #[stable(feature = "rust1", since = "1.0.0")]97 impl<T: PointeeSized> !Send for *const T {}98 #[stable(feature = "rust1", since = "1.0.0")]99 impl<T: PointeeSized> !Send for *mut T {}100 101 // Most instances arise automatically, but this instance is needed to link up `T: Sync` with102 // `&T: Send` (and it also removes the unsound default instance `T Send` -> `&T: Send` that would103 // otherwise exist).104 #[stable(feature = "rust1", since = "1.0.0")]105 unsafe impl<T: Sync + PointeeSized> Send for &T {}106 107 /// Types with a constant size known at compile time.108 ///109 /// All type parameters have an implicit bound of `Sized`. The special syntax110 /// `?Sized` can be used to remove this bound if it's not appropriate.111 ///112 /// ```113 /// # #![allow(dead_code)]114 /// struct Foo<T>(T);115 /// struct Bar<T: ?Sized>(T);116 ///117 /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]118 /// struct BarUse(Bar<[i32]>); // OK119 /// ```120 ///121 /// The one exception is the implicit `Self` type of a trait. A trait does not122 /// have an implicit `Sized` bound as this is incompatible with [trait object]s123 /// where, by definition, the trait needs to work with all possible implementors,124 /// and thus could be any size.125 ///126 /// Although Rust will let you bind `Sized` to a trait, you won't127 /// be able to use it to form a trait object later:128 ///129 /// ```130 /// # #![allow(unused_variables)]131 /// trait Foo { }132 /// trait Bar: Sized { }133 ///134 /// struct Impl;135 /// impl Foo for Impl { }136 /// impl Bar for Impl { }137 ///138 /// let x: &dyn Foo = &Impl;    // OK139 /// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot be made into an object140 /// ```141 ///142 /// [trait object]: ../../book/ch17-02-trait-objects.html143 #[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 evaluatable151 #[rustc_specialization_trait]152 #[rustc_deny_explicit_impl]153 #[rustc_dyn_incompatible_trait]154 // `Sized` being coinductive, despite having supertraits, is okay as there are no user-written impls,155 // and we know that the supertraits are always implemented if the subtrait is just by looking at156 // the builtin impls.157 #[rustc_coinductive]158 pub trait Sized: MetaSized {159     // Empty.160 }161 162 /// Types with a size that can be determined from pointer metadata.163 #[unstable(feature = "sized_hierarchy", issue = "144404")]164 #[lang = "meta_sized"]165 #[diagnostic::on_unimplemented(166     message = "the size for values of type `{Self}` cannot be known",167     label = "doesn't have a known size"168 )]169 #[fundamental]170 #[rustc_specialization_trait]171 #[rustc_deny_explicit_impl]172 // `MetaSized` being coinductive, despite having supertraits, is okay for the same reasons as173 // `Sized` above.174 #[rustc_coinductive]175 pub trait MetaSized: PointeeSized {176     // Empty177 }178 179 /// Types that may or may not have a size.180 #[unstable(feature = "sized_hierarchy", issue = "144404")]181 #[lang = "pointee_sized"]182 #[diagnostic::on_unimplemented(183     message = "values of type `{Self}` may or may not have a size",184     label = "may or may not have a known size"185 )]186 #[fundamental]187 #[rustc_specialization_trait]188 #[rustc_deny_explicit_impl]189 #[rustc_coinductive]190 pub trait PointeeSized {191     // Empty192 }193 194 /// Types that can be "unsized" to a dynamically-sized type.195 ///196 /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and197 /// `Unsize<dyn fmt::Debug>`.198 ///199 /// All implementations of `Unsize` are provided automatically by the compiler.200 /// Those implementations are:201 ///202 /// - Arrays `[T; N]` implement `Unsize<[T]>`.203 /// - A type implements `Unsize<dyn Trait + 'a>` if all of these conditions are met:204 ///   - The type implements `Trait`.205 ///   - `Trait` is dyn-compatible[^1].206 ///   - The type is sized.207 ///   - The type outlives `'a`.208 /// - Trait objects `dyn TraitA + AutoA... + 'a` implement `Unsize<dyn TraitB + AutoB... + 'b>`209 ///    if all of these conditions are met:210 ///   - `TraitB` is a supertrait of `TraitA`.211 ///   - `AutoB...` is a subset of `AutoA...`.212 ///   - `'a` outlives `'b`.213 /// - Structs `Foo<..., T1, ..., Tn, ...>` implement `Unsize<Foo<..., U1, ..., Un, ...>>`214 ///   where any number of (type and const) parameters may be changed if all of these conditions215 ///   are met:216 ///   - Only the last field of `Foo` has a type involving the parameters `T1`, ..., `Tn`.217 ///   - All other parameters of the struct are equal.218 ///   - `Field<T1, ..., Tn>: Unsize<Field<U1, ..., Un>>`, where `Field<...>` stands for the actual219 ///     type of the struct's last field.220 ///221 /// `Unsize` is used along with [`ops::CoerceUnsized`] to allow222 /// "user-defined" containers such as [`Rc`] to contain dynamically-sized223 /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]224 /// for more details.225 ///226 /// [`ops::CoerceUnsized`]: crate::ops::CoerceUnsized227 /// [`Rc`]: ../../std/rc/struct.Rc.html228 /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md229 /// [nomicon-coerce]: ../../nomicon/coercions.html230 /// [^1]: Formerly known as *object safe*.231 #[unstable(feature = "unsize", issue = "18598")]232 #[lang = "unsize"]233 #[rustc_deny_explicit_impl]234 #[rustc_dyn_incompatible_trait]235 pub trait Unsize<T: PointeeSized>: PointeeSized {236     // Empty.237 }238 239 /// Required trait for constants used in pattern matches.240 ///241 /// Constants are only allowed as patterns if (a) their type implements242 /// `PartialEq`, and (b) interpreting the value of the constant as a pattern243 /// is equivalent to calling `PartialEq`. This ensures that constants used as244 /// patterns cannot expose implementation details in an unexpected way or245 /// cause semver hazards.246 ///247 /// This trait ensures point (b).248 /// Any type that derives `PartialEq` automatically implements this trait.249 ///250 /// Implementing this trait (which is unstable) is a way for type authors to explicitly allow251 /// comparing const values of this type; that operation will recursively compare all fields252 /// (including private fields), even if that behavior differs from `PartialEq`. This can make it253 /// semver-breaking to add further private fields to a type.254 #[unstable(feature = "structural_match", issue = "31434")]255 #[diagnostic::on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")]256 #[lang = "structural_peq"]257 pub trait StructuralPartialEq {258     // Empty.259 }260 261 marker_impls! {262     #[unstable(feature = "structural_match", issue = "31434")]263     StructuralPartialEq for264         usize, u8, u16, u32, u64, u128,265         isize, i8, i16, i32, i64, i128,266         bool,267         char,268         str /* Technically requires `[u8]: StructuralPartialEq` */,269         (),270         {T, const N: usize} [T; N],271         {T} [T],272         {T: PointeeSized} &T,273 }274 275 /// Types whose values can be duplicated simply by copying bits.276 ///277 /// By default, variable bindings have 'move semantics.' In other278 /// words:279 ///280 /// ```281 /// #[derive(Debug)]282 /// struct Foo;283 ///284 /// let x = Foo;285 ///286 /// let y = x;287 ///288 /// // `x` has moved into `y`, and so cannot be used289 ///290 /// // println!("{x:?}"); // error: use of moved value291 /// ```292 ///293 /// However, if a type implements `Copy`, it instead has 'copy semantics':294 ///295 /// ```296 /// // We can derive a `Copy` implementation. `Clone` is also required, as it's297 /// // a supertrait of `Copy`.298 /// #[derive(Debug, Copy, Clone)]299 /// struct Foo;300 ///301 /// let x = Foo;302 ///303 /// let y = x;304 ///305 /// // `y` is a copy of `x`306 ///307 /// println!("{x:?}"); // A-OK!308 /// ```309 ///310 /// It's important to note that in these two examples, the only difference is whether you311 /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move312 /// can result in bits being copied in memory, although this is sometimes optimized away.313 ///314 /// ## How can I implement `Copy`?315 ///316 /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:317 ///318 /// ```319 /// #[derive(Copy, Clone)]320 /// struct MyStruct;321 /// ```322 ///323 /// You can also implement `Copy` and `Clone` manually:324 ///325 /// ```326 /// struct MyStruct;327 ///328 /// impl Copy for MyStruct { }329 ///330 /// impl Clone for MyStruct {331 ///     fn clone(&self) -> MyStruct {332 ///         *self333 ///     }334 /// }335 /// ```336 ///337 /// There is a small difference between the two. The `derive` strategy will also place a `Copy`338 /// bound on type parameters:339 ///340 /// ```341 /// #[derive(Clone)]342 /// struct MyStruct<T>(T);343 ///344 /// impl<T: Copy> Copy for MyStruct<T> { }345 /// ```346 ///347 /// This isn't always desired. For example, shared references (`&T`) can be copied regardless of348 /// whether `T` is `Copy`. Likewise, a generic struct containing markers such as [`PhantomData`]349 /// could potentially be duplicated with a bit-wise copy.350 ///351 /// ## What's the difference between `Copy` and `Clone`?352 ///353 /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of354 /// `Copy` is not overloadable; it is always a simple bit-wise copy.355 ///356 /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can357 /// provide any type-specific behavior necessary to duplicate values safely. For example,358 /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string359 /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the360 /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]361 /// but not `Copy`.362 ///363 /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement364 /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`365 /// (see the example above).366 ///367 /// ## When can my type be `Copy`?368 ///369 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this370 /// struct can be `Copy`:371 ///372 /// ```373 /// # #[allow(dead_code)]374 /// #[derive(Copy, Clone)]375 /// struct Point {376 ///    x: i32,377 ///    y: i32,378 /// }379 /// ```380 ///381 /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.382 /// By contrast, consider383 ///384 /// ```385 /// # #![allow(dead_code)]386 /// # struct Point;387 /// struct PointList {388 ///     points: Vec<Point>,389 /// }390 /// ```391 ///392 /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we393 /// attempt to derive a `Copy` implementation, we'll get an error:394 ///395 /// ```text396 /// the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy`397 /// ```398 ///399 /// Shared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds400 /// shared references of types `T` that are *not* `Copy`. Consider the following struct,401 /// which can implement `Copy`, because it only holds a *shared reference* to our non-`Copy`402 /// type `PointList` from above:403 ///404 /// ```405 /// # #![allow(dead_code)]406 /// # struct PointList;407 /// #[derive(Copy, Clone)]408 /// struct PointListWrapper<'a> {409 ///     point_list_ref: &'a PointList,410 /// }411 /// ```412 ///413 /// ## When *can't* my type be `Copy`?414 ///415 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased416 /// mutable reference. Copying [`String`] would duplicate responsibility for managing the417 /// [`String`]'s buffer, leading to a double free.418 ///419 /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's420 /// managing some resource besides its own [`size_of::<T>`] bytes.421 ///422 /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get423 /// the error [E0204].424 ///425 /// [E0204]: ../../error_codes/E0204.html426 ///427 /// ## When *should* my type be `Copy`?428 ///429 /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,430 /// that implementing `Copy` is part of the public API of your type. If the type might become431 /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to432 /// avoid a breaking API change.433 ///434 /// ## Additional implementors435 ///436 /// In addition to the [implementors listed below][impls],437 /// the following types also implement `Copy`:438 ///439 /// * Function item types (i.e., the distinct types defined for each function)440 /// * Function pointer types (e.g., `fn() -> i32`)441 /// * Closure types, if they capture no value from the environment442 ///   or if all such captured values implement `Copy` themselves.443 ///   Note that variables captured by shared reference always implement `Copy`444 ///   (even if the referent doesn't),445 ///   while variables captured by mutable reference never implement `Copy`.446 ///447 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html448 /// [`String`]: ../../std/string/struct.String.html449 /// [`size_of::<T>`]: size_of450 /// [impls]: #implementors451 #[stable(feature = "rust1", since = "1.0.0")]452 #[lang = "copy"]453 #[rustc_diagnostic_item = "Copy"]454 pub trait Copy: Clone {455     // Empty.456 }457 458 /// Derive macro generating an impl of the trait `Copy`.459 #[rustc_builtin_macro]460 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]461 #[allow_internal_unstable(core_intrinsics, derive_clone_copy_internals)]462 pub macro Copy($item:item) {463     /* compiler built-in */464 }465 466 // Implementations of `Copy` for primitive types.467 //468 // Implementations that cannot be described in Rust469 // are implemented in `traits::SelectionContext::copy_clone_conditions()`470 // in `rustc_trait_selection`.471 marker_impls! {472     #[stable(feature = "rust1", since = "1.0.0")]473     Copy for474         usize, u8, u16, u32, u64, u128,475         isize, i8, i16, i32, i64, i128,476         f16, f32, f64, f128,477         bool, char,478         {T: PointeeSized} *const T,479         {T: PointeeSized} *mut T,480 481 }482 483 #[unstable(feature = "never_type", issue = "35121")]484 impl Copy for ! {}485 486 /// Shared references can be copied, but mutable references *cannot*!487 #[stable(feature = "rust1", since = "1.0.0")]488 impl<T: PointeeSized> Copy for &T {}489 490 /// Marker trait for the types that are allowed in union fields and unsafe491 /// binder types.492 ///493 /// Implemented for:494 /// * `&T`, `&mut T` for all `T`,495 /// * `ManuallyDrop<T>` for all `T`,496 /// * tuples and arrays whose elements implement `BikeshedGuaranteedNoDrop`,497 /// * or otherwise, all types that are `Copy`.498 ///499 /// Notably, this doesn't include all trivially-destructible types for semver500 /// reasons.501 ///502 /// Bikeshed name for now. This trait does not do anything other than reflect the503 /// set of types that are allowed within unions for field validity.504 #[unstable(feature = "bikeshed_guaranteed_no_drop", issue = "none")]505 #[lang = "bikeshed_guaranteed_no_drop"]506 #[rustc_deny_explicit_impl]507 #[rustc_dyn_incompatible_trait]508 #[doc(hidden)]509 pub trait BikeshedGuaranteedNoDrop {}510 511 /// Types for which it is safe to share references between threads.512 ///513 /// This trait is automatically implemented when the compiler determines514 /// it's appropriate.515 ///516 /// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is517 /// [`Send`]. In other words, if there is no possibility of518 /// [undefined behavior][ub] (including data races) when passing519 /// `&T` references between threads.520 ///521 /// As one would expect, primitive types like [`u8`] and [`f64`]522 /// are all [`Sync`], and so are simple aggregate types containing them,523 /// like tuples, structs and enums. More examples of basic [`Sync`]524 /// types include "immutable" types like `&T`, and those with simple525 /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and526 /// most other collection types. (Generic parameters need to be [`Sync`]527 /// for their container to be [`Sync`].)528 ///529 /// A somewhat surprising consequence of the definition is that `&mut T`530 /// is `Sync` (if `T` is `Sync`) even though it seems like that might531 /// provide unsynchronized mutation. The trick is that a mutable532 /// reference behind a shared reference (that is, `& &mut T`)533 /// becomes read-only, as if it were a `& &T`. Hence there is no risk534 /// of a data race.535 ///536 /// A shorter overview of how [`Sync`] and [`Send`] relate to referencing:537 /// * `&T` is [`Send`] if and only if `T` is [`Sync`]538 /// * `&mut T` is [`Send`] if and only if `T` is [`Send`]539 /// * `&T` and `&mut T` are [`Sync`] if and only if `T` is [`Sync`]540 ///541 /// Types that are not `Sync` are those that have "interior542 /// mutability" in a non-thread-safe form, such as [`Cell`][cell]543 /// and [`RefCell`][refcell]. These types allow for mutation of544 /// their contents even through an immutable, shared reference. For545 /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires546 /// only a shared reference [`&Cell<T>`][cell]. The method performs no547 /// synchronization, thus [`Cell`][cell] cannot be `Sync`.548 ///549 /// Another example of a non-`Sync` type is the reference-counting550 /// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone551 /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.552 ///553 /// For cases when one does need thread-safe interior mutability,554 /// Rust provides [atomic data types], as well as explicit locking via555 /// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types556 /// ensure that any mutation cannot cause data races, hence the types557 /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe558 /// analogue of [`Rc`][rc].559 ///560 /// Any types with interior mutability must also use the561 /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which562 /// can be mutated through a shared reference. Failing to doing this is563 /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing564 /// from `&T` to `&mut T` is invalid.565 ///566 /// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.567 ///568 /// [box]: ../../std/boxed/struct.Box.html569 /// [vec]: ../../std/vec/struct.Vec.html570 /// [cell]: crate::cell::Cell571 /// [refcell]: crate::cell::RefCell572 /// [rc]: ../../std/rc/struct.Rc.html573 /// [arc]: ../../std/sync/struct.Arc.html574 /// [atomic data types]: crate::sync::atomic575 /// [mutex]: ../../std/sync/struct.Mutex.html576 /// [rwlock]: ../../std/sync/struct.RwLock.html577 /// [unsafecell]: crate::cell::UnsafeCell578 /// [ub]: ../../reference/behavior-considered-undefined.html579 /// [transmute]: crate::mem::transmute580 /// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html581 #[stable(feature = "rust1", since = "1.0.0")]582 #[rustc_diagnostic_item = "Sync"]583 #[lang = "sync"]584 #[rustc_on_unimplemented(585     on(586         Self = "core::cell::once::OnceCell<T>",587         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead"588     ),589     on(590         Self = "core::cell::Cell<u8>",591         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead",592     ),593     on(594         Self = "core::cell::Cell<u16>",595         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead",596     ),597     on(598         Self = "core::cell::Cell<u32>",599         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead",600     ),601     on(602         Self = "core::cell::Cell<u64>",603         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead",604     ),605     on(606         Self = "core::cell::Cell<usize>",607         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead",608     ),609     on(610         Self = "core::cell::Cell<i8>",611         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead",612     ),613     on(614         Self = "core::cell::Cell<i16>",615         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead",616     ),617     on(618         Self = "core::cell::Cell<i32>",619         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead",620     ),621     on(622         Self = "core::cell::Cell<i64>",623         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead",624     ),625     on(626         Self = "core::cell::Cell<isize>",627         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead",628     ),629     on(630         Self = "core::cell::Cell<bool>",631         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead",632     ),633     on(634         all(635             Self = "core::cell::Cell<T>",636             not(Self = "core::cell::Cell<u8>"),637             not(Self = "core::cell::Cell<u16>"),638             not(Self = "core::cell::Cell<u32>"),639             not(Self = "core::cell::Cell<u64>"),640             not(Self = "core::cell::Cell<usize>"),641             not(Self = "core::cell::Cell<i8>"),642             not(Self = "core::cell::Cell<i16>"),643             not(Self = "core::cell::Cell<i32>"),644             not(Self = "core::cell::Cell<i64>"),645             not(Self = "core::cell::Cell<isize>"),646             not(Self = "core::cell::Cell<bool>")647         ),648         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`",649     ),650     on(651         Self = "core::cell::RefCell<T>",652         note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead",653     ),654     message = "`{Self}` cannot be shared between threads safely",655     label = "`{Self}` cannot be shared between threads safely"656 )]657 pub unsafe auto trait Sync {658     // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`659     // lands in beta, and it has been extended to check whether a closure is660     // anywhere in the requirement chain, extend it as such (#48534):661     // ```662     // on(663     //     closure,664     //     note="`{Self}` cannot be shared safely, consider marking the closure `move`"665     // ),666     // ```667 668     // Empty669 }670 671 #[stable(feature = "rust1", since = "1.0.0")]672 impl<T: PointeeSized> !Sync for *const T {}673 #[stable(feature = "rust1", since = "1.0.0")]674 impl<T: PointeeSized> !Sync for *mut T {}675 676 /// Zero-sized type used to mark things that "act like" they own a `T`.677 ///678 /// Adding a `PhantomData<T>` field to your type tells the compiler that your679 /// type acts as though it stores a value of type `T`, even though it doesn't680 /// really. This information is used when computing certain safety properties.681 ///682 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see683 /// [the Nomicon](../../nomicon/phantom-data.html).684 ///685 /// # A ghastly note ๐Ÿ‘ป๐Ÿ‘ป๐Ÿ‘ป686 ///687 /// Though they both have scary names, `PhantomData` and 'phantom types' are688 /// related, but not identical. A phantom type parameter is simply a type689 /// parameter which is never used. In Rust, this often causes the compiler to690 /// complain, and the solution is to add a "dummy" use by way of `PhantomData`.691 ///692 /// # Examples693 ///694 /// ## Unused lifetime parameters695 ///696 /// Perhaps the most common use case for `PhantomData` is a struct that has an697 /// unused lifetime parameter, typically as part of some unsafe code. For698 /// example, here is a struct `Slice` that has two pointers of type `*const T`,699 /// presumably pointing into an array somewhere:700 ///701 /// ```compile_fail,E0392702 /// struct Slice<'a, T> {703 ///     start: *const T,704 ///     end: *const T,705 /// }706 /// ```707 ///708 /// The intention is that the underlying data is only valid for the709 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this710 /// intent is not expressed in the code, since there are no uses of711 /// the lifetime `'a` and hence it is not clear what data it applies712 /// to. We can correct this by telling the compiler to act *as if* the713 /// `Slice` struct contained a reference `&'a T`:714 ///715 /// ```716 /// use std::marker::PhantomData;717 ///718 /// # #[allow(dead_code)]719 /// struct Slice<'a, T> {720 ///     start: *const T,721 ///     end: *const T,722 ///     phantom: PhantomData<&'a T>,723 /// }724 /// ```725 ///726 /// This also in turn infers the lifetime bound `T: 'a`, indicating727 /// that any references in `T` are valid over the lifetime `'a`.728 ///729 /// When initializing a `Slice` you simply provide the value730 /// `PhantomData` for the field `phantom`:731 ///732 /// ```733 /// # #![allow(dead_code)]734 /// # use std::marker::PhantomData;735 /// # struct Slice<'a, T> {736 /// #     start: *const T,737 /// #     end: *const T,738 /// #     phantom: PhantomData<&'a T>,739 /// # }740 /// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {741 ///     let ptr = vec.as_ptr();742 ///     Slice {743 ///         start: ptr,744 ///         end: unsafe { ptr.add(vec.len()) },745 ///         phantom: PhantomData,746 ///     }747 /// }748 /// ```749 ///750 /// ## Unused type parameters751 ///752 /// It sometimes happens that you have unused type parameters which753 /// indicate what type of data a struct is "tied" to, even though that754 /// data is not actually found in the struct itself. Here is an755 /// example where this arises with [FFI]. The foreign interface uses756 /// handles of type `*mut ()` to refer to Rust values of different757 /// types. We track the Rust type using a phantom type parameter on758 /// the struct `ExternalResource` which wraps a handle.759 ///760 /// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code761 ///762 /// ```763 /// # #![allow(dead_code)]764 /// # trait ResType { }765 /// # struct ParamType;766 /// # mod foreign_lib {767 /// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }768 /// #     pub fn do_stuff(_: *mut (), _: usize) {}769 /// # }770 /// # fn convert_params(_: ParamType) -> usize { 42 }771 /// use std::marker::PhantomData;772 ///773 /// struct ExternalResource<R> {774 ///    resource_handle: *mut (),775 ///    resource_type: PhantomData<R>,776 /// }777 ///778 /// impl<R: ResType> ExternalResource<R> {779 ///     fn new() -> Self {780 ///         let size_of_res = size_of::<R>();781 ///         Self {782 ///             resource_handle: foreign_lib::new(size_of_res),783 ///             resource_type: PhantomData,784 ///         }785 ///     }786 ///787 ///     fn do_stuff(&self, param: ParamType) {788 ///         let foreign_params = convert_params(param);789 ///         foreign_lib::do_stuff(self.resource_handle, foreign_params);790 ///     }791 /// }792 /// ```793 ///794 /// ## Ownership and the drop check795 ///796 /// The exact interaction of `PhantomData` with drop check **may change in the future**.797 ///798 /// Currently, adding a field of type `PhantomData<T>` indicates that your type *owns* data of type799 /// `T` in very rare circumstances. This in turn has effects on the Rust compiler's [drop check]800 /// analysis. For the exact rules, see the [drop check] documentation.801 ///802 /// ## Layout803 ///804 /// For all `T`, the following are guaranteed:805 /// * `size_of::<PhantomData<T>>() == 0`806 /// * `align_of::<PhantomData<T>>() == 1`807 ///808 /// [drop check]: Drop#drop-check809 #[lang = "phantom_data"]810 #[stable(feature = "rust1", since = "1.0.0")]811 pub struct PhantomData<T: PointeeSized>;812 813 #[stable(feature = "rust1", since = "1.0.0")]814 impl<T: PointeeSized> Hash for PhantomData<T> {815     #[inline]816     fn hash<H: Hasher>(&self, _: &mut H) {}817 }818 819 #[stable(feature = "rust1", since = "1.0.0")]820 impl<T: PointeeSized> cmp::PartialEq for PhantomData<T> {821     fn eq(&self, _other: &PhantomData<T>) -> bool {822         true823     }824 }825 826 #[stable(feature = "rust1", since = "1.0.0")]827 impl<T: PointeeSized> cmp::Eq for PhantomData<T> {}828 829 #[stable(feature = "rust1", since = "1.0.0")]830 impl<T: PointeeSized> cmp::PartialOrd for PhantomData<T> {831     fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<cmp::Ordering> {832         Option::Some(cmp::Ordering::Equal)833     }834 }835 836 #[stable(feature = "rust1", since = "1.0.0")]837 impl<T: PointeeSized> cmp::Ord for PhantomData<T> {838     fn cmp(&self, _other: &PhantomData<T>) -> cmp::Ordering {839         cmp::Ordering::Equal840     }841 }842 843 #[stable(feature = "rust1", since = "1.0.0")]844 impl<T: PointeeSized> Copy for PhantomData<T> {}845 846 #[stable(feature = "rust1", since = "1.0.0")]847 impl<T: PointeeSized> Clone for PhantomData<T> {848     fn clone(&self) -> Self {849         *self850     }851 }852 853 #[doc(hidden)]854 #[unstable(feature = "trivial_clone", issue = "none")]855 unsafe impl<T: PointeeSized> TrivialClone for PhantomData<T> {}856 857 #[stable(feature = "rust1", since = "1.0.0")]858 #[rustc_const_unstable(feature = "const_default", issue = "143894")]859 const impl<T: PointeeSized> Default for PhantomData<T> {860     fn default() -> Self {861         Self862     }863 }864 865 #[unstable(feature = "structural_match", issue = "31434")]866 impl<T: PointeeSized> StructuralPartialEq for PhantomData<T> {}867 868 /// Compiler-internal trait used to indicate the type of enum discriminants.869 ///870 /// This trait is automatically implemented for every type and does not add any871 /// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute872 /// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.873 ///874 /// [`mem::Discriminant`]: crate::mem::Discriminant875 #[unstable(876     feature = "discriminant_kind",877     issue = "none",878     reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"879 )]880 #[lang = "discriminant_kind"]881 #[rustc_deny_explicit_impl]882 #[rustc_dyn_incompatible_trait]883 pub trait DiscriminantKind {884     /// The type of the discriminant, which must satisfy the trait885     /// bounds required by `mem::Discriminant`.886     #[lang = "discriminant_type"]887     type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;888 }889 890 /// Used to determine whether a type contains891 /// any `UnsafeCell` internally, but not through an indirection.892 /// This affects, for example, whether a `static` of that type is893 /// placed in read-only static memory or writable static memory.894 /// This can be used to declare that a constant with a generic type895 /// will not contain interior mutability, and subsequently allow896 /// placing the constant behind references.897 ///898 /// # Safety899 ///900 /// This trait is a core part of the language, it is just expressed as a trait in libcore for901 /// convenience. Do *not* implement it for other types.902 // FIXME: Eventually this trait should become `#[rustc_deny_explicit_impl]`.903 // That requires porting the impls below to native internal impls.904 #[lang = "freeze"]905 #[unstable(feature = "freeze", issue = "121675")]906 pub unsafe auto trait Freeze {}907 908 #[unstable(feature = "freeze", issue = "121675")]909 impl<T: PointeeSized> !Freeze for UnsafeCell<T> {}910 marker_impls! {911     #[unstable(feature = "freeze", issue = "121675")]912     unsafe Freeze for913         {T: PointeeSized} PhantomData<T>,914         {T: PointeeSized} *const T,915         {T: PointeeSized} *mut T,916         {T: PointeeSized} &T,917         {T: PointeeSized} &mut T,918 }919 920 /// Used to determine whether a type contains any `UnsafePinned` (or `PhantomPinned`) internally,921 /// but not through an indirection. This affects, for example, whether we emit `noalias` metadata922 /// for `&mut T` or not.923 ///924 /// This is part of [RFC 3467](https://rust-lang.github.io/rfcs/3467-unsafe-pinned.html), and is925 /// tracked by [#125735](https://github.com/rust-lang/rust/issues/125735).926 #[lang = "unsafe_unpin"]927 #[unstable(feature = "unsafe_unpin", issue = "125735")]928 pub unsafe auto trait UnsafeUnpin {}929 930 #[unstable(feature = "unsafe_unpin", issue = "125735")]931 impl<T: PointeeSized> !UnsafeUnpin for UnsafePinned<T> {}932 marker_impls! {933 #[unstable(feature = "unsafe_unpin", issue = "125735")]934     unsafe UnsafeUnpin for935         {T: PointeeSized} PhantomData<T>,936         {T: PointeeSized} *const T,937         {T: PointeeSized} *mut T,938         {T: PointeeSized} &T,939         {T: PointeeSized} &mut T,940         {T: PointeeSized} pattern_type!(*const T is !null),941         {T: PointeeSized} pattern_type!(*mut T is !null),942 }943 944 /// Types that do not require any pinning guarantees.945 ///946 /// For information on what "pinning" is, see the [`pin` module] documentation.947 ///948 /// Implementing the `Unpin` trait for `T` expresses the fact that `T` is pinning-agnostic:949 /// it shall not expose nor rely on any pinning guarantees. This, in turn, means that a950 /// `Pin`-wrapped pointer to such a type can feature a *fully unrestricted* API.951 /// In other words, if `T: Unpin`, a value of type `T` will *not* be bound by the invariants952 /// which pinning otherwise offers, even when "pinned" by a [`Pin<Ptr>`] pointing at it.953 /// When a value of type `T` is pointed at by a [`Pin<Ptr>`], [`Pin`] will not restrict access954 /// to the pointee value like it normally would, thus allowing the user to do anything that they955 /// normally could with a non-[`Pin`]-wrapped `Ptr` to that value.956 ///957 /// The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use958 /// of [`Pin`] for soundness for some types, but which also want to be used by other types that959 /// don't care about pinning. The prime example of such an API is [`Future::poll`]. There are many960 /// [`Future`] types that don't care about pinning. These futures can implement `Unpin` and961 /// therefore get around the pinning related restrictions in the API, while still allowing the962 /// subset of [`Future`]s which *do* require pinning to be implemented soundly.963 ///964 /// For more discussion on the consequences of [`Unpin`] within the wider scope of the pinning965 /// system, see the [section about `Unpin`] in the [`pin` module].966 ///967 /// `Unpin` has no consequence at all for non-pinned data. In particular, [`mem::replace`] happily968 /// moves `!Unpin` data, which would be immovable when pinned ([`mem::replace`] works for any969 /// `&mut T`, not just when `T: Unpin`).970 ///971 /// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped972 /// inside a [`Pin<Ptr>`] pointing at it. This is because you cannot (safely) use a973 /// [`Pin<Ptr>`] to get a `&mut T` to its pointee value, which you would need to call974 /// [`mem::replace`], and *that* is what makes this system work.975 ///976 /// So this, for example, can only be done on types implementing `Unpin`:977 ///978 /// ```rust979 /// # #![allow(unused_must_use)]980 /// use std::mem;981 /// use std::pin::Pin;982 ///983 /// let mut string = "this".to_string();984 /// let mut pinned_string = Pin::new(&mut string);985 ///986 /// // We need a mutable reference to call `mem::replace`.987 /// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,988 /// // but that is only possible because `String` implements `Unpin`.989 /// mem::replace(&mut *pinned_string, "other".to_string());990 /// ```991 ///992 /// This trait is automatically implemented for almost every type. The compiler is free993 /// to take the conservative stance of marking types as [`Unpin`] so long as all of the types that994 /// compose its fields are also [`Unpin`]. This is because if a type implements [`Unpin`], then it995 /// is unsound for that type's implementation to rely on pinning-related guarantees for soundness,996 /// *even* when viewed through a "pinning" pointer! It is the responsibility of the implementor of997 /// a type that relies upon pinning for soundness to ensure that type is *not* marked as [`Unpin`]998 /// by adding [`PhantomPinned`] field. For more details, see the [`pin` module] docs.999 ///1000 /// [`mem::replace`]: crate::mem::replace "mem replace"1001 /// [`Future`]: crate::future::Future "Future"1002 /// [`Future::poll`]: crate::future::Future::poll "Future poll"1003 /// [`Pin`]: crate::pin::Pin "Pin"1004 /// [`Pin<Ptr>`]: crate::pin::Pin "Pin"1005 /// [`pin` module]: crate::pin "pin module"1006 /// [section about `Unpin`]: crate::pin#unpin "pin module docs about unpin"1007 /// [`unsafe`]: ../../std/keyword.unsafe.html "keyword unsafe"1008 #[stable(feature = "pin", since = "1.33.0")]1009 #[diagnostic::on_unimplemented(1010     note = "consider using the `pin!` macro\nconsider using `Box::pin` if you need to access the pinned value outside of the current scope",1011     message = "`{Self}` cannot be unpinned"1012 )]1013 #[lang = "unpin"]1014 pub auto trait Unpin {}1015 1016 /// A marker type which does not implement `Unpin`.1017 ///1018 /// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.1019 //1020 // FIXME(unsafe_pinned): This is *not* a stable guarantee we want to make, at least not yet.1021 // Note that for backwards compatibility with the new [`UnsafePinned`] wrapper type, placing this1022 // marker in your struct acts as if you wrapped the entire struct in an `UnsafePinned`. This type1023 // will likely eventually be deprecated, and all new code should be using `UnsafePinned` instead.1024 #[stable(feature = "pin", since = "1.33.0")]1025 #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]1026 pub struct PhantomPinned;1027 1028 #[stable(feature = "pin", since = "1.33.0")]1029 impl !Unpin for PhantomPinned {}1030 1031 // This is a small hack to allow existing code which uses PhantomPinned to opt-out of noalias to1032 // continue working. Ideally PhantomPinned could just wrap an `UnsafePinned<()>` to get the same1033 // effect, but we can't add a new field to an already stable unit struct -- that would be a breaking1034 // change.1035 #[unstable(feature = "unsafe_unpin", issue = "125735")]1036 impl !UnsafeUnpin for PhantomPinned {}1037 1038 marker_impls! {1039     #[stable(feature = "pin", since = "1.33.0")]1040     Unpin for1041         {T: PointeeSized} &T,1042         {T: PointeeSized} &mut T,1043 }1044 1045 marker_impls! {1046     #[stable(feature = "pin_raw", since = "1.38.0")]1047     Unpin for1048         {T: PointeeSized} *const T,1049         {T: PointeeSized} *mut T,1050 }1051 1052 /// A marker for types that can be dropped.1053 ///1054 /// This should be used for `[const]` bounds,1055 /// as non-const bounds will always hold for every type.1056 #[unstable(feature = "const_destruct", issue = "133214")]1057 #[rustc_const_unstable(feature = "const_destruct", issue = "133214")]1058 #[lang = "destruct"]1059 #[diagnostic::on_unimplemented(message = "can't drop `{Self}`")]1060 #[rustc_deny_explicit_impl]1061 #[rustc_dyn_incompatible_trait]1062 pub const trait Destruct: PointeeSized {}1063 1064 /// A marker for tuple types.1065 ///1066 /// The implementation of this trait is built-in and cannot be implemented1067 /// for any user type.1068 #[unstable(feature = "tuple_trait", issue = "none")]1069 #[lang = "tuple_trait"]1070 #[diagnostic::on_unimplemented(message = "`{Self}` is not a tuple")]1071 #[rustc_deny_explicit_impl]1072 #[rustc_dyn_incompatible_trait]1073 pub trait Tuple {}1074 1075 /// A marker for types which can be used as types of `const` generic parameters.1076 ///1077 /// These types must have a proper equivalence relation (`Eq`) and it must be automatically1078 /// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring1079 /// that all fields are also `ConstParamTy`, which implies that recursively, all fields1080 /// are `StructuralPartialEq`.1081 #[lang = "const_param_ty"]1082 #[unstable(feature = "const_param_ty_trait", issue = "95174", implied_by = "unsized_const_params")]1083 #[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")]1084 #[allow(multiple_supertrait_upcastable)]1085 // We name this differently than the derive macro so that the `adt_const_params` can1086 // be used independently of `unsized_const_params` without requiring a full path1087 // to the derive macro every time it is used. This should be renamed on stabilization.1088 pub trait ConstParamTy_: StructuralPartialEq + Eq {}1089 1090 /// Derive macro generating an impl of the trait `ConstParamTy`.1091 #[rustc_builtin_macro]1092 #[allow_internal_unstable(const_param_ty_trait)]1093 #[unstable(feature = "min_adt_const_params", issue = "154042", implied_by = "adt_const_params")]1094 pub macro ConstParamTy($item:item) {1095     /* compiler built-in */1096 }1097 1098 // For `adt_const_params` to be recognized as a feature1099 #[unstable(feature = "adt_const_params", issue = "95174")]1100 const _: () = ();1101 1102 // FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure`1103 marker_impls! {1104     #[unstable(feature = "min_adt_const_params", issue = "154042")]1105     ConstParamTy_ for1106         usize, u8, u16, u32, u64, u128,1107         isize, i8, i16, i32, i64, i128,1108         bool,1109         char,1110         (),1111         {T: ConstParamTy_, const N: usize} [T; N],1112 }1113 1114 marker_impls! {1115     #[unstable(feature = "unsized_const_params", issue = "95174")]1116     #[unstable_feature_bound(unsized_const_params)]1117     ConstParamTy_ for1118         str,1119         {T: ConstParamTy_} [T],1120         {T: ConstParamTy_ + ?Sized} &T,1121 }1122 1123 /// A common trait implemented by all function pointers.1124 //1125 // Note that while the trait is internal and unstable it is nevertheless1126 // exposed as a public bound of the stable `core::ptr::fn_addr_eq` function.1127 #[unstable(1128     feature = "fn_ptr_trait",1129     issue = "none",1130     reason = "internal trait for implementing various traits for all function pointers"1131 )]1132 #[lang = "fn_ptr_trait"]1133 #[rustc_deny_explicit_impl]1134 #[rustc_dyn_incompatible_trait]1135 pub trait FnPtr: Copy + Clone {1136     /// Returns the address of the function pointer.1137     #[lang = "fn_ptr_addr"]1138     fn addr(self) -> *const ();1139 }1140 1141 /// Derive macro that makes a smart pointer usable with trait objects.1142 ///1143 /// # What this macro does1144 ///1145 /// This macro is intended to be used with user-defined pointer types, and makes it possible to1146 /// perform coercions on the pointee of the user-defined pointer. There are two aspects to this:1147 ///1148 /// ## Unsizing coercions of the pointee1149 ///1150 /// By using the macro, the following example will compile:1151 /// ```1152 /// #![feature(derive_coerce_pointee)]1153 /// use std::marker::CoercePointee;1154 /// use std::ops::Deref;1155 ///1156 /// #[derive(CoercePointee)]1157 /// #[repr(transparent)]1158 /// struct MySmartPointer<T: ?Sized>(Box<T>);1159 ///1160 /// impl<T: ?Sized> Deref for MySmartPointer<T> {1161 ///     type Target = T;1162 ///     fn deref(&self) -> &T {1163 ///         &self.01164 ///     }1165 /// }1166 ///1167 /// trait MyTrait {}1168 ///1169 /// impl MyTrait for i32 {}1170 ///1171 /// fn main() {1172 ///     let ptr: MySmartPointer<i32> = MySmartPointer(Box::new(4));1173 ///1174 ///     // This coercion would be an error without the derive.1175 ///     let ptr: MySmartPointer<dyn MyTrait> = ptr;1176 /// }1177 /// ```1178 /// Without the `#[derive(CoercePointee)]` macro, this example would fail with the following error:1179 /// ```text1180 /// error[E0308]: mismatched types1181 ///   --> src/main.rs:11:441182 ///    |1183 /// 11 |     let ptr: MySmartPointer<dyn MyTrait> = ptr;1184 ///    |              ---------------------------   ^^^ expected `MySmartPointer<dyn MyTrait>`, found `MySmartPointer<i32>`1185 ///    |              |1186 ///    |              expected due to this1187 ///    |1188 ///    = note: expected struct `MySmartPointer<dyn MyTrait>`1189 ///               found struct `MySmartPointer<i32>`1190 ///    = 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 well1191 /// ```1192 ///1193 /// ## Dyn compatibility1194 ///1195 /// This macro allows you to dispatch on the user-defined pointer type. That is, traits using the1196 /// type as a receiver are dyn-compatible. For example, this compiles:1197 ///1198 /// ```1199 /// #![feature(arbitrary_self_types, derive_coerce_pointee)]1200 /// use std::marker::CoercePointee;1201 /// use std::ops::Deref;1202 ///1203 /// #[derive(CoercePointee)]1204 /// #[repr(transparent)]1205 /// struct MySmartPointer<T: ?Sized>(Box<T>);1206 ///1207 /// impl<T: ?Sized> Deref for MySmartPointer<T> {1208 ///     type Target = T;1209 ///     fn deref(&self) -> &T {1210 ///         &self.01211 ///     }1212 /// }1213 ///1214 /// // You can always define this trait. (as long as you have #![feature(arbitrary_self_types)])1215 /// trait MyTrait {1216 ///     fn func(self: MySmartPointer<Self>);1217 /// }1218 ///1219 /// // But using `dyn MyTrait` requires #[derive(CoercePointee)].1220 /// fn call_func(value: MySmartPointer<dyn MyTrait>) {1221 ///     value.func();1222 /// }1223 /// ```1224 /// If you remove the `#[derive(CoercePointee)]` annotation from the struct, then the above example1225 /// will fail with this error message:1226 /// ```text1227 /// error[E0038]: the trait `MyTrait` is not dyn compatible1228 ///   --> src/lib.rs:21:361229 ///    |1230 /// 17 |     fn func(self: MySmartPointer<Self>);1231 ///    |                   -------------------- help: consider changing method `func`'s `self` parameter to be `&self`: `&Self`1232 /// ...1233 /// 21 | fn call_func(value: MySmartPointer<dyn MyTrait>) {1234 ///    |                                    ^^^^^^^^^^^ `MyTrait` is not dyn compatible1235 ///    |1236 /// note: for a trait to be dyn compatible it needs to allow building a vtable1237 ///       for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>1238 ///   --> src/lib.rs:17:191239 ///    |1240 /// 16 | trait MyTrait {1241 ///    |       ------- this trait is not dyn compatible...1242 /// 17 |     fn func(self: MySmartPointer<Self>);1243 ///    |                   ^^^^^^^^^^^^^^^^^^^^ ...because method `func`'s `self` parameter cannot be dispatched on1244 /// ```1245 ///1246 /// # Requirements for using the macro1247 ///1248 /// This macro can only be used if:1249 /// * The type is a `#[repr(transparent)]` struct.1250 /// * The type of its non-zero-sized field must either be a standard library pointer type1251 ///   (reference, raw pointer, `NonNull`, `Box`, `Rc`, `Arc`, etc.) or another user-defined type1252 ///   also using the `#[derive(CoercePointee)]` macro.1253 /// * Zero-sized fields must not mention any generic parameters unless the zero-sized field has1254 ///   type [`PhantomData`].1255 ///1256 /// ## Multiple type parameters1257 ///1258 /// If the type has multiple type parameters, then you must explicitly specify which one should be1259 /// used for dynamic dispatch. For example:1260 /// ```1261 /// # #![feature(derive_coerce_pointee)]1262 /// # use std::marker::{CoercePointee, PhantomData};1263 /// #[derive(CoercePointee)]1264 /// #[repr(transparent)]1265 /// struct MySmartPointer<#[pointee] T: ?Sized, U> {1266 ///     ptr: Box<T>,1267 ///     _phantom: PhantomData<U>,1268 /// }1269 /// ```1270 /// Specifying `#[pointee]` when the struct has only one type parameter is allowed, but not required.1271 ///1272 /// # Examples1273 ///1274 /// A custom implementation of the `Rc` type:1275 /// ```1276 /// #![feature(derive_coerce_pointee)]1277 /// use std::marker::CoercePointee;1278 /// use std::ops::Deref;1279 /// use std::ptr::NonNull;1280 ///1281 /// #[derive(CoercePointee)]1282 /// #[repr(transparent)]1283 /// pub struct Rc<T: ?Sized> {1284 ///     inner: NonNull<RcInner<T>>,1285 /// }1286 ///1287 /// struct RcInner<T: ?Sized> {1288 ///     refcount: usize,1289 ///     value: T,1290 /// }1291 ///1292 /// impl<T: ?Sized> Deref for Rc<T> {1293 ///     type Target = T;1294 ///     fn deref(&self) -> &T {1295 ///         let ptr = self.inner.as_ptr();1296 ///         unsafe { &(*ptr).value }1297 ///     }1298 /// }1299 ///1300 /// impl<T> Rc<T> {1301 ///     pub fn new(value: T) -> Self {1302 ///         let inner = Box::new(RcInner {1303 ///             refcount: 1,1304 ///             value,1305 ///         });1306 ///         Self {1307 ///             inner: NonNull::from(Box::leak(inner)),1308 ///         }1309 ///     }1310 /// }1311 ///1312 /// impl<T: ?Sized> Clone for Rc<T> {1313 ///     fn clone(&self) -> Self {1314 ///         // A real implementation would handle overflow here.1315 ///         unsafe { (*self.inner.as_ptr()).refcount += 1 };1316 ///         Self { inner: self.inner }1317 ///     }1318 /// }1319 ///1320 /// impl<T: ?Sized> Drop for Rc<T> {1321 ///     fn drop(&mut self) {1322 ///         let ptr = self.inner.as_ptr();1323 ///         unsafe { (*ptr).refcount -= 1 };1324 ///         if unsafe { (*ptr).refcount } == 0 {1325 ///             drop(unsafe { Box::from_raw(ptr) });1326 ///         }1327 ///     }1328 /// }1329 /// ```1330 #[rustc_builtin_macro(CoercePointee, attributes(pointee))]1331 #[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize, coerce_pointee_validated)]1332 #[rustc_diagnostic_item = "CoercePointee"]1333 #[unstable(feature = "derive_coerce_pointee", issue = "123430")]1334 pub macro CoercePointee($item:item) {1335     /* compiler built-in */1336 }1337 1338 /// A trait that is implemented for ADTs with `derive(CoercePointee)` so that1339 /// the compiler can enforce the derive impls are valid post-expansion, since1340 /// the derive has stricter requirements than if the impls were written by hand.1341 ///1342 /// This trait is not intended to be implemented by users or used other than1343 /// validation, so it should never be stabilized.1344 #[lang = "coerce_pointee_validated"]1345 #[unstable(feature = "coerce_pointee_validated", issue = "none")]1346 #[doc(hidden)]1347 pub trait CoercePointeeValidated {1348     /* compiler built-in */1349 }1350 1351 /// Allows value to be reborrowed as exclusive, creating a copy of the value1352 /// that disables the source for reads and writes for the lifetime of the copy.1353 #[lang = "reborrow"]1354 #[unstable(feature = "reborrow", issue = "145612")]1355 pub trait Reborrow {1356     /* compiler built-in */1357 }1358 1359 /// Allows reborrowable value to be reborrowed as shared, creating a copy1360 /// that disables the source for writes for the lifetime of the copy.1361 #[lang = "coerce_shared"]1362 #[unstable(feature = "reborrow", issue = "145612")]1363 pub trait CoerceShared<Target: Copy>: Reborrow {1364     /* compiler built-in */1365 }
Reference details
commit14210df0e27ccd7d9e6a05b8085cbd438e4bbc65
sha2560aed53724eade60e5fa60f598faee5245b599903f79d8eb3c0590bf9a94d2f44
urlhttps://raw.githubusercontent.com/rust-lang/rust/14210df0e27ccd7d9e6a05b8085cbd438e4bbc65/library/core/src/marker.rs