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