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