]> git.lizzy.rs Git - rust.git/blob - src/libcore/marker.rs
Rollup merge of #40521 - TimNN:panic-free-shift, 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 cmp;
20 use hash::Hash;
21 use hash::Hasher;
22
23 /// Types that can be transferred across thread boundaries.
24 ///
25 /// This trait is automatically implemented when the compiler determines it's
26 /// appropriate.
27 ///
28 /// An example of a non-`Send` type is the reference-counting pointer
29 /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same
30 /// reference-counted value, they might try to update the reference count at the
31 /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic
32 /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring
33 /// some overhead) and thus is `Send`.
34 ///
35 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more details.
36 ///
37 /// [`Rc`]: ../../std/rc/struct.Rc.html
38 /// [arc]: ../../std/sync/struct.Arc.html
39 /// [ub]: ../../reference/behavior-considered-undefined.html
40 #[stable(feature = "rust1", since = "1.0.0")]
41 #[lang = "send"]
42 #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
43 pub unsafe trait Send {
44     // empty.
45 }
46
47 #[stable(feature = "rust1", since = "1.0.0")]
48 unsafe impl Send for .. { }
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, which does not
70 /// get an implicit `Sized` bound. This is because a `Sized` bound prevents
71 /// the trait from being used to form a [trait object]:
72 ///
73 /// ```
74 /// # #![allow(unused_variables)]
75 /// trait Foo { }
76 /// trait Bar: Sized { }
77 ///
78 /// struct Impl;
79 /// impl Foo for Impl { }
80 /// impl Bar for Impl { }
81 ///
82 /// let x: &Foo = &Impl;    // OK
83 /// // let y: &Bar = &Impl; // error: the trait `Bar` cannot
84 ///                         // be made into an object
85 /// ```
86 ///
87 /// [trait object]: ../../book/trait-objects.html
88 #[stable(feature = "rust1", since = "1.0.0")]
89 #[lang = "sized"]
90 #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
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
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 need only 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 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
263 /// [`String`]: ../../std/string/struct.String.html
264 /// [`Drop`]: ../../std/ops/trait.Drop.html
265 /// [`size_of::<T>`]: ../../std/mem/fn.size_of.html
266 /// [`Clone`]: ../clone/trait.Clone.html
267 /// [`String`]: ../../std/string/struct.String.html
268 /// [`i32`]: ../../std/primitive.i32.html
269 #[stable(feature = "rust1", since = "1.0.0")]
270 #[lang = "copy"]
271 pub trait Copy : Clone {
272     // Empty.
273 }
274
275 /// Types for which it is safe to share references between threads.
276 ///
277 /// This trait is automatically implemented when the compiler determines
278 /// it's appropriate.
279 ///
280 /// The precise definition is: a type `T` is `Sync` if `&T` is
281 /// [`Send`][send]. In other words, if there is no possibility of
282 /// [undefined behavior][ub] (including data races) when passing
283 /// `&T` references between threads.
284 ///
285 /// As one would expect, primitive types like [`u8`][u8] and [`f64`][f64]
286 /// are all `Sync`, and so are simple aggregate types containing them,
287 /// like tuples, structs and enums. More examples of basic `Sync`
288 /// types include "immutable" types like `&T`, and those with simple
289 /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
290 /// most other collection types. (Generic parameters need to be `Sync`
291 /// for their container to be `Sync`.)
292 ///
293 /// A somewhat surprising consequence of the definition is that `&mut T`
294 /// is `Sync` (if `T` is `Sync`) even though it seems like that might
295 /// provide unsynchronized mutation. The trick is that a mutable
296 /// reference behind a shared reference (that is, `& &mut T`)
297 /// becomes read-only, as if it were a `& &T`. Hence there is no risk
298 /// of a data race.
299 ///
300 /// Types that are not `Sync` are those that have "interior
301 /// mutability" in a non-thread-safe form, such as [`cell::Cell`][cell]
302 /// and [`cell::RefCell`][refcell]. These types allow for mutation of
303 /// their contents even through an immutable, shared reference. For
304 /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
305 /// only a shared reference [`&Cell<T>`][cell]. The method performs no
306 /// synchronization, thus [`Cell`][cell] cannot be `Sync`.
307 ///
308 /// Another example of a non-`Sync` type is the reference-counting
309 /// pointer [`rc::Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
310 /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
311 ///
312 /// For cases when one does need thread-safe interior mutability,
313 /// Rust provides [atomic data types], as well as explicit locking via
314 /// [`sync::Mutex`][mutex] and [`sync::RWLock`][rwlock]. These types
315 /// ensure that any mutation cannot cause data races, hence the types
316 /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
317 /// analogue of [`Rc`][rc].
318 ///
319 /// Any types with interior mutability must also use the
320 /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
321 /// can be mutated through a shared reference. Failing to doing this is
322 /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
323 /// from `&T` to `&mut T` is invalid.
324 ///
325 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more
326 /// details about `Sync`.
327 ///
328 /// [send]: trait.Send.html
329 /// [u8]: ../../std/primitive.u8.html
330 /// [f64]: ../../std/primitive.f64.html
331 /// [box]: ../../std/boxed/struct.Box.html
332 /// [vec]: ../../std/vec/struct.Vec.html
333 /// [cell]: ../cell/struct.Cell.html
334 /// [refcell]: ../cell/struct.RefCell.html
335 /// [rc]: ../../std/rc/struct.Rc.html
336 /// [arc]: ../../std/sync/struct.Arc.html
337 /// [atomic data types]: ../sync/atomic/index.html
338 /// [mutex]: ../../std/sync/struct.Mutex.html
339 /// [rwlock]: ../../std/sync/struct.RwLock.html
340 /// [unsafecell]: ../cell/struct.UnsafeCell.html
341 /// [ub]: ../../reference/behavior-considered-undefined.html
342 /// [transmute]: ../../std/mem/fn.transmute.html
343 #[stable(feature = "rust1", since = "1.0.0")]
344 #[lang = "sync"]
345 #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
346 pub unsafe trait Sync {
347     // Empty
348 }
349
350 #[stable(feature = "rust1", since = "1.0.0")]
351 unsafe impl Sync for .. { }
352
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<T: ?Sized> !Sync for *const T { }
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl<T: ?Sized> !Sync for *mut T { }
357
358 macro_rules! impls{
359     ($t: ident) => (
360         #[stable(feature = "rust1", since = "1.0.0")]
361         impl<T:?Sized> Hash for $t<T> {
362             #[inline]
363             fn hash<H: Hasher>(&self, _: &mut H) {
364             }
365         }
366
367         #[stable(feature = "rust1", since = "1.0.0")]
368         impl<T:?Sized> cmp::PartialEq for $t<T> {
369             fn eq(&self, _other: &$t<T>) -> bool {
370                 true
371             }
372         }
373
374         #[stable(feature = "rust1", since = "1.0.0")]
375         impl<T:?Sized> cmp::Eq for $t<T> {
376         }
377
378         #[stable(feature = "rust1", since = "1.0.0")]
379         impl<T:?Sized> cmp::PartialOrd for $t<T> {
380             fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
381                 Option::Some(cmp::Ordering::Equal)
382             }
383         }
384
385         #[stable(feature = "rust1", since = "1.0.0")]
386         impl<T:?Sized> cmp::Ord for $t<T> {
387             fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
388                 cmp::Ordering::Equal
389             }
390         }
391
392         #[stable(feature = "rust1", since = "1.0.0")]
393         impl<T:?Sized> Copy for $t<T> { }
394
395         #[stable(feature = "rust1", since = "1.0.0")]
396         impl<T:?Sized> Clone for $t<T> {
397             fn clone(&self) -> $t<T> {
398                 $t
399             }
400         }
401
402         #[stable(feature = "rust1", since = "1.0.0")]
403         impl<T:?Sized> Default for $t<T> {
404             fn default() -> $t<T> {
405                 $t
406             }
407         }
408         )
409 }
410
411 /// Zero-sized type used to mark things that "act like" they own a `T`.
412 ///
413 /// Adding a `PhantomData<T>` field to your type tells the compiler that your
414 /// type acts as though it stores a value of type `T`, even though it doesn't
415 /// really. This information is used when computing certain safety properties.
416 ///
417 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see
418 /// [the Nomicon](../../nomicon/phantom-data.html).
419 ///
420 /// # A ghastly note ðŸ‘»ðŸ‘»ðŸ‘»
421 ///
422 /// Though they both have scary names, `PhantomData` and 'phantom types' are
423 /// related, but not identical. A phantom type parameter is simply a type
424 /// parameter which is never used. In Rust, this often causes the compiler to
425 /// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
426 ///
427 /// # Examples
428 ///
429 /// ## Unused lifetime parameters
430 ///
431 /// Perhaps the most common use case for `PhantomData` is a struct that has an
432 /// unused lifetime parameter, typically as part of some unsafe code. For
433 /// example, here is a struct `Slice` that has two pointers of type `*const T`,
434 /// presumably pointing into an array somewhere:
435 ///
436 /// ```ignore
437 /// struct Slice<'a, T> {
438 ///     start: *const T,
439 ///     end: *const T,
440 /// }
441 /// ```
442 ///
443 /// The intention is that the underlying data is only valid for the
444 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
445 /// intent is not expressed in the code, since there are no uses of
446 /// the lifetime `'a` and hence it is not clear what data it applies
447 /// to. We can correct this by telling the compiler to act *as if* the
448 /// `Slice` struct contained a reference `&'a T`:
449 ///
450 /// ```
451 /// use std::marker::PhantomData;
452 ///
453 /// # #[allow(dead_code)]
454 /// struct Slice<'a, T: 'a> {
455 ///     start: *const T,
456 ///     end: *const T,
457 ///     phantom: PhantomData<&'a T>,
458 /// }
459 /// ```
460 ///
461 /// This also in turn requires the annotation `T: 'a`, indicating
462 /// that any references in `T` are valid over the lifetime `'a`.
463 ///
464 /// When initializing a `Slice` you simply provide the value
465 /// `PhantomData` for the field `phantom`:
466 ///
467 /// ```
468 /// # #![allow(dead_code)]
469 /// # use std::marker::PhantomData;
470 /// # struct Slice<'a, T: 'a> {
471 /// #     start: *const T,
472 /// #     end: *const T,
473 /// #     phantom: PhantomData<&'a T>,
474 /// # }
475 /// fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
476 ///     let ptr = vec.as_ptr();
477 ///     Slice {
478 ///         start: ptr,
479 ///         end: unsafe { ptr.offset(vec.len() as isize) },
480 ///         phantom: PhantomData,
481 ///     }
482 /// }
483 /// ```
484 ///
485 /// ## Unused type parameters
486 ///
487 /// It sometimes happens that you have unused type parameters which
488 /// indicate what type of data a struct is "tied" to, even though that
489 /// data is not actually found in the struct itself. Here is an
490 /// example where this arises with [FFI]. The foreign interface uses
491 /// handles of type `*mut ()` to refer to Rust values of different
492 /// types. We track the Rust type using a phantom type parameter on
493 /// the struct `ExternalResource` which wraps a handle.
494 ///
495 /// [FFI]: ../../book/ffi.html
496 ///
497 /// ```
498 /// # #![allow(dead_code)]
499 /// # trait ResType { }
500 /// # struct ParamType;
501 /// # mod foreign_lib {
502 /// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }
503 /// #     pub fn do_stuff(_: *mut (), _: usize) {}
504 /// # }
505 /// # fn convert_params(_: ParamType) -> usize { 42 }
506 /// use std::marker::PhantomData;
507 /// use std::mem;
508 ///
509 /// struct ExternalResource<R> {
510 ///    resource_handle: *mut (),
511 ///    resource_type: PhantomData<R>,
512 /// }
513 ///
514 /// impl<R: ResType> ExternalResource<R> {
515 ///     fn new() -> ExternalResource<R> {
516 ///         let size_of_res = mem::size_of::<R>();
517 ///         ExternalResource {
518 ///             resource_handle: foreign_lib::new(size_of_res),
519 ///             resource_type: PhantomData,
520 ///         }
521 ///     }
522 ///
523 ///     fn do_stuff(&self, param: ParamType) {
524 ///         let foreign_params = convert_params(param);
525 ///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
526 ///     }
527 /// }
528 /// ```
529 ///
530 /// ## Ownership and the drop check
531 ///
532 /// Adding a field of type `PhantomData<T>` indicates that your
533 /// type owns data of type `T`. This in turn implies that when your
534 /// type is dropped, it may drop one or more instances of the type
535 /// `T`. This has bearing on the Rust compiler's [drop check]
536 /// analysis.
537 ///
538 /// If your struct does not in fact *own* the data of type `T`, it is
539 /// better to use a reference type, like `PhantomData<&'a T>`
540 /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
541 /// as not to indicate ownership.
542 ///
543 /// [drop check]: ../../nomicon/dropck.html
544 #[lang = "phantom_data"]
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub struct PhantomData<T:?Sized>;
547
548 impls! { PhantomData }
549
550 mod impls {
551     #[stable(feature = "rust1", since = "1.0.0")]
552     unsafe impl<'a, T: Sync + ?Sized> Send for &'a T {}
553     #[stable(feature = "rust1", since = "1.0.0")]
554     unsafe impl<'a, T: Send + ?Sized> Send for &'a mut T {}
555 }