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