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