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