]> git.proxmox.com Git - rustc.git/blob - src/libcore/marker.rs
Imported Upstream version 1.11.0+dfsg1
[rustc.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 marker types representing basic 'kinds' of types.
12 //!
13 //! Rust types can be classified in various useful ways according to
14 //! intrinsic properties of the type. These classifications, often called
15 //! 'kinds', are represented as traits.
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 use clone::Clone;
20 use cmp;
21 use default::Default;
22 use option::Option;
23 use hash::Hash;
24 use hash::Hasher;
25
26 /// Types that can be transferred across thread boundaries.
27 ///
28 /// This trait is automatically derived when the compiler determines it's appropriate.
29 #[stable(feature = "rust1", since = "1.0.0")]
30 #[lang = "send"]
31 #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
32 pub unsafe trait Send {
33 // empty.
34 }
35
36 #[stable(feature = "rust1", since = "1.0.0")]
37 unsafe impl Send for .. { }
38
39 #[stable(feature = "rust1", since = "1.0.0")]
40 impl<T: ?Sized> !Send for *const T { }
41 #[stable(feature = "rust1", since = "1.0.0")]
42 impl<T: ?Sized> !Send for *mut T { }
43
44 /// Types with a constant size known at compile-time.
45 ///
46 /// All type parameters which can be bounded have an implicit bound of `Sized`. The special syntax
47 /// `?Sized` can be used to remove this bound if it is not appropriate.
48 ///
49 /// ```
50 /// # #![allow(dead_code)]
51 /// struct Foo<T>(T);
52 /// struct Bar<T: ?Sized>(T);
53 ///
54 /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
55 /// struct BarUse(Bar<[i32]>); // OK
56 /// ```
57 #[stable(feature = "rust1", since = "1.0.0")]
58 #[lang = "sized"]
59 #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
60 #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
61 pub trait Sized {
62 // Empty.
63 }
64
65 /// Types that can be "unsized" to a dynamically sized type.
66 #[unstable(feature = "unsize", issue = "27732")]
67 #[lang="unsize"]
68 pub trait Unsize<T: ?Sized> {
69 // Empty.
70 }
71
72 /// Types that can be copied by simply copying bits (i.e. `memcpy`).
73 ///
74 /// By default, variable bindings have 'move semantics.' In other
75 /// words:
76 ///
77 /// ```
78 /// #[derive(Debug)]
79 /// struct Foo;
80 ///
81 /// let x = Foo;
82 ///
83 /// let y = x;
84 ///
85 /// // `x` has moved into `y`, and so cannot be used
86 ///
87 /// // println!("{:?}", x); // error: use of moved value
88 /// ```
89 ///
90 /// However, if a type implements `Copy`, it instead has 'copy semantics':
91 ///
92 /// ```
93 /// // we can just derive a `Copy` implementation
94 /// #[derive(Debug, Copy, Clone)]
95 /// struct Foo;
96 ///
97 /// let x = Foo;
98 ///
99 /// let y = x;
100 ///
101 /// // `y` is a copy of `x`
102 ///
103 /// println!("{:?}", x); // A-OK!
104 /// ```
105 ///
106 /// It's important to note that in these two examples, the only difference is if you are allowed to
107 /// access `x` after the assignment: a move is also a bitwise copy under the hood.
108 ///
109 /// ## When can my type be `Copy`?
110 ///
111 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
112 /// `struct` can be `Copy`:
113 ///
114 /// ```
115 /// # #[allow(dead_code)]
116 /// struct Point {
117 /// x: i32,
118 /// y: i32,
119 /// }
120 /// ```
121 ///
122 /// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
123 ///
124 /// ```
125 /// # #![allow(dead_code)]
126 /// # struct Point;
127 /// struct PointList {
128 /// points: Vec<Point>,
129 /// }
130 /// ```
131 ///
132 /// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
133 /// attempt to derive a `Copy` implementation, we'll get an error:
134 ///
135 /// ```text
136 /// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
137 /// ```
138 ///
139 /// ## When can my type _not_ be `Copy`?
140 ///
141 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
142 /// mutable reference, and copying `String` would result in two attempts to free the same buffer.
143 ///
144 /// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
145 /// managing some resource besides its own `size_of::<T>()` bytes.
146 ///
147 /// ## When should my type be `Copy`?
148 ///
149 /// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
150 /// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
151 /// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
152 /// change: that second example would fail to compile if we made `Foo` non-`Copy`.
153 ///
154 /// ## Derivable
155 ///
156 /// This trait can be used with `#[derive]` if all of its components implement `Copy` and the type
157 /// implements `Clone`. The implementation will copy the bytes of each field using `memcpy`.
158 ///
159 /// ## How can I implement `Copy`?
160 ///
161 /// There are two ways to implement `Copy` on your type:
162 ///
163 /// ```
164 /// #[derive(Copy, Clone)]
165 /// struct MyStruct;
166 /// ```
167 ///
168 /// and
169 ///
170 /// ```
171 /// struct MyStruct;
172 /// impl Copy for MyStruct {}
173 /// impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }
174 /// ```
175 ///
176 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
177 /// bound on type parameters, which isn't always desired.
178 #[stable(feature = "rust1", since = "1.0.0")]
179 #[lang = "copy"]
180 pub trait Copy : Clone {
181 // Empty.
182 }
183
184 /// Types that can be safely shared between threads when aliased.
185 ///
186 /// The precise definition is: a type `T` is `Sync` if `&T` is
187 /// thread-safe. In other words, there is no possibility of data races
188 /// when passing `&T` references between threads.
189 ///
190 /// As one would expect, primitive types like `u8` and `f64` are all
191 /// `Sync`, and so are simple aggregate types containing them (like
192 /// tuples, structs and enums). More instances of basic `Sync` types
193 /// include "immutable" types like `&T` and those with simple
194 /// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
195 /// collection types. (Generic parameters need to be `Sync` for their
196 /// container to be `Sync`.)
197 ///
198 /// A somewhat surprising consequence of the definition is `&mut T` is
199 /// `Sync` (if `T` is `Sync`) even though it seems that it might
200 /// provide unsynchronized mutation. The trick is a mutable reference
201 /// stored in an aliasable reference (that is, `& &mut T`) becomes
202 /// read-only, as if it were a `& &T`, hence there is no risk of a data
203 /// race.
204 ///
205 /// Types that are not `Sync` are those that have "interior
206 /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
207 /// in `std::cell`. These types allow for mutation of their contents
208 /// even when in an immutable, aliasable slot, e.g. the contents of
209 /// `&Cell<T>` can be `.set`, and do not ensure data races are
210 /// impossible, hence they cannot be `Sync`. A higher level example
211 /// of a non-`Sync` type is the reference counted pointer
212 /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
213 /// reference, which modifies the reference counts in a non-atomic
214 /// way.
215 ///
216 /// For cases when one does need thread-safe interior mutability,
217 /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
218 /// the `sync` crate do ensure that any mutation cannot cause data
219 /// races. Hence these types are `Sync`.
220 ///
221 /// Any types with interior mutability must also use the `std::cell::UnsafeCell`
222 /// wrapper around the value(s) which can be mutated when behind a `&`
223 /// reference; not doing this is undefined behavior (for example,
224 /// `transmute`-ing from `&T` to `&mut T` is invalid).
225 ///
226 /// This trait is automatically derived when the compiler determines it's appropriate.
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[lang = "sync"]
229 #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
230 pub unsafe trait Sync {
231 // Empty
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 unsafe impl Sync for .. { }
236
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<T: ?Sized> !Sync for *const T { }
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl<T: ?Sized> !Sync for *mut T { }
241
242 macro_rules! impls{
243 ($t: ident) => (
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<T:?Sized> Hash for $t<T> {
246 #[inline]
247 fn hash<H: Hasher>(&self, _: &mut H) {
248 }
249 }
250
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<T:?Sized> cmp::PartialEq for $t<T> {
253 fn eq(&self, _other: &$t<T>) -> bool {
254 true
255 }
256 }
257
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T:?Sized> cmp::Eq for $t<T> {
260 }
261
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T:?Sized> cmp::PartialOrd for $t<T> {
264 fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
265 Option::Some(cmp::Ordering::Equal)
266 }
267 }
268
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T:?Sized> cmp::Ord for $t<T> {
271 fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
272 cmp::Ordering::Equal
273 }
274 }
275
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T:?Sized> Copy for $t<T> { }
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<T:?Sized> Clone for $t<T> {
281 fn clone(&self) -> $t<T> {
282 $t
283 }
284 }
285
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T:?Sized> Default for $t<T> {
288 fn default() -> $t<T> {
289 $t
290 }
291 }
292 )
293 }
294
295 /// `PhantomData<T>` allows you to describe that a type acts as if it stores a value of type `T`,
296 /// even though it does not. This allows you to inform the compiler about certain safety properties
297 /// of your code.
298 ///
299 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see [the Nomicon].
300 ///
301 /// [the Nomicon]: ../../nomicon/phantom-data.html
302 ///
303 /// # A ghastly note 👻👻👻
304 ///
305 /// Though they both have scary names, `PhantomData<T>` and 'phantom types' are related, but not
306 /// identical. Phantom types are a more general concept that don't require `PhantomData<T>` to
307 /// implement, but `PhantomData<T>` is the most common way to implement them in a correct manner.
308 ///
309 /// # Examples
310 ///
311 /// ## Unused lifetime parameter
312 ///
313 /// Perhaps the most common time that `PhantomData` is required is
314 /// with a struct that has an unused lifetime parameter, typically as
315 /// part of some unsafe code. For example, here is a struct `Slice`
316 /// that has two pointers of type `*const T`, presumably pointing into
317 /// an array somewhere:
318 ///
319 /// ```ignore
320 /// struct Slice<'a, T> {
321 /// start: *const T,
322 /// end: *const T,
323 /// }
324 /// ```
325 ///
326 /// The intention is that the underlying data is only valid for the
327 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
328 /// intent is not expressed in the code, since there are no uses of
329 /// the lifetime `'a` and hence it is not clear what data it applies
330 /// to. We can correct this by telling the compiler to act *as if* the
331 /// `Slice` struct contained a borrowed reference `&'a T`:
332 ///
333 /// ```
334 /// use std::marker::PhantomData;
335 ///
336 /// # #[allow(dead_code)]
337 /// struct Slice<'a, T: 'a> {
338 /// start: *const T,
339 /// end: *const T,
340 /// phantom: PhantomData<&'a T>
341 /// }
342 /// ```
343 ///
344 /// This also in turn requires that we annotate `T:'a`, indicating
345 /// that `T` is a type that can be borrowed for the lifetime `'a`.
346 ///
347 /// ## Unused type parameters
348 ///
349 /// It sometimes happens that there are unused type parameters that
350 /// indicate what type of data a struct is "tied" to, even though that
351 /// data is not actually found in the struct itself. Here is an
352 /// example where this arises when handling external resources over a
353 /// foreign function interface. `PhantomData<T>` can prevent
354 /// mismatches by enforcing types in the method implementations:
355 ///
356 /// ```
357 /// # #![allow(dead_code)]
358 /// # trait ResType { fn foo(&self); }
359 /// # struct ParamType;
360 /// # mod foreign_lib {
361 /// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
362 /// # pub fn do_stuff(_: *mut (), _: usize) {}
363 /// # }
364 /// # fn convert_params(_: ParamType) -> usize { 42 }
365 /// use std::marker::PhantomData;
366 /// use std::mem;
367 ///
368 /// struct ExternalResource<R> {
369 /// resource_handle: *mut (),
370 /// resource_type: PhantomData<R>,
371 /// }
372 ///
373 /// impl<R: ResType> ExternalResource<R> {
374 /// fn new() -> ExternalResource<R> {
375 /// let size_of_res = mem::size_of::<R>();
376 /// ExternalResource {
377 /// resource_handle: foreign_lib::new(size_of_res),
378 /// resource_type: PhantomData,
379 /// }
380 /// }
381 ///
382 /// fn do_stuff(&self, param: ParamType) {
383 /// let foreign_params = convert_params(param);
384 /// foreign_lib::do_stuff(self.resource_handle, foreign_params);
385 /// }
386 /// }
387 /// ```
388 ///
389 /// ## Indicating ownership
390 ///
391 /// Adding a field of type `PhantomData<T>` also indicates that your
392 /// struct owns data of type `T`. This in turn implies that when your
393 /// struct is dropped, it may in turn drop one or more instances of
394 /// the type `T`, though that may not be apparent from the other
395 /// structure of the type itself. This is commonly necessary if the
396 /// structure is using a raw pointer like `*mut T` whose referent
397 /// may be dropped when the type is dropped, as a `*mut T` is
398 /// otherwise not treated as owned.
399 ///
400 /// If your struct does not in fact *own* the data of type `T`, it is
401 /// better to use a reference type, like `PhantomData<&'a T>`
402 /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
403 /// as not to indicate ownership.
404 #[lang = "phantom_data"]
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub struct PhantomData<T:?Sized>;
407
408 impls! { PhantomData }
409
410 mod impls {
411 use super::{Send, Sync, Sized};
412
413 #[stable(feature = "rust1", since = "1.0.0")]
414 unsafe impl<'a, T: Sync + ?Sized> Send for &'a T {}
415 #[stable(feature = "rust1", since = "1.0.0")]
416 unsafe impl<'a, T: Send + ?Sized> Send for &'a mut T {}
417 }
418
419 /// Types that can be reflected over.
420 ///
421 /// This trait is implemented for all types. Its purpose is to ensure
422 /// that when you write a generic function that will employ
423 /// reflection, that must be reflected (no pun intended) in the
424 /// generic bounds of that function. Here is an example:
425 ///
426 /// ```
427 /// #![feature(reflect_marker)]
428 /// use std::marker::Reflect;
429 /// use std::any::Any;
430 ///
431 /// # #[allow(dead_code)]
432 /// fn foo<T: Reflect + 'static>(x: &T) {
433 /// let any: &Any = x;
434 /// if any.is::<u32>() { println!("u32"); }
435 /// }
436 /// ```
437 ///
438 /// Without the declaration `T: Reflect`, `foo` would not type check
439 /// (note: as a matter of style, it would be preferable to write
440 /// `T: Any`, because `T: Any` implies `T: Reflect` and `T: 'static`, but
441 /// we use `Reflect` here to show how it works). The `Reflect` bound
442 /// thus serves to alert `foo`'s caller to the fact that `foo` may
443 /// behave differently depending on whether `T = u32` or not. In
444 /// particular, thanks to the `Reflect` bound, callers know that a
445 /// function declared like `fn bar<T>(...)` will always act in
446 /// precisely the same way no matter what type `T` is supplied,
447 /// because there are no bounds declared on `T`. (The ability for a
448 /// caller to reason about what a function may do based solely on what
449 /// generic bounds are declared is often called the ["parametricity
450 /// property"][1].)
451 ///
452 /// [1]: http://en.wikipedia.org/wiki/Parametricity
453 #[rustc_reflect_like]
454 #[unstable(feature = "reflect_marker",
455 reason = "requires RFC and more experience",
456 issue = "27749")]
457 #[rustc_on_unimplemented = "`{Self}` does not implement `Any`; \
458 ensure all type parameters are bounded by `Any`"]
459 pub trait Reflect {}
460
461 #[unstable(feature = "reflect_marker",
462 reason = "requires RFC and more experience",
463 issue = "27749")]
464 impl Reflect for .. { }