]> git.lizzy.rs Git - rust.git/blob - src/libcore/marker.rs
Auto merge of #41437 - cuviper:remove-unstable-deprecated, r=alexcrichton
[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 #[lang = "send"]
43 #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
44 pub unsafe trait Send {
45     // empty.
46 }
47
48 #[stable(feature = "rust1", since = "1.0.0")]
49 unsafe impl Send for .. { }
50
51 #[stable(feature = "rust1", since = "1.0.0")]
52 impl<T: ?Sized> !Send for *const T { }
53 #[stable(feature = "rust1", since = "1.0.0")]
54 impl<T: ?Sized> !Send for *mut T { }
55
56 /// Types with a constant size known at compile time.
57 ///
58 /// All type parameters have an implicit bound of `Sized`. The special syntax
59 /// `?Sized` can be used to remove this bound if it's not appropriate.
60 ///
61 /// ```
62 /// # #![allow(dead_code)]
63 /// struct Foo<T>(T);
64 /// struct Bar<T: ?Sized>(T);
65 ///
66 /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
67 /// struct BarUse(Bar<[i32]>); // OK
68 /// ```
69 ///
70 /// The one exception is the implicit `Self` type of a trait, which does not
71 /// get an implicit `Sized` bound. This is because a `Sized` bound prevents
72 /// the trait from being used to form a [trait object]:
73 ///
74 /// ```
75 /// # #![allow(unused_variables)]
76 /// trait Foo { }
77 /// trait Bar: Sized { }
78 ///
79 /// struct Impl;
80 /// impl Foo for Impl { }
81 /// impl Bar for Impl { }
82 ///
83 /// let x: &Foo = &Impl;    // OK
84 /// // let y: &Bar = &Impl; // error: the trait `Bar` cannot
85 ///                         // be made into an object
86 /// ```
87 ///
88 /// [trait object]: ../../book/trait-objects.html
89 #[stable(feature = "rust1", since = "1.0.0")]
90 #[lang = "sized"]
91 #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
92 #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
93 pub trait Sized {
94     // Empty.
95 }
96
97 /// Types that can be "unsized" to a dynamically-sized type.
98 ///
99 /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and
100 /// `Unsize<fmt::Debug>`.
101 ///
102 /// All implementations of `Unsize` are provided automatically by the compiler.
103 ///
104 /// `Unsize` is implemented for:
105 ///
106 /// - `[T; N]` is `Unsize<[T]>`
107 /// - `T` is `Unsize<Trait>` when `T: Trait`
108 /// - `Foo<..., T, ...>` is `Unsize<Foo<..., U, ...>>` if:
109 ///   - `T: Unsize<U>`
110 ///   - Foo is a struct
111 ///   - Only the last field of `Foo` has a type involving `T`
112 ///   - `T` is not part of the type of any other fields
113 ///   - `Bar<T>: Unsize<Bar<U>>`, if the last field of `Foo` has type `Bar<T>`
114 ///
115 /// `Unsize` is used along with [`ops::CoerceUnsized`][coerceunsized] to allow
116 /// "user-defined" containers such as [`rc::Rc`][rc] to contain dynamically-sized
117 /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]
118 /// for more details.
119 ///
120 /// [coerceunsized]: ../ops/trait.CoerceUnsized.html
121 /// [rc]: ../../std/rc/struct.Rc.html
122 /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
123
124 #[unstable(feature = "unsize", issue = "27732")]
125 #[lang="unsize"]
126 pub trait Unsize<T: ?Sized> {
127     // Empty.
128 }
129
130 /// Types whose values can be duplicated simply by copying bits.
131 ///
132 /// By default, variable bindings have 'move semantics.' In other
133 /// words:
134 ///
135 /// ```
136 /// #[derive(Debug)]
137 /// struct Foo;
138 ///
139 /// let x = Foo;
140 ///
141 /// let y = x;
142 ///
143 /// // `x` has moved into `y`, and so cannot be used
144 ///
145 /// // println!("{:?}", x); // error: use of moved value
146 /// ```
147 ///
148 /// However, if a type implements `Copy`, it instead has 'copy semantics':
149 ///
150 /// ```
151 /// // We can derive a `Copy` implementation. `Clone` is also required, as it's
152 /// // a supertrait of `Copy`.
153 /// #[derive(Debug, Copy, Clone)]
154 /// struct Foo;
155 ///
156 /// let x = Foo;
157 ///
158 /// let y = x;
159 ///
160 /// // `y` is a copy of `x`
161 ///
162 /// println!("{:?}", x); // A-OK!
163 /// ```
164 ///
165 /// It's important to note that in these two examples, the only difference is whether you
166 /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move
167 /// can result in bits being copied in memory, although this is sometimes optimized away.
168 ///
169 /// ## How can I implement `Copy`?
170 ///
171 /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:
172 ///
173 /// ```
174 /// #[derive(Copy, Clone)]
175 /// struct MyStruct;
176 /// ```
177 ///
178 /// You can also implement `Copy` and `Clone` manually:
179 ///
180 /// ```
181 /// struct MyStruct;
182 ///
183 /// impl Copy for MyStruct { }
184 ///
185 /// impl Clone for MyStruct {
186 ///     fn clone(&self) -> MyStruct {
187 ///         *self
188 ///     }
189 /// }
190 /// ```
191 ///
192 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
193 /// bound on type parameters, which isn't always desired.
194 ///
195 /// ## What's the difference between `Copy` and `Clone`?
196 ///
197 /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of
198 /// `Copy` is not overloadable; it is always a simple bit-wise copy.
199 ///
200 /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can
201 /// provide any type-specific behavior necessary to duplicate values safely. For example,
202 /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string
203 /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the
204 /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]
205 /// but not `Copy`.
206 ///
207 /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement
208 /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation need only return `*self`
209 /// (see the example above).
210 ///
211 /// ## When can my type be `Copy`?
212 ///
213 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
214 /// struct can be `Copy`:
215 ///
216 /// ```
217 /// # #[allow(dead_code)]
218 /// struct Point {
219 ///    x: i32,
220 ///    y: i32,
221 /// }
222 /// ```
223 ///
224 /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.
225 /// By contrast, consider
226 ///
227 /// ```
228 /// # #![allow(dead_code)]
229 /// # struct Point;
230 /// struct PointList {
231 ///     points: Vec<Point>,
232 /// }
233 /// ```
234 ///
235 /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we
236 /// attempt to derive a `Copy` implementation, we'll get an error:
237 ///
238 /// ```text
239 /// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
240 /// ```
241 ///
242 /// ## When *can't* my type be `Copy`?
243 ///
244 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
245 /// mutable reference. Copying [`String`] would duplicate responsibility for managing the
246 /// [`String`]'s buffer, leading to a double free.
247 ///
248 /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's
249 /// managing some resource besides its own [`size_of::<T>`] bytes.
250 ///
251 /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get
252 /// the error [E0204].
253 ///
254 /// [E0204]: ../../error-index.html#E0204
255 ///
256 /// ## When *should* my type be `Copy`?
257 ///
258 /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,
259 /// that implementing `Copy` is part of the public API of your type. If the type might become
260 /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to
261 /// avoid a breaking API change.
262 ///
263 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
264 /// [`String`]: ../../std/string/struct.String.html
265 /// [`Drop`]: ../../std/ops/trait.Drop.html
266 /// [`size_of::<T>`]: ../../std/mem/fn.size_of.html
267 /// [`Clone`]: ../clone/trait.Clone.html
268 /// [`String`]: ../../std/string/struct.String.html
269 /// [`i32`]: ../../std/primitive.i32.html
270 #[stable(feature = "rust1", since = "1.0.0")]
271 #[lang = "copy"]
272 pub trait Copy : Clone {
273     // Empty.
274 }
275
276 /// Types for which it is safe to share references between threads.
277 ///
278 /// This trait is automatically implemented when the compiler determines
279 /// it's appropriate.
280 ///
281 /// The precise definition is: a type `T` is `Sync` if `&T` is
282 /// [`Send`][send]. In other words, if there is no possibility of
283 /// [undefined behavior][ub] (including data races) when passing
284 /// `&T` references between threads.
285 ///
286 /// As one would expect, primitive types like [`u8`][u8] and [`f64`][f64]
287 /// are all `Sync`, and so are simple aggregate types containing them,
288 /// like tuples, structs and enums. More examples of basic `Sync`
289 /// types include "immutable" types like `&T`, and those with simple
290 /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
291 /// most other collection types. (Generic parameters need to be `Sync`
292 /// for their container to be `Sync`.)
293 ///
294 /// A somewhat surprising consequence of the definition is that `&mut T`
295 /// is `Sync` (if `T` is `Sync`) even though it seems like that might
296 /// provide unsynchronized mutation. The trick is that a mutable
297 /// reference behind a shared reference (that is, `& &mut T`)
298 /// becomes read-only, as if it were a `& &T`. Hence there is no risk
299 /// of a data race.
300 ///
301 /// Types that are not `Sync` are those that have "interior
302 /// mutability" in a non-thread-safe form, such as [`cell::Cell`][cell]
303 /// and [`cell::RefCell`][refcell]. These types allow for mutation of
304 /// their contents even through an immutable, shared reference. For
305 /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
306 /// only a shared reference [`&Cell<T>`][cell]. The method performs no
307 /// synchronization, thus [`Cell`][cell] cannot be `Sync`.
308 ///
309 /// Another example of a non-`Sync` type is the reference-counting
310 /// pointer [`rc::Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
311 /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
312 ///
313 /// For cases when one does need thread-safe interior mutability,
314 /// Rust provides [atomic data types], as well as explicit locking via
315 /// [`sync::Mutex`][mutex] and [`sync::RWLock`][rwlock]. These types
316 /// ensure that any mutation cannot cause data races, hence the types
317 /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
318 /// analogue of [`Rc`][rc].
319 ///
320 /// Any types with interior mutability must also use the
321 /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
322 /// can be mutated through a shared reference. Failing to doing this is
323 /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
324 /// from `&T` to `&mut T` is invalid.
325 ///
326 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more
327 /// details about `Sync`.
328 ///
329 /// [send]: trait.Send.html
330 /// [u8]: ../../std/primitive.u8.html
331 /// [f64]: ../../std/primitive.f64.html
332 /// [box]: ../../std/boxed/struct.Box.html
333 /// [vec]: ../../std/vec/struct.Vec.html
334 /// [cell]: ../cell/struct.Cell.html
335 /// [refcell]: ../cell/struct.RefCell.html
336 /// [rc]: ../../std/rc/struct.Rc.html
337 /// [arc]: ../../std/sync/struct.Arc.html
338 /// [atomic data types]: ../sync/atomic/index.html
339 /// [mutex]: ../../std/sync/struct.Mutex.html
340 /// [rwlock]: ../../std/sync/struct.RwLock.html
341 /// [unsafecell]: ../cell/struct.UnsafeCell.html
342 /// [ub]: ../../reference/behavior-considered-undefined.html
343 /// [transmute]: ../../std/mem/fn.transmute.html
344 #[stable(feature = "rust1", since = "1.0.0")]
345 #[lang = "sync"]
346 #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
347 pub unsafe trait Sync {
348     // Empty
349 }
350
351 #[stable(feature = "rust1", since = "1.0.0")]
352 unsafe impl Sync for .. { }
353
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<T: ?Sized> !Sync for *const T { }
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl<T: ?Sized> !Sync for *mut T { }
358
359 macro_rules! impls{
360     ($t: ident) => (
361         #[stable(feature = "rust1", since = "1.0.0")]
362         impl<T:?Sized> Hash for $t<T> {
363             #[inline]
364             fn hash<H: Hasher>(&self, _: &mut H) {
365             }
366         }
367
368         #[stable(feature = "rust1", since = "1.0.0")]
369         impl<T:?Sized> cmp::PartialEq for $t<T> {
370             fn eq(&self, _other: &$t<T>) -> bool {
371                 true
372             }
373         }
374
375         #[stable(feature = "rust1", since = "1.0.0")]
376         impl<T:?Sized> cmp::Eq for $t<T> {
377         }
378
379         #[stable(feature = "rust1", since = "1.0.0")]
380         impl<T:?Sized> cmp::PartialOrd for $t<T> {
381             fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
382                 Option::Some(cmp::Ordering::Equal)
383             }
384         }
385
386         #[stable(feature = "rust1", since = "1.0.0")]
387         impl<T:?Sized> cmp::Ord for $t<T> {
388             fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
389                 cmp::Ordering::Equal
390             }
391         }
392
393         #[stable(feature = "rust1", since = "1.0.0")]
394         impl<T:?Sized> Copy for $t<T> { }
395
396         #[stable(feature = "rust1", since = "1.0.0")]
397         impl<T:?Sized> Clone for $t<T> {
398             fn clone(&self) -> $t<T> {
399                 $t
400             }
401         }
402
403         #[stable(feature = "rust1", since = "1.0.0")]
404         impl<T:?Sized> Default for $t<T> {
405             fn default() -> $t<T> {
406                 $t
407             }
408         }
409         )
410 }
411
412 /// Zero-sized type used to mark things that "act like" they own a `T`.
413 ///
414 /// Adding a `PhantomData<T>` field to your type tells the compiler that your
415 /// type acts as though it stores a value of type `T`, even though it doesn't
416 /// really. This information is used when computing certain safety properties.
417 ///
418 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see
419 /// [the Nomicon](../../nomicon/phantom-data.html).
420 ///
421 /// # A ghastly note ðŸ‘»ðŸ‘»ðŸ‘»
422 ///
423 /// Though they both have scary names, `PhantomData` and 'phantom types' are
424 /// related, but not identical. A phantom type parameter is simply a type
425 /// parameter which is never used. In Rust, this often causes the compiler to
426 /// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
427 ///
428 /// # Examples
429 ///
430 /// ## Unused lifetime parameters
431 ///
432 /// Perhaps the most common use case for `PhantomData` is a struct that has an
433 /// unused lifetime parameter, typically as part of some unsafe code. For
434 /// example, here is a struct `Slice` that has two pointers of type `*const T`,
435 /// presumably pointing into an array somewhere:
436 ///
437 /// ```ignore
438 /// struct Slice<'a, T> {
439 ///     start: *const T,
440 ///     end: *const T,
441 /// }
442 /// ```
443 ///
444 /// The intention is that the underlying data is only valid for the
445 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
446 /// intent is not expressed in the code, since there are no uses of
447 /// the lifetime `'a` and hence it is not clear what data it applies
448 /// to. We can correct this by telling the compiler to act *as if* the
449 /// `Slice` struct contained a reference `&'a T`:
450 ///
451 /// ```
452 /// use std::marker::PhantomData;
453 ///
454 /// # #[allow(dead_code)]
455 /// struct Slice<'a, T: 'a> {
456 ///     start: *const T,
457 ///     end: *const T,
458 ///     phantom: PhantomData<&'a T>,
459 /// }
460 /// ```
461 ///
462 /// This also in turn requires the annotation `T: 'a`, indicating
463 /// that any references in `T` are valid over the lifetime `'a`.
464 ///
465 /// When initializing a `Slice` you simply provide the value
466 /// `PhantomData` for the field `phantom`:
467 ///
468 /// ```
469 /// # #![allow(dead_code)]
470 /// # use std::marker::PhantomData;
471 /// # struct Slice<'a, T: 'a> {
472 /// #     start: *const T,
473 /// #     end: *const T,
474 /// #     phantom: PhantomData<&'a T>,
475 /// # }
476 /// fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
477 ///     let ptr = vec.as_ptr();
478 ///     Slice {
479 ///         start: ptr,
480 ///         end: unsafe { ptr.offset(vec.len() as isize) },
481 ///         phantom: PhantomData,
482 ///     }
483 /// }
484 /// ```
485 ///
486 /// ## Unused type parameters
487 ///
488 /// It sometimes happens that you have unused type parameters which
489 /// indicate what type of data a struct is "tied" to, even though that
490 /// data is not actually found in the struct itself. Here is an
491 /// example where this arises with [FFI]. The foreign interface uses
492 /// handles of type `*mut ()` to refer to Rust values of different
493 /// types. We track the Rust type using a phantom type parameter on
494 /// the struct `ExternalResource` which wraps a handle.
495 ///
496 /// [FFI]: ../../book/ffi.html
497 ///
498 /// ```
499 /// # #![allow(dead_code)]
500 /// # trait ResType { }
501 /// # struct ParamType;
502 /// # mod foreign_lib {
503 /// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }
504 /// #     pub fn do_stuff(_: *mut (), _: usize) {}
505 /// # }
506 /// # fn convert_params(_: ParamType) -> usize { 42 }
507 /// use std::marker::PhantomData;
508 /// use std::mem;
509 ///
510 /// struct ExternalResource<R> {
511 ///    resource_handle: *mut (),
512 ///    resource_type: PhantomData<R>,
513 /// }
514 ///
515 /// impl<R: ResType> ExternalResource<R> {
516 ///     fn new() -> ExternalResource<R> {
517 ///         let size_of_res = mem::size_of::<R>();
518 ///         ExternalResource {
519 ///             resource_handle: foreign_lib::new(size_of_res),
520 ///             resource_type: PhantomData,
521 ///         }
522 ///     }
523 ///
524 ///     fn do_stuff(&self, param: ParamType) {
525 ///         let foreign_params = convert_params(param);
526 ///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
527 ///     }
528 /// }
529 /// ```
530 ///
531 /// ## Ownership and the drop check
532 ///
533 /// Adding a field of type `PhantomData<T>` indicates that your
534 /// type owns data of type `T`. This in turn implies that when your
535 /// type is dropped, it may drop one or more instances of the type
536 /// `T`. This has bearing on the Rust compiler's [drop check]
537 /// analysis.
538 ///
539 /// If your struct does not in fact *own* the data of type `T`, it is
540 /// better to use a reference type, like `PhantomData<&'a T>`
541 /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
542 /// as not to indicate ownership.
543 ///
544 /// [drop check]: ../../nomicon/dropck.html
545 #[lang = "phantom_data"]
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub struct PhantomData<T:?Sized>;
548
549 impls! { PhantomData }
550
551 mod impls {
552     #[stable(feature = "rust1", since = "1.0.0")]
553     unsafe impl<'a, T: Sync + ?Sized> Send for &'a T {}
554     #[stable(feature = "rust1", since = "1.0.0")]
555     unsafe impl<'a, T: Send + ?Sized> Send for &'a mut T {}
556 }
557
558 /// Compiler-internal trait used to determine whether a type contains
559 /// any `UnsafeCell` internally, but not through an indirection.
560 /// This affects, for example, whether a `static` of that type is
561 /// placed in read-only static memory or writable static memory.
562 #[cfg_attr(not(stage0), lang = "freeze")]
563 unsafe trait Freeze {}
564
565 unsafe impl Freeze for .. {}
566
567 impl<T: ?Sized> !Freeze for UnsafeCell<T> {}
568 unsafe impl<T: ?Sized> Freeze for PhantomData<T> {}
569 unsafe impl<T: ?Sized> Freeze for *const T {}
570 unsafe impl<T: ?Sized> Freeze for *mut T {}
571 unsafe impl<'a, T: ?Sized> Freeze for &'a T {}
572 unsafe impl<'a, T: ?Sized> Freeze for &'a mut T {}