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