]> git.lizzy.rs Git - rust.git/blob - library/core/src/marker.rs
Added docs to internal_macro const
[rust.git] / library / core / src / marker.rs
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 use crate::cell::UnsafeCell;
10 use crate::cmp;
11 use crate::fmt::Debug;
12 use crate::hash::Hash;
13 use crate::hash::Hasher;
14
15 /// Types that can be transferred across thread boundaries.
16 ///
17 /// This trait is automatically implemented when the compiler determines it's
18 /// appropriate.
19 ///
20 /// An example of a non-`Send` type is the reference-counting pointer
21 /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same
22 /// reference-counted value, they might try to update the reference count at the
23 /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic
24 /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring
25 /// some overhead) and thus is `Send`.
26 ///
27 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more details.
28 ///
29 /// [`Rc`]: ../../std/rc/struct.Rc.html
30 /// [arc]: ../../std/sync/struct.Arc.html
31 /// [ub]: ../../reference/behavior-considered-undefined.html
32 #[stable(feature = "rust1", since = "1.0.0")]
33 #[cfg_attr(all(not(test), bootstrap), rustc_diagnostic_item = "send_trait")]
34 #[cfg_attr(all(not(test), not(bootstrap)), rustc_diagnostic_item = "Send")]
35 #[rustc_on_unimplemented(
36     message = "`{Self}` cannot be sent between threads safely",
37     label = "`{Self}` cannot be sent between threads safely"
38 )]
39 pub unsafe auto trait Send {
40     // empty.
41 }
42
43 #[stable(feature = "rust1", since = "1.0.0")]
44 impl<T: ?Sized> !Send for *const T {}
45 #[stable(feature = "rust1", since = "1.0.0")]
46 impl<T: ?Sized> !Send for *mut T {}
47
48 /// Types with a constant size known at compile time.
49 ///
50 /// All type parameters have an implicit bound of `Sized`. The special syntax
51 /// `?Sized` can be used to remove this bound if it's not appropriate.
52 ///
53 /// ```
54 /// # #![allow(dead_code)]
55 /// struct Foo<T>(T);
56 /// struct Bar<T: ?Sized>(T);
57 ///
58 /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
59 /// struct BarUse(Bar<[i32]>); // OK
60 /// ```
61 ///
62 /// The one exception is the implicit `Self` type of a trait. A trait does not
63 /// have an implicit `Sized` bound as this is incompatible with [trait object]s
64 /// where, by definition, the trait needs to work with all possible implementors,
65 /// and thus could be any size.
66 ///
67 /// Although Rust will let you bind `Sized` to a trait, you won't
68 /// be able to use it to form a trait object later:
69 ///
70 /// ```
71 /// # #![allow(unused_variables)]
72 /// trait Foo { }
73 /// trait Bar: Sized { }
74 ///
75 /// struct Impl;
76 /// impl Foo for Impl { }
77 /// impl Bar for Impl { }
78 ///
79 /// let x: &dyn Foo = &Impl;    // OK
80 /// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot
81 ///                             // be made into an object
82 /// ```
83 ///
84 /// [trait object]: ../../book/ch17-02-trait-objects.html
85 #[stable(feature = "rust1", since = "1.0.0")]
86 #[lang = "sized"]
87 #[rustc_on_unimplemented(
88     message = "the size for values of type `{Self}` cannot be known at compilation time",
89     label = "doesn't have a size known at compile-time"
90 )]
91 #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
92 #[rustc_specialization_trait]
93 pub trait Sized {
94     // Empty.
95 }
96
97 /// Types that can be "unsized" to a dynamically-sized type.
98 ///
99 /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and
100 /// `Unsize<dyn fmt::Debug>`.
101 ///
102 /// All implementations of `Unsize` are provided automatically by the compiler.
103 /// Those implementations are:
104 ///
105 /// - Arrays `[T; N]` implement `Unsize<[T]>`.
106 /// - Types implementing a trait `Trait` also implement `Unsize<dyn Trait>`.
107 /// - Structs `Foo<..., T, ...>` implement `Unsize<Foo<..., U, ...>>` if all of these conditions
108 ///   are met:
109 ///   - `T: Unsize<U>`.
110 ///   - Only the last field of `Foo` has a type involving `T`.
111 ///   - `Bar<T>: Unsize<Bar<U>>`, where `Bar<T>` stands for the actual type of that last field.
112 ///
113 /// `Unsize` is used along with [`ops::CoerceUnsized`] to allow
114 /// "user-defined" containers such as [`Rc`] to contain dynamically-sized
115 /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]
116 /// for more details.
117 ///
118 /// [`ops::CoerceUnsized`]: crate::ops::CoerceUnsized
119 /// [`Rc`]: ../../std/rc/struct.Rc.html
120 /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
121 /// [nomicon-coerce]: ../../nomicon/coercions.html
122 #[unstable(feature = "unsize", issue = "27732")]
123 #[lang = "unsize"]
124 pub trait Unsize<T: ?Sized> {
125     // Empty.
126 }
127
128 /// Required trait for constants used in pattern matches.
129 ///
130 /// Any type that derives `PartialEq` automatically implements this trait,
131 /// *regardless* of whether its type-parameters implement `Eq`.
132 ///
133 /// If a `const` item contains some type that does not implement this trait,
134 /// then that type either (1.) does not implement `PartialEq` (which means the
135 /// constant will not provide that comparison method, which code generation
136 /// assumes is available), or (2.) it implements *its own* version of
137 /// `PartialEq` (which we assume does not conform to a structural-equality
138 /// comparison).
139 ///
140 /// In either of the two scenarios above, we reject usage of such a constant in
141 /// a pattern match.
142 ///
143 /// See also the [structural match RFC][RFC1445], and [issue 63438] which
144 /// motivated migrating from attribute-based design to this trait.
145 ///
146 /// [RFC1445]: https://github.com/rust-lang/rfcs/blob/master/text/1445-restrict-constants-in-patterns.md
147 /// [issue 63438]: https://github.com/rust-lang/rust/issues/63438
148 #[unstable(feature = "structural_match", issue = "31434")]
149 #[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")]
150 #[lang = "structural_peq"]
151 pub trait StructuralPartialEq {
152     // Empty.
153 }
154
155 /// Required trait for constants used in pattern matches.
156 ///
157 /// Any type that derives `Eq` automatically implements this trait, *regardless*
158 /// of whether its type parameters implement `Eq`.
159 ///
160 /// This is a hack to work around a limitation in our type system.
161 ///
162 /// # Background
163 ///
164 /// We want to require that types of consts used in pattern matches
165 /// have the attribute `#[derive(PartialEq, Eq)]`.
166 ///
167 /// In a more ideal world, we could check that requirement by just checking that
168 /// the given type implements both the `StructuralPartialEq` trait *and*
169 /// the `Eq` trait. However, you can have ADTs that *do* `derive(PartialEq, Eq)`,
170 /// and be a case that we want the compiler to accept, and yet the constant's
171 /// type fails to implement `Eq`.
172 ///
173 /// Namely, a case like this:
174 ///
175 /// ```rust
176 /// #[derive(PartialEq, Eq)]
177 /// struct Wrap<X>(X);
178 ///
179 /// fn higher_order(_: &()) { }
180 ///
181 /// const CFN: Wrap<fn(&())> = Wrap(higher_order);
182 ///
183 /// fn main() {
184 ///     match CFN {
185 ///         CFN => {}
186 ///         _ => {}
187 ///     }
188 /// }
189 /// ```
190 ///
191 /// (The problem in the above code is that `Wrap<fn(&())>` does not implement
192 /// `PartialEq`, nor `Eq`, because `for<'a> fn(&'a _)` does not implement those
193 /// traits.)
194 ///
195 /// Therefore, we cannot rely on naive check for `StructuralPartialEq` and
196 /// mere `Eq`.
197 ///
198 /// As a hack to work around this, we use two separate traits injected by each
199 /// of the two derives (`#[derive(PartialEq)]` and `#[derive(Eq)]`) and check
200 /// that both of them are present as part of structural-match checking.
201 #[unstable(feature = "structural_match", issue = "31434")]
202 #[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(Eq)]`")]
203 #[lang = "structural_teq"]
204 pub trait StructuralEq {
205     // Empty.
206 }
207
208 /// Types whose values can be duplicated simply by copying bits.
209 ///
210 /// By default, variable bindings have 'move semantics.' In other
211 /// words:
212 ///
213 /// ```
214 /// #[derive(Debug)]
215 /// struct Foo;
216 ///
217 /// let x = Foo;
218 ///
219 /// let y = x;
220 ///
221 /// // `x` has moved into `y`, and so cannot be used
222 ///
223 /// // println!("{:?}", x); // error: use of moved value
224 /// ```
225 ///
226 /// However, if a type implements `Copy`, it instead has 'copy semantics':
227 ///
228 /// ```
229 /// // We can derive a `Copy` implementation. `Clone` is also required, as it's
230 /// // a supertrait of `Copy`.
231 /// #[derive(Debug, Copy, Clone)]
232 /// struct Foo;
233 ///
234 /// let x = Foo;
235 ///
236 /// let y = x;
237 ///
238 /// // `y` is a copy of `x`
239 ///
240 /// println!("{:?}", x); // A-OK!
241 /// ```
242 ///
243 /// It's important to note that in these two examples, the only difference is whether you
244 /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move
245 /// can result in bits being copied in memory, although this is sometimes optimized away.
246 ///
247 /// ## How can I implement `Copy`?
248 ///
249 /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:
250 ///
251 /// ```
252 /// #[derive(Copy, Clone)]
253 /// struct MyStruct;
254 /// ```
255 ///
256 /// You can also implement `Copy` and `Clone` manually:
257 ///
258 /// ```
259 /// struct MyStruct;
260 ///
261 /// impl Copy for MyStruct { }
262 ///
263 /// impl Clone for MyStruct {
264 ///     fn clone(&self) -> MyStruct {
265 ///         *self
266 ///     }
267 /// }
268 /// ```
269 ///
270 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
271 /// bound on type parameters, which isn't always desired.
272 ///
273 /// ## What's the difference between `Copy` and `Clone`?
274 ///
275 /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of
276 /// `Copy` is not overloadable; it is always a simple bit-wise copy.
277 ///
278 /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can
279 /// provide any type-specific behavior necessary to duplicate values safely. For example,
280 /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string
281 /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the
282 /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]
283 /// but not `Copy`.
284 ///
285 /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement
286 /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`
287 /// (see the example above).
288 ///
289 /// ## When can my type be `Copy`?
290 ///
291 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
292 /// struct can be `Copy`:
293 ///
294 /// ```
295 /// # #[allow(dead_code)]
296 /// #[derive(Copy, Clone)]
297 /// struct Point {
298 ///    x: i32,
299 ///    y: i32,
300 /// }
301 /// ```
302 ///
303 /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.
304 /// By contrast, consider
305 ///
306 /// ```
307 /// # #![allow(dead_code)]
308 /// # struct Point;
309 /// struct PointList {
310 ///     points: Vec<Point>,
311 /// }
312 /// ```
313 ///
314 /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we
315 /// attempt to derive a `Copy` implementation, we'll get an error:
316 ///
317 /// ```text
318 /// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
319 /// ```
320 ///
321 /// Shared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds
322 /// shared references of types `T` that are *not* `Copy`. Consider the following struct,
323 /// which can implement `Copy`, because it only holds a *shared reference* to our non-`Copy`
324 /// type `PointList` from above:
325 ///
326 /// ```
327 /// # #![allow(dead_code)]
328 /// # struct PointList;
329 /// #[derive(Copy, Clone)]
330 /// struct PointListWrapper<'a> {
331 ///     point_list_ref: &'a PointList,
332 /// }
333 /// ```
334 ///
335 /// ## When *can't* my type be `Copy`?
336 ///
337 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
338 /// mutable reference. Copying [`String`] would duplicate responsibility for managing the
339 /// [`String`]'s buffer, leading to a double free.
340 ///
341 /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's
342 /// managing some resource besides its own [`size_of::<T>`] bytes.
343 ///
344 /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get
345 /// the error [E0204].
346 ///
347 /// [E0204]: ../../error-index.html#E0204
348 ///
349 /// ## When *should* my type be `Copy`?
350 ///
351 /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,
352 /// that implementing `Copy` is part of the public API of your type. If the type might become
353 /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to
354 /// avoid a breaking API change.
355 ///
356 /// ## Additional implementors
357 ///
358 /// In addition to the [implementors listed below][impls],
359 /// the following types also implement `Copy`:
360 ///
361 /// * Function item types (i.e., the distinct types defined for each function)
362 /// * Function pointer types (e.g., `fn() -> i32`)
363 /// * Array types, for all sizes, if the item type also implements `Copy` (e.g., `[i32; 123456]`)
364 /// * Tuple types, if each component also implements `Copy` (e.g., `()`, `(i32, bool)`)
365 /// * Closure types, if they capture no value from the environment
366 ///   or if all such captured values implement `Copy` themselves.
367 ///   Note that variables captured by shared reference always implement `Copy`
368 ///   (even if the referent doesn't),
369 ///   while variables captured by mutable reference never implement `Copy`.
370 ///
371 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
372 /// [`String`]: ../../std/string/struct.String.html
373 /// [`size_of::<T>`]: crate::mem::size_of
374 /// [impls]: #implementors
375 #[stable(feature = "rust1", since = "1.0.0")]
376 #[lang = "copy"]
377 // FIXME(matthewjasper) This allows copying a type that doesn't implement
378 // `Copy` because of unsatisfied lifetime bounds (copying `A<'_>` when only
379 // `A<'static>: Copy` and `A<'_>: Clone`).
380 // We have this attribute here for now only because there are quite a few
381 // existing specializations on `Copy` that already exist in the standard
382 // library, and there's no way to safely have this behavior right now.
383 #[rustc_unsafe_specialization_marker]
384 #[rustc_diagnostic_item = "Copy"]
385 pub trait Copy: Clone {
386     // Empty.
387 }
388
389 /// Derive macro generating an impl of the trait `Copy`.
390 #[rustc_builtin_macro]
391 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
392 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
393 pub macro Copy($item:item) {
394     /* compiler built-in */
395 }
396
397 /// Types for which it is safe to share references between threads.
398 ///
399 /// This trait is automatically implemented when the compiler determines
400 /// it's appropriate.
401 ///
402 /// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is
403 /// [`Send`]. In other words, if there is no possibility of
404 /// [undefined behavior][ub] (including data races) when passing
405 /// `&T` references between threads.
406 ///
407 /// As one would expect, primitive types like [`u8`] and [`f64`]
408 /// are all [`Sync`], and so are simple aggregate types containing them,
409 /// like tuples, structs and enums. More examples of basic [`Sync`]
410 /// types include "immutable" types like `&T`, and those with simple
411 /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
412 /// most other collection types. (Generic parameters need to be [`Sync`]
413 /// for their container to be [`Sync`].)
414 ///
415 /// A somewhat surprising consequence of the definition is that `&mut T`
416 /// is `Sync` (if `T` is `Sync`) even though it seems like that might
417 /// provide unsynchronized mutation. The trick is that a mutable
418 /// reference behind a shared reference (that is, `& &mut T`)
419 /// becomes read-only, as if it were a `& &T`. Hence there is no risk
420 /// of a data race.
421 ///
422 /// Types that are not `Sync` are those that have "interior
423 /// mutability" in a non-thread-safe form, such as [`Cell`][cell]
424 /// and [`RefCell`][refcell]. These types allow for mutation of
425 /// their contents even through an immutable, shared reference. For
426 /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
427 /// only a shared reference [`&Cell<T>`][cell]. The method performs no
428 /// synchronization, thus [`Cell`][cell] cannot be `Sync`.
429 ///
430 /// Another example of a non-`Sync` type is the reference-counting
431 /// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
432 /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
433 ///
434 /// For cases when one does need thread-safe interior mutability,
435 /// Rust provides [atomic data types], as well as explicit locking via
436 /// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types
437 /// ensure that any mutation cannot cause data races, hence the types
438 /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
439 /// analogue of [`Rc`][rc].
440 ///
441 /// Any types with interior mutability must also use the
442 /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
443 /// can be mutated through a shared reference. Failing to doing this is
444 /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
445 /// from `&T` to `&mut T` is invalid.
446 ///
447 /// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.
448 ///
449 /// [box]: ../../std/boxed/struct.Box.html
450 /// [vec]: ../../std/vec/struct.Vec.html
451 /// [cell]: crate::cell::Cell
452 /// [refcell]: crate::cell::RefCell
453 /// [rc]: ../../std/rc/struct.Rc.html
454 /// [arc]: ../../std/sync/struct.Arc.html
455 /// [atomic data types]: crate::sync::atomic
456 /// [mutex]: ../../std/sync/struct.Mutex.html
457 /// [rwlock]: ../../std/sync/struct.RwLock.html
458 /// [unsafecell]: crate::cell::UnsafeCell
459 /// [ub]: ../../reference/behavior-considered-undefined.html
460 /// [transmute]: crate::mem::transmute
461 /// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html
462 #[stable(feature = "rust1", since = "1.0.0")]
463 #[cfg_attr(not(test), rustc_diagnostic_item = "Sync")]
464 #[lang = "sync"]
465 #[rustc_on_unimplemented(
466     message = "`{Self}` cannot be shared between threads safely",
467     label = "`{Self}` cannot be shared between threads safely"
468 )]
469 pub unsafe auto trait Sync {
470     // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`
471     // lands in beta, and it has been extended to check whether a closure is
472     // anywhere in the requirement chain, extend it as such (#48534):
473     // ```
474     // on(
475     //     closure,
476     //     note="`{Self}` cannot be shared safely, consider marking the closure `move`"
477     // ),
478     // ```
479
480     // Empty
481 }
482
483 #[stable(feature = "rust1", since = "1.0.0")]
484 impl<T: ?Sized> !Sync for *const T {}
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T: ?Sized> !Sync for *mut T {}
487
488 macro_rules! impls {
489     ($t: ident) => {
490         #[stable(feature = "rust1", since = "1.0.0")]
491         impl<T: ?Sized> Hash for $t<T> {
492             #[inline]
493             fn hash<H: Hasher>(&self, _: &mut H) {}
494         }
495
496         #[stable(feature = "rust1", since = "1.0.0")]
497         impl<T: ?Sized> cmp::PartialEq for $t<T> {
498             fn eq(&self, _other: &$t<T>) -> bool {
499                 true
500             }
501         }
502
503         #[stable(feature = "rust1", since = "1.0.0")]
504         impl<T: ?Sized> cmp::Eq for $t<T> {}
505
506         #[stable(feature = "rust1", since = "1.0.0")]
507         impl<T: ?Sized> cmp::PartialOrd for $t<T> {
508             fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
509                 Option::Some(cmp::Ordering::Equal)
510             }
511         }
512
513         #[stable(feature = "rust1", since = "1.0.0")]
514         impl<T: ?Sized> cmp::Ord for $t<T> {
515             fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
516                 cmp::Ordering::Equal
517             }
518         }
519
520         #[stable(feature = "rust1", since = "1.0.0")]
521         impl<T: ?Sized> Copy for $t<T> {}
522
523         #[stable(feature = "rust1", since = "1.0.0")]
524         impl<T: ?Sized> Clone for $t<T> {
525             fn clone(&self) -> Self {
526                 Self
527             }
528         }
529
530         #[stable(feature = "rust1", since = "1.0.0")]
531         #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
532         impl<T: ?Sized> const Default for $t<T> {
533             fn default() -> Self {
534                 Self
535             }
536         }
537
538         #[unstable(feature = "structural_match", issue = "31434")]
539         impl<T: ?Sized> StructuralPartialEq for $t<T> {}
540
541         #[unstable(feature = "structural_match", issue = "31434")]
542         impl<T: ?Sized> StructuralEq for $t<T> {}
543     };
544 }
545
546 /// Zero-sized type used to mark things that "act like" they own a `T`.
547 ///
548 /// Adding a `PhantomData<T>` field to your type tells the compiler that your
549 /// type acts as though it stores a value of type `T`, even though it doesn't
550 /// really. This information is used when computing certain safety properties.
551 ///
552 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see
553 /// [the Nomicon](../../nomicon/phantom-data.html).
554 ///
555 /// # A ghastly note ðŸ‘»ðŸ‘»ðŸ‘»
556 ///
557 /// Though they both have scary names, `PhantomData` and 'phantom types' are
558 /// related, but not identical. A phantom type parameter is simply a type
559 /// parameter which is never used. In Rust, this often causes the compiler to
560 /// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
561 ///
562 /// # Examples
563 ///
564 /// ## Unused lifetime parameters
565 ///
566 /// Perhaps the most common use case for `PhantomData` is a struct that has an
567 /// unused lifetime parameter, typically as part of some unsafe code. For
568 /// example, here is a struct `Slice` that has two pointers of type `*const T`,
569 /// presumably pointing into an array somewhere:
570 ///
571 /// ```compile_fail,E0392
572 /// struct Slice<'a, T> {
573 ///     start: *const T,
574 ///     end: *const T,
575 /// }
576 /// ```
577 ///
578 /// The intention is that the underlying data is only valid for the
579 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
580 /// intent is not expressed in the code, since there are no uses of
581 /// the lifetime `'a` and hence it is not clear what data it applies
582 /// to. We can correct this by telling the compiler to act *as if* the
583 /// `Slice` struct contained a reference `&'a T`:
584 ///
585 /// ```
586 /// use std::marker::PhantomData;
587 ///
588 /// # #[allow(dead_code)]
589 /// struct Slice<'a, T: 'a> {
590 ///     start: *const T,
591 ///     end: *const T,
592 ///     phantom: PhantomData<&'a T>,
593 /// }
594 /// ```
595 ///
596 /// This also in turn requires the annotation `T: 'a`, indicating
597 /// that any references in `T` are valid over the lifetime `'a`.
598 ///
599 /// When initializing a `Slice` you simply provide the value
600 /// `PhantomData` for the field `phantom`:
601 ///
602 /// ```
603 /// # #![allow(dead_code)]
604 /// # use std::marker::PhantomData;
605 /// # struct Slice<'a, T: 'a> {
606 /// #     start: *const T,
607 /// #     end: *const T,
608 /// #     phantom: PhantomData<&'a T>,
609 /// # }
610 /// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
611 ///     let ptr = vec.as_ptr();
612 ///     Slice {
613 ///         start: ptr,
614 ///         end: unsafe { ptr.add(vec.len()) },
615 ///         phantom: PhantomData,
616 ///     }
617 /// }
618 /// ```
619 ///
620 /// ## Unused type parameters
621 ///
622 /// It sometimes happens that you have unused type parameters which
623 /// indicate what type of data a struct is "tied" to, even though that
624 /// data is not actually found in the struct itself. Here is an
625 /// example where this arises with [FFI]. The foreign interface uses
626 /// handles of type `*mut ()` to refer to Rust values of different
627 /// types. We track the Rust type using a phantom type parameter on
628 /// the struct `ExternalResource` which wraps a handle.
629 ///
630 /// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
631 ///
632 /// ```
633 /// # #![allow(dead_code)]
634 /// # trait ResType { }
635 /// # struct ParamType;
636 /// # mod foreign_lib {
637 /// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }
638 /// #     pub fn do_stuff(_: *mut (), _: usize) {}
639 /// # }
640 /// # fn convert_params(_: ParamType) -> usize { 42 }
641 /// use std::marker::PhantomData;
642 /// use std::mem;
643 ///
644 /// struct ExternalResource<R> {
645 ///    resource_handle: *mut (),
646 ///    resource_type: PhantomData<R>,
647 /// }
648 ///
649 /// impl<R: ResType> ExternalResource<R> {
650 ///     fn new() -> Self {
651 ///         let size_of_res = mem::size_of::<R>();
652 ///         Self {
653 ///             resource_handle: foreign_lib::new(size_of_res),
654 ///             resource_type: PhantomData,
655 ///         }
656 ///     }
657 ///
658 ///     fn do_stuff(&self, param: ParamType) {
659 ///         let foreign_params = convert_params(param);
660 ///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
661 ///     }
662 /// }
663 /// ```
664 ///
665 /// ## Ownership and the drop check
666 ///
667 /// Adding a field of type `PhantomData<T>` indicates that your
668 /// type owns data of type `T`. This in turn implies that when your
669 /// type is dropped, it may drop one or more instances of the type
670 /// `T`. This has bearing on the Rust compiler's [drop check]
671 /// analysis.
672 ///
673 /// If your struct does not in fact *own* the data of type `T`, it is
674 /// better to use a reference type, like `PhantomData<&'a T>`
675 /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
676 /// as not to indicate ownership.
677 ///
678 /// [drop check]: ../../nomicon/dropck.html
679 #[lang = "phantom_data"]
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub struct PhantomData<T: ?Sized>;
682
683 impls! { PhantomData }
684
685 mod impls {
686     #[stable(feature = "rust1", since = "1.0.0")]
687     unsafe impl<T: Sync + ?Sized> Send for &T {}
688     #[stable(feature = "rust1", since = "1.0.0")]
689     unsafe impl<T: Send + ?Sized> Send for &mut T {}
690 }
691
692 /// Compiler-internal trait used to indicate the type of enum discriminants.
693 ///
694 /// This trait is automatically implemented for every type and does not add any
695 /// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute
696 /// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.
697 ///
698 /// [`mem::Discriminant`]: crate::mem::Discriminant
699 #[unstable(
700     feature = "discriminant_kind",
701     issue = "none",
702     reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
703 )]
704 #[lang = "discriminant_kind"]
705 pub trait DiscriminantKind {
706     /// The type of the discriminant, which must satisfy the trait
707     /// bounds required by `mem::Discriminant`.
708     #[lang = "discriminant_type"]
709     type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;
710 }
711
712 /// Compiler-internal trait used to determine whether a type contains
713 /// any `UnsafeCell` internally, but not through an indirection.
714 /// This affects, for example, whether a `static` of that type is
715 /// placed in read-only static memory or writable static memory.
716 #[lang = "freeze"]
717 pub(crate) unsafe auto trait Freeze {}
718
719 impl<T: ?Sized> !Freeze for UnsafeCell<T> {}
720 unsafe impl<T: ?Sized> Freeze for PhantomData<T> {}
721 unsafe impl<T: ?Sized> Freeze for *const T {}
722 unsafe impl<T: ?Sized> Freeze for *mut T {}
723 unsafe impl<T: ?Sized> Freeze for &T {}
724 unsafe impl<T: ?Sized> Freeze for &mut T {}
725
726 /// Types that can be safely moved after being pinned.
727 ///
728 /// Rust itself has no notion of immovable types, and considers moves (e.g.,
729 /// through assignment or [`mem::replace`]) to always be safe.
730 ///
731 /// The [`Pin`][Pin] type is used instead to prevent moves through the type
732 /// system. Pointers `P<T>` wrapped in the [`Pin<P<T>>`][Pin] wrapper can't be
733 /// moved out of. See the [`pin` module] documentation for more information on
734 /// pinning.
735 ///
736 /// Implementing the `Unpin` trait for `T` lifts the restrictions of pinning off
737 /// the type, which then allows moving `T` out of [`Pin<P<T>>`][Pin] with
738 /// functions such as [`mem::replace`].
739 ///
740 /// `Unpin` has no consequence at all for non-pinned data. In particular,
741 /// [`mem::replace`] happily moves `!Unpin` data (it works for any `&mut T`, not
742 /// just when `T: Unpin`). However, you cannot use [`mem::replace`] on data
743 /// wrapped inside a [`Pin<P<T>>`][Pin] because you cannot get the `&mut T` you
744 /// need for that, and *that* is what makes this system work.
745 ///
746 /// So this, for example, can only be done on types implementing `Unpin`:
747 ///
748 /// ```rust
749 /// # #![allow(unused_must_use)]
750 /// use std::mem;
751 /// use std::pin::Pin;
752 ///
753 /// let mut string = "this".to_string();
754 /// let mut pinned_string = Pin::new(&mut string);
755 ///
756 /// // We need a mutable reference to call `mem::replace`.
757 /// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
758 /// // but that is only possible because `String` implements `Unpin`.
759 /// mem::replace(&mut *pinned_string, "other".to_string());
760 /// ```
761 ///
762 /// This trait is automatically implemented for almost every type.
763 ///
764 /// [`mem::replace`]: crate::mem::replace
765 /// [Pin]: crate::pin::Pin
766 /// [`pin` module]: crate::pin
767 #[stable(feature = "pin", since = "1.33.0")]
768 #[rustc_on_unimplemented(
769     note = "consider using `Box::pin`",
770     message = "`{Self}` cannot be unpinned"
771 )]
772 #[lang = "unpin"]
773 pub auto trait Unpin {}
774
775 /// A marker type which does not implement `Unpin`.
776 ///
777 /// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.
778 #[stable(feature = "pin", since = "1.33.0")]
779 #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
780 pub struct PhantomPinned;
781
782 #[stable(feature = "pin", since = "1.33.0")]
783 impl !Unpin for PhantomPinned {}
784
785 #[stable(feature = "pin", since = "1.33.0")]
786 impl<'a, T: ?Sized + 'a> Unpin for &'a T {}
787
788 #[stable(feature = "pin", since = "1.33.0")]
789 impl<'a, T: ?Sized + 'a> Unpin for &'a mut T {}
790
791 #[stable(feature = "pin_raw", since = "1.38.0")]
792 impl<T: ?Sized> Unpin for *const T {}
793
794 #[stable(feature = "pin_raw", since = "1.38.0")]
795 impl<T: ?Sized> Unpin for *mut T {}
796
797 /// Implementations of `Copy` for primitive types.
798 ///
799 /// Implementations that cannot be described in Rust
800 /// are implemented in `traits::SelectionContext::copy_clone_conditions()`
801 /// in `rustc_trait_selection`.
802 mod copy_impls {
803
804     use super::Copy;
805
806     macro_rules! impl_copy {
807         ($($t:ty)*) => {
808             $(
809                 #[stable(feature = "rust1", since = "1.0.0")]
810                 impl Copy for $t {}
811             )*
812         }
813     }
814
815     impl_copy! {
816         usize u8 u16 u32 u64 u128
817         isize i8 i16 i32 i64 i128
818         f32 f64
819         bool char
820     }
821
822     #[unstable(feature = "never_type", issue = "35121")]
823     impl Copy for ! {}
824
825     #[stable(feature = "rust1", since = "1.0.0")]
826     impl<T: ?Sized> Copy for *const T {}
827
828     #[stable(feature = "rust1", since = "1.0.0")]
829     impl<T: ?Sized> Copy for *mut T {}
830
831     /// Shared references can be copied, but mutable references *cannot*!
832     #[stable(feature = "rust1", since = "1.0.0")]
833     impl<T: ?Sized> Copy for &T {}
834 }