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