]> git.lizzy.rs Git - rust.git/blob - src/libcore/marker.rs
Rollup merge of #21579 - brson:beta, 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 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]
27
28 use clone::Clone;
29
30 /// Types able to be transferred across thread boundaries.
31 #[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
32 #[lang="send"]
33 #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
34 pub unsafe trait Send: 'static {
35     // empty.
36 }
37
38 /// Types with a constant size known at compile-time.
39 #[stable]
40 #[lang="sized"]
41 #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
42 pub trait Sized {
43     // Empty.
44 }
45
46 /// Types that can be copied by simply copying bits (i.e. `memcpy`).
47 ///
48 /// By default, variable bindings have 'move semantics.' In other
49 /// words:
50 ///
51 /// ```
52 /// #[derive(Show)]
53 /// struct Foo;
54 ///
55 /// let x = Foo;
56 ///
57 /// let y = x;
58 ///
59 /// // `x` has moved into `y`, and so cannot be used
60 ///
61 /// // println!("{:?}", x); // error: use of moved value
62 /// ```
63 ///
64 /// However, if a type implements `Copy`, it instead has 'copy semantics':
65 ///
66 /// ```
67 /// // we can just derive a `Copy` implementation
68 /// #[derive(Show, Copy)]
69 /// struct Foo;
70 ///
71 /// let x = Foo;
72 ///
73 /// let y = x;
74 ///
75 /// // `y` is a copy of `x`
76 ///
77 /// println!("{:?}", x); // A-OK!
78 /// ```
79 ///
80 /// It's important to note that in these two examples, the only difference is if you are allowed to
81 /// access `x` after the assignment: a move is also a bitwise copy under the hood.
82 ///
83 /// ## When can my type be `Copy`?
84 ///
85 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
86 /// `struct` can be `Copy`:
87 ///
88 /// ```
89 /// struct Point {
90 ///    x: i32,
91 ///    y: i32,
92 /// }
93 /// ```
94 ///
95 /// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
96 ///
97 /// ```
98 /// # struct Point;
99 /// struct PointList {
100 ///     points: Vec<Point>,
101 /// }
102 /// ```
103 ///
104 /// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
105 /// attempt to derive a `Copy` implementation, we'll get an error.
106 ///
107 /// ```text
108 /// error: the trait `Copy` may not be implemented for this type; field `points` does not implement
109 /// `Copy`
110 /// ```
111 ///
112 /// ## How can I implement `Copy`?
113 ///
114 /// There are two ways to implement `Copy` on your type:
115 ///
116 /// ```
117 /// #[derive(Copy)]
118 /// struct MyStruct;
119 /// ```
120 ///
121 /// and
122 ///
123 /// ```
124 /// struct MyStruct;
125 /// impl Copy for MyStruct {}
126 /// ```
127 ///
128 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
129 /// bound on type parameters, which isn't always desired.
130 ///
131 /// ## When can my type _not_ be `Copy`?
132 ///
133 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
134 /// mutable reference, and copying `String` would result in two attempts to free the same buffer.
135 ///
136 /// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
137 /// managing some resource besides its own `size_of::<T>()` bytes.
138 ///
139 /// ## When should my type be `Copy`?
140 ///
141 /// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
142 /// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
143 /// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
144 /// change: that second example would fail to compile if we made `Foo` non-`Copy`.
145 #[stable]
146 #[lang="copy"]
147 pub trait Copy {
148     // Empty.
149 }
150
151 /// Types that can be safely shared between threads when aliased.
152 ///
153 /// The precise definition is: a type `T` is `Sync` if `&T` is
154 /// thread-safe. In other words, there is no possibility of data races
155 /// when passing `&T` references between threads.
156 ///
157 /// As one would expect, primitive types like `u8` and `f64` are all
158 /// `Sync`, and so are simple aggregate types containing them (like
159 /// tuples, structs and enums). More instances of basic `Sync` types
160 /// include "immutable" types like `&T` and those with simple
161 /// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
162 /// collection types. (Generic parameters need to be `Sync` for their
163 /// container to be `Sync`.)
164 ///
165 /// A somewhat surprising consequence of the definition is `&mut T` is
166 /// `Sync` (if `T` is `Sync`) even though it seems that it might
167 /// provide unsynchronised mutation. The trick is a mutable reference
168 /// stored in an aliasable reference (that is, `& &mut T`) becomes
169 /// read-only, as if it were a `& &T`, hence there is no risk of a data
170 /// race.
171 ///
172 /// Types that are not `Sync` are those that have "interior
173 /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
174 /// in `std::cell`. These types allow for mutation of their contents
175 /// even when in an immutable, aliasable slot, e.g. the contents of
176 /// `&Cell<T>` can be `.set`, and do not ensure data races are
177 /// impossible, hence they cannot be `Sync`. A higher level example
178 /// of a non-`Sync` type is the reference counted pointer
179 /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
180 /// reference, which modifies the reference counts in a non-atomic
181 /// way.
182 ///
183 /// For cases when one does need thread-safe interior mutability,
184 /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
185 /// the `sync` crate do ensure that any mutation cannot cause data
186 /// races.  Hence these types are `Sync`.
187 ///
188 /// Users writing their own types with interior mutability (or anything
189 /// else that is not thread-safe) should use the `NoSync` marker type
190 /// (from `std::marker`) to ensure that the compiler doesn't
191 /// consider the user-defined type to be `Sync`.  Any types with
192 /// interior mutability must also use the `std::cell::UnsafeCell` wrapper
193 /// around the value(s) which can be mutated when behind a `&`
194 /// reference; not doing this is undefined behaviour (for example,
195 /// `transmute`-ing from `&T` to `&mut T` is illegal).
196 #[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
197 #[lang="sync"]
198 #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
199 pub unsafe trait Sync {
200     // Empty
201 }
202
203
204 /// A marker type whose type parameter `T` is considered to be
205 /// covariant with respect to the type itself. This is (typically)
206 /// used to indicate that an instance of the type `T` is being stored
207 /// into memory and read from, even though that may not be apparent.
208 ///
209 /// For more information about variance, refer to this Wikipedia
210 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
211 ///
212 /// *Note:* It is very unusual to have to add a covariant constraint.
213 /// If you are not sure, you probably want to use `InvariantType`.
214 ///
215 /// # Example
216 ///
217 /// Given a struct `S` that includes a type parameter `T`
218 /// but does not actually *reference* that type parameter:
219 ///
220 /// ```ignore
221 /// use std::mem;
222 ///
223 /// struct S<T> { x: *() }
224 /// fn get<T>(s: &S<T>) -> T {
225 ///    unsafe {
226 ///        let x: *T = mem::transmute(s.x);
227 ///        *x
228 ///    }
229 /// }
230 /// ```
231 ///
232 /// The type system would currently infer that the value of
233 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
234 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
235 /// any `U`). But this is incorrect because `get()` converts the
236 /// `*()` into a `*T` and reads from it. Therefore, we should include the
237 /// a marker field `CovariantType<T>` to inform the type checker that
238 /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
239 /// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
240 /// for some lifetime `'a`, but not the other way around).
241 #[unstable = "likely to change with new variance strategy"]
242 #[lang="covariant_type"]
243 #[derive(PartialEq, Eq, PartialOrd, Ord)]
244 pub struct CovariantType<T: ?Sized>;
245
246 impl<T: ?Sized> Copy for CovariantType<T> {}
247 impl<T: ?Sized> Clone for CovariantType<T> {
248     fn clone(&self) -> CovariantType<T> { *self }
249 }
250
251 /// A marker type whose type parameter `T` is considered to be
252 /// contravariant with respect to the type itself. This is (typically)
253 /// used to indicate that an instance of the type `T` will be consumed
254 /// (but not read from), even though that may not be apparent.
255 ///
256 /// For more information about variance, refer to this Wikipedia
257 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
258 ///
259 /// *Note:* It is very unusual to have to add a contravariant constraint.
260 /// If you are not sure, you probably want to use `InvariantType`.
261 ///
262 /// # Example
263 ///
264 /// Given a struct `S` that includes a type parameter `T`
265 /// but does not actually *reference* that type parameter:
266 ///
267 /// ```
268 /// use std::mem;
269 ///
270 /// struct S<T> { x: *const () }
271 /// fn get<T>(s: &S<T>, v: T) {
272 ///    unsafe {
273 ///        let x: fn(T) = mem::transmute(s.x);
274 ///        x(v)
275 ///    }
276 /// }
277 /// ```
278 ///
279 /// The type system would currently infer that the value of
280 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
281 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
282 /// any `U`). But this is incorrect because `get()` converts the
283 /// `*()` into a `fn(T)` and then passes a value of type `T` to it.
284 ///
285 /// Supplying a `ContravariantType` marker would correct the
286 /// problem, because it would mark `S` so that `S<T>` is only a
287 /// subtype of `S<U>` if `U` is a subtype of `T`; given that the
288 /// function requires arguments of type `T`, it must also accept
289 /// arguments of type `U`, hence such a conversion is safe.
290 #[unstable = "likely to change with new variance strategy"]
291 #[lang="contravariant_type"]
292 #[derive(PartialEq, Eq, PartialOrd, Ord)]
293 pub struct ContravariantType<T: ?Sized>;
294
295 impl<T: ?Sized> Copy for ContravariantType<T> {}
296 impl<T: ?Sized> Clone for ContravariantType<T> {
297     fn clone(&self) -> ContravariantType<T> { *self }
298 }
299
300 /// A marker type whose type parameter `T` is considered to be
301 /// invariant with respect to the type itself. This is (typically)
302 /// used to indicate that instances of the type `T` may be read or
303 /// written, even though that may not be apparent.
304 ///
305 /// For more information about variance, refer to this Wikipedia
306 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
307 ///
308 /// # Example
309 ///
310 /// The Cell type is an example which uses unsafe code to achieve
311 /// "interior" mutability:
312 ///
313 /// ```
314 /// struct Cell<T> { value: T }
315 /// ```
316 ///
317 /// The type system would infer that `value` is only read here and
318 /// never written, but in fact `Cell` uses unsafe code to achieve
319 /// interior mutability.
320 #[unstable = "likely to change with new variance strategy"]
321 #[lang="invariant_type"]
322 #[derive(PartialEq, Eq, PartialOrd, Ord)]
323 pub struct InvariantType<T: ?Sized>;
324
325 #[unstable = "likely to change with new variance strategy"]
326 impl<T: ?Sized> Copy for InvariantType<T> {}
327 #[unstable = "likely to change with new variance strategy"]
328 impl<T: ?Sized> Clone for InvariantType<T> {
329     fn clone(&self) -> InvariantType<T> { *self }
330 }
331
332 /// As `CovariantType`, but for lifetime parameters. Using
333 /// `CovariantLifetime<'a>` indicates that it is ok to substitute
334 /// a *longer* lifetime for `'a` than the one you originally
335 /// started with (e.g., you could convert any lifetime `'foo` to
336 /// `'static`). You almost certainly want `ContravariantLifetime`
337 /// instead, or possibly `InvariantLifetime`. The only case where
338 /// it would be appropriate is that you have a (type-casted, and
339 /// hence hidden from the type system) function pointer with a
340 /// signature like `fn(&'a T)` (and no other uses of `'a`). In
341 /// this case, it is ok to substitute a larger lifetime for `'a`
342 /// (e.g., `fn(&'static T)`), because the function is only
343 /// becoming more selective in terms of what it accepts as
344 /// argument.
345 ///
346 /// For more information about variance, refer to this Wikipedia
347 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
348 #[unstable = "likely to change with new variance strategy"]
349 #[lang="covariant_lifetime"]
350 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
351 pub struct CovariantLifetime<'a>;
352
353 /// As `ContravariantType`, but for lifetime parameters. Using
354 /// `ContravariantLifetime<'a>` indicates that it is ok to
355 /// substitute a *shorter* lifetime for `'a` than the one you
356 /// originally started with (e.g., you could convert `'static` to
357 /// any lifetime `'foo`). This is appropriate for cases where you
358 /// have an unsafe pointer that is actually a pointer into some
359 /// memory with lifetime `'a`, and thus you want to limit the
360 /// lifetime of your data structure to `'a`. An example of where
361 /// this is used is the iterator for vectors.
362 ///
363 /// For more information about variance, refer to this Wikipedia
364 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
365 #[unstable = "likely to change with new variance strategy"]
366 #[lang="contravariant_lifetime"]
367 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
368 pub struct ContravariantLifetime<'a>;
369
370 /// As `InvariantType`, but for lifetime parameters. Using
371 /// `InvariantLifetime<'a>` indicates that it is not ok to
372 /// substitute any other lifetime for `'a` besides its original
373 /// value. This is appropriate for cases where you have an unsafe
374 /// pointer that is actually a pointer into memory with lifetime `'a`,
375 /// and this pointer is itself stored in an inherently mutable
376 /// location (such as a `Cell`).
377 #[unstable = "likely to change with new variance strategy"]
378 #[lang="invariant_lifetime"]
379 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
380 pub struct InvariantLifetime<'a>;
381
382 /// A type which is considered "not POD", meaning that it is not
383 /// implicitly copyable. This is typically embedded in other types to
384 /// ensure that they are never copied, even if they lack a destructor.
385 #[unstable = "likely to change with new variance strategy"]
386 #[lang="no_copy_bound"]
387 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
388 #[allow(missing_copy_implementations)]
389 pub struct NoCopy;
390
391 /// A type which is considered managed by the GC. This is typically
392 /// embedded in other types.
393 #[unstable = "likely to change with new variance strategy"]
394 #[lang="managed_bound"]
395 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
396 #[allow(missing_copy_implementations)]
397 pub struct Managed;