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