]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
9e0c209e | 11 | //! Primitive traits and types representing basic properties of types. |
1a4d82fc JJ |
12 | //! |
13 | //! Rust types can be classified in various useful ways according to | |
9e0c209e SL |
14 | //! their intrinsic properties. These classifications are represented |
15 | //! as traits. | |
1a4d82fc | 16 | |
85aaf69f | 17 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 18 | |
cc61c64b | 19 | use cell::UnsafeCell; |
85aaf69f | 20 | use cmp; |
85aaf69f SL |
21 | use hash::Hash; |
22 | use hash::Hasher; | |
1a4d82fc | 23 | |
92a42be0 | 24 | /// Types that can be transferred across thread boundaries. |
9cc50fc6 | 25 | /// |
9e0c209e SL |
26 | /// This trait is automatically implemented when the compiler determines it's |
27 | /// appropriate. | |
28 | /// | |
29 | /// An example of a non-`Send` type is the reference-counting pointer | |
476ff2be | 30 | /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same |
9e0c209e | 31 | /// reference-counted value, they might try to update the reference count at the |
476ff2be | 32 | /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic |
9e0c209e SL |
33 | /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring |
34 | /// some overhead) and thus is `Send`. | |
35 | /// | |
36 | /// See [the Nomicon](../../nomicon/send-and-sync.html) for more details. | |
37 | /// | |
476ff2be | 38 | /// [`Rc`]: ../../std/rc/struct.Rc.html |
9e0c209e | 39 | /// [arc]: ../../std/sync/struct.Arc.html |
8bb4bdeb | 40 | /// [ub]: ../../reference/behavior-considered-undefined.html |
85aaf69f | 41 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 42 | #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"] |
2c00a5a8 | 43 | pub unsafe auto trait Send { |
9346a6ac AL |
44 | // empty. |
45 | } | |
46 | ||
92a42be0 SL |
47 | #[stable(feature = "rust1", since = "1.0.0")] |
48 | impl<T: ?Sized> !Send for *const T { } | |
49 | #[stable(feature = "rust1", since = "1.0.0")] | |
50 | impl<T: ?Sized> !Send for *mut T { } | |
c34b1796 | 51 | |
9e0c209e | 52 | /// Types with a constant size known at compile time. |
b039eaaf | 53 | /// |
9e0c209e SL |
54 | /// All type parameters have an implicit bound of `Sized`. The special syntax |
55 | /// `?Sized` can be used to remove this bound if it's not appropriate. | |
b039eaaf SL |
56 | /// |
57 | /// ``` | |
92a42be0 | 58 | /// # #![allow(dead_code)] |
b039eaaf SL |
59 | /// struct Foo<T>(T); |
60 | /// struct Bar<T: ?Sized>(T); | |
61 | /// | |
62 | /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32] | |
63 | /// struct BarUse(Bar<[i32]>); // OK | |
64 | /// ``` | |
9e0c209e | 65 | /// |
0531ce1d XL |
66 | /// The one exception is the implicit `Self` type of a trait. A trait does not |
67 | /// have an implicit `Sized` bound as this is incompatible with [trait object]s | |
68 | /// where, by definition, the trait needs to work with all possible implementors, | |
69 | /// and thus could be any size. | |
70 | /// | |
71 | /// Although Rust will let you bind `Sized` to a trait, you won't | |
72 | /// be able to use it to form a trait object later: | |
9e0c209e SL |
73 | /// |
74 | /// ``` | |
75 | /// # #![allow(unused_variables)] | |
76 | /// trait Foo { } | |
77 | /// trait Bar: Sized { } | |
78 | /// | |
79 | /// struct Impl; | |
80 | /// impl Foo for Impl { } | |
81 | /// impl Bar for Impl { } | |
82 | /// | |
83 | /// let x: &Foo = &Impl; // OK | |
84 | /// // let y: &Bar = &Impl; // error: the trait `Bar` cannot | |
85 | /// // be made into an object | |
86 | /// ``` | |
87 | /// | |
041b39d2 | 88 | /// [trait object]: ../../book/first-edition/trait-objects.html |
85aaf69f | 89 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 90 | #[lang = "sized"] |
85aaf69f | 91 | #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"] |
c34b1796 | 92 | #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable |
9346a6ac AL |
93 | pub trait Sized { |
94 | // Empty. | |
95 | } | |
96 | ||
9e0c209e SL |
97 | /// Types that can be "unsized" to a dynamically-sized type. |
98 | /// | |
99 | /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and | |
100 | /// `Unsize<fmt::Debug>`. | |
101 | /// | |
102 | /// All implementations of `Unsize` are provided automatically by the compiler. | |
103 | /// | |
32a655c1 SL |
104 | /// `Unsize` is implemented for: |
105 | /// | |
106 | /// - `[T; N]` is `Unsize<[T]>` | |
107 | /// - `T` is `Unsize<Trait>` when `T: Trait` | |
108 | /// - `Foo<..., T, ...>` is `Unsize<Foo<..., U, ...>>` if: | |
109 | /// - `T: Unsize<U>` | |
110 | /// - Foo is a struct | |
111 | /// - Only the last field of `Foo` has a type involving `T` | |
112 | /// - `T` is not part of the type of any other fields | |
113 | /// - `Bar<T>: Unsize<Bar<U>>`, if the last field of `Foo` has type `Bar<T>` | |
114 | /// | |
9e0c209e SL |
115 | /// `Unsize` is used along with [`ops::CoerceUnsized`][coerceunsized] to allow |
116 | /// "user-defined" containers such as [`rc::Rc`][rc] to contain dynamically-sized | |
32a655c1 SL |
117 | /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce] |
118 | /// for more details. | |
9e0c209e SL |
119 | /// |
120 | /// [coerceunsized]: ../ops/trait.CoerceUnsized.html | |
121 | /// [rc]: ../../std/rc/struct.Rc.html | |
122 | /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md | |
7cac9316 | 123 | /// [nomicon-coerce]: ../../nomicon/coercions.html |
e9174d1e | 124 | #[unstable(feature = "unsize", issue = "27732")] |
ea8adc8c | 125 | #[lang = "unsize"] |
e9174d1e | 126 | pub trait Unsize<T: ?Sized> { |
1a4d82fc JJ |
127 | // Empty. |
128 | } | |
129 | ||
9e0c209e | 130 | /// Types whose values can be duplicated simply by copying bits. |
85aaf69f SL |
131 | /// |
132 | /// By default, variable bindings have 'move semantics.' In other | |
133 | /// words: | |
134 | /// | |
135 | /// ``` | |
136 | /// #[derive(Debug)] | |
137 | /// struct Foo; | |
138 | /// | |
139 | /// let x = Foo; | |
140 | /// | |
141 | /// let y = x; | |
142 | /// | |
143 | /// // `x` has moved into `y`, and so cannot be used | |
144 | /// | |
145 | /// // println!("{:?}", x); // error: use of moved value | |
146 | /// ``` | |
147 | /// | |
148 | /// However, if a type implements `Copy`, it instead has 'copy semantics': | |
149 | /// | |
150 | /// ``` | |
9e0c209e SL |
151 | /// // We can derive a `Copy` implementation. `Clone` is also required, as it's |
152 | /// // a supertrait of `Copy`. | |
c34b1796 | 153 | /// #[derive(Debug, Copy, Clone)] |
85aaf69f SL |
154 | /// struct Foo; |
155 | /// | |
156 | /// let x = Foo; | |
157 | /// | |
158 | /// let y = x; | |
159 | /// | |
160 | /// // `y` is a copy of `x` | |
161 | /// | |
162 | /// println!("{:?}", x); // A-OK! | |
163 | /// ``` | |
164 | /// | |
9e0c209e SL |
165 | /// It's important to note that in these two examples, the only difference is whether you |
166 | /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move | |
167 | /// can result in bits being copied in memory, although this is sometimes optimized away. | |
168 | /// | |
169 | /// ## How can I implement `Copy`? | |
170 | /// | |
171 | /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`: | |
172 | /// | |
173 | /// ``` | |
174 | /// #[derive(Copy, Clone)] | |
175 | /// struct MyStruct; | |
176 | /// ``` | |
177 | /// | |
178 | /// You can also implement `Copy` and `Clone` manually: | |
179 | /// | |
180 | /// ``` | |
181 | /// struct MyStruct; | |
182 | /// | |
183 | /// impl Copy for MyStruct { } | |
184 | /// | |
185 | /// impl Clone for MyStruct { | |
186 | /// fn clone(&self) -> MyStruct { | |
187 | /// *self | |
188 | /// } | |
189 | /// } | |
190 | /// ``` | |
191 | /// | |
192 | /// There is a small difference between the two: the `derive` strategy will also place a `Copy` | |
193 | /// bound on type parameters, which isn't always desired. | |
194 | /// | |
195 | /// ## What's the difference between `Copy` and `Clone`? | |
196 | /// | |
197 | /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of | |
198 | /// `Copy` is not overloadable; it is always a simple bit-wise copy. | |
199 | /// | |
476ff2be | 200 | /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can |
9e0c209e | 201 | /// provide any type-specific behavior necessary to duplicate values safely. For example, |
476ff2be SL |
202 | /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string |
203 | /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the | |
204 | /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`] | |
9e0c209e SL |
205 | /// but not `Copy`. |
206 | /// | |
476ff2be | 207 | /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement |
041b39d2 | 208 | /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self` |
9e0c209e SL |
209 | /// (see the example above). |
210 | /// | |
85aaf69f SL |
211 | /// ## When can my type be `Copy`? |
212 | /// | |
213 | /// A type can implement `Copy` if all of its components implement `Copy`. For example, this | |
9e0c209e | 214 | /// struct can be `Copy`: |
85aaf69f SL |
215 | /// |
216 | /// ``` | |
92a42be0 | 217 | /// # #[allow(dead_code)] |
85aaf69f SL |
218 | /// struct Point { |
219 | /// x: i32, | |
220 | /// y: i32, | |
221 | /// } | |
222 | /// ``` | |
223 | /// | |
476ff2be | 224 | /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`. |
9e0c209e | 225 | /// By contrast, consider |
85aaf69f SL |
226 | /// |
227 | /// ``` | |
92a42be0 | 228 | /// # #![allow(dead_code)] |
85aaf69f SL |
229 | /// # struct Point; |
230 | /// struct PointList { | |
231 | /// points: Vec<Point>, | |
232 | /// } | |
233 | /// ``` | |
234 | /// | |
9e0c209e | 235 | /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we |
62682a34 | 236 | /// attempt to derive a `Copy` implementation, we'll get an error: |
85aaf69f SL |
237 | /// |
238 | /// ```text | |
62682a34 | 239 | /// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy` |
85aaf69f SL |
240 | /// ``` |
241 | /// | |
9e0c209e | 242 | /// ## When *can't* my type be `Copy`? |
3157f602 XL |
243 | /// |
244 | /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased | |
476ff2be SL |
245 | /// mutable reference. Copying [`String`] would duplicate responsibility for managing the |
246 | /// [`String`]'s buffer, leading to a double free. | |
3157f602 | 247 | /// |
9e0c209e | 248 | /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's |
cc61c64b | 249 | /// managing some resource besides its own [`size_of::<T>`] bytes. |
3157f602 | 250 | /// |
32a655c1 SL |
251 | /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get |
252 | /// the error [E0204]. | |
85aaf69f | 253 | /// |
c30ab7b3 | 254 | /// [E0204]: ../../error-index.html#E0204 |
85aaf69f | 255 | /// |
9e0c209e | 256 | /// ## When *should* my type be `Copy`? |
85aaf69f | 257 | /// |
9e0c209e SL |
258 | /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though, |
259 | /// that implementing `Copy` is part of the public API of your type. If the type might become | |
260 | /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to | |
261 | /// avoid a breaking API change. | |
85aaf69f | 262 | /// |
83c7162d XL |
263 | /// ## Additional implementors |
264 | /// | |
265 | /// In addition to the [implementors listed below][impls], | |
266 | /// the following types also implement `Copy`: | |
267 | /// | |
268 | /// * Function item types (i.e. the distinct types defined for each function) | |
269 | /// * Function pointer types (e.g. `fn() -> i32`) | |
270 | /// * Array types, for all sizes, if the item type also implements `Copy` (e.g. `[i32; 123456]`) | |
271 | /// * Tuple types, if each component also implements `Copy` (e.g. `()`, `(i32, bool)`) | |
272 | /// * Closure types, if they capture no value from the environment | |
273 | /// or if all such captured values implement `Copy` themselves. | |
274 | /// Note that variables captured by shared reference always implement `Copy` | |
275 | /// (even if the referent doesn't), | |
276 | /// while variables captured by mutable reference never implement `Copy`. | |
277 | /// | |
9e0c209e SL |
278 | /// [`Vec<T>`]: ../../std/vec/struct.Vec.html |
279 | /// [`String`]: ../../std/string/struct.String.html | |
280 | /// [`Drop`]: ../../std/ops/trait.Drop.html | |
cc61c64b | 281 | /// [`size_of::<T>`]: ../../std/mem/fn.size_of.html |
476ff2be SL |
282 | /// [`Clone`]: ../clone/trait.Clone.html |
283 | /// [`String`]: ../../std/string/struct.String.html | |
284 | /// [`i32`]: ../../std/primitive.i32.html | |
83c7162d | 285 | /// [impls]: #implementors |
85aaf69f | 286 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 287 | #[lang = "copy"] |
c34b1796 | 288 | pub trait Copy : Clone { |
1a4d82fc JJ |
289 | // Empty. |
290 | } | |
291 | ||
9e0c209e SL |
292 | /// Types for which it is safe to share references between threads. |
293 | /// | |
294 | /// This trait is automatically implemented when the compiler determines | |
295 | /// it's appropriate. | |
1a4d82fc | 296 | /// |
94b46f34 | 297 | /// The precise definition is: a type `T` is `Sync` if and only if `&T` is |
9e0c209e SL |
298 | /// [`Send`][send]. In other words, if there is no possibility of |
299 | /// [undefined behavior][ub] (including data races) when passing | |
300 | /// `&T` references between threads. | |
301 | /// | |
302 | /// As one would expect, primitive types like [`u8`][u8] and [`f64`][f64] | |
303 | /// are all `Sync`, and so are simple aggregate types containing them, | |
304 | /// like tuples, structs and enums. More examples of basic `Sync` | |
305 | /// types include "immutable" types like `&T`, and those with simple | |
306 | /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and | |
307 | /// most other collection types. (Generic parameters need to be `Sync` | |
308 | /// for their container to be `Sync`.) | |
309 | /// | |
310 | /// A somewhat surprising consequence of the definition is that `&mut T` | |
311 | /// is `Sync` (if `T` is `Sync`) even though it seems like that might | |
312 | /// provide unsynchronized mutation. The trick is that a mutable | |
313 | /// reference behind a shared reference (that is, `& &mut T`) | |
314 | /// becomes read-only, as if it were a `& &T`. Hence there is no risk | |
315 | /// of a data race. | |
1a4d82fc JJ |
316 | /// |
317 | /// Types that are not `Sync` are those that have "interior | |
9e0c209e SL |
318 | /// mutability" in a non-thread-safe form, such as [`cell::Cell`][cell] |
319 | /// and [`cell::RefCell`][refcell]. These types allow for mutation of | |
320 | /// their contents even through an immutable, shared reference. For | |
476ff2be SL |
321 | /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires |
322 | /// only a shared reference [`&Cell<T>`][cell]. The method performs no | |
323 | /// synchronization, thus [`Cell`][cell] cannot be `Sync`. | |
1a4d82fc | 324 | /// |
9e0c209e | 325 | /// Another example of a non-`Sync` type is the reference-counting |
476ff2be SL |
326 | /// pointer [`rc::Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone |
327 | /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way. | |
9cc50fc6 | 328 | /// |
9e0c209e SL |
329 | /// For cases when one does need thread-safe interior mutability, |
330 | /// Rust provides [atomic data types], as well as explicit locking via | |
ff7c6d11 | 331 | /// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types |
9e0c209e SL |
332 | /// ensure that any mutation cannot cause data races, hence the types |
333 | /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe | |
476ff2be | 334 | /// analogue of [`Rc`][rc]. |
9e0c209e SL |
335 | /// |
336 | /// Any types with interior mutability must also use the | |
337 | /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which | |
338 | /// can be mutated through a shared reference. Failing to doing this is | |
339 | /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing | |
340 | /// from `&T` to `&mut T` is invalid. | |
341 | /// | |
342 | /// See [the Nomicon](../../nomicon/send-and-sync.html) for more | |
343 | /// details about `Sync`. | |
344 | /// | |
345 | /// [send]: trait.Send.html | |
346 | /// [u8]: ../../std/primitive.u8.html | |
347 | /// [f64]: ../../std/primitive.f64.html | |
348 | /// [box]: ../../std/boxed/struct.Box.html | |
349 | /// [vec]: ../../std/vec/struct.Vec.html | |
350 | /// [cell]: ../cell/struct.Cell.html | |
351 | /// [refcell]: ../cell/struct.RefCell.html | |
352 | /// [rc]: ../../std/rc/struct.Rc.html | |
353 | /// [arc]: ../../std/sync/struct.Arc.html | |
354 | /// [atomic data types]: ../sync/atomic/index.html | |
355 | /// [mutex]: ../../std/sync/struct.Mutex.html | |
356 | /// [rwlock]: ../../std/sync/struct.RwLock.html | |
357 | /// [unsafecell]: ../cell/struct.UnsafeCell.html | |
8bb4bdeb | 358 | /// [ub]: ../../reference/behavior-considered-undefined.html |
9e0c209e | 359 | /// [transmute]: ../../std/mem/fn.transmute.html |
9346a6ac | 360 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 361 | #[lang = "sync"] |
0531ce1d XL |
362 | #[rustc_on_unimplemented( |
363 | message="`{Self}` cannot be shared between threads safely", | |
364 | label="`{Self}` cannot be shared between threads safely" | |
365 | )] | |
2c00a5a8 | 366 | pub unsafe auto trait Sync { |
0531ce1d XL |
367 | // FIXME(estebank): once support to add notes in `rustc_on_unimplemented` |
368 | // lands in beta, and it has been extended to check whether a closure is | |
369 | // anywhere in the requirement chain, extend it as such (#48534): | |
370 | // ``` | |
371 | // on( | |
372 | // closure, | |
373 | // note="`{Self}` cannot be shared safely, consider marking the closure `move`" | |
374 | // ), | |
375 | // ``` | |
376 | ||
9346a6ac AL |
377 | // Empty |
378 | } | |
379 | ||
92a42be0 SL |
380 | #[stable(feature = "rust1", since = "1.0.0")] |
381 | impl<T: ?Sized> !Sync for *const T { } | |
382 | #[stable(feature = "rust1", since = "1.0.0")] | |
383 | impl<T: ?Sized> !Sync for *mut T { } | |
c34b1796 | 384 | |
85aaf69f SL |
385 | macro_rules! impls{ |
386 | ($t: ident) => ( | |
92a42be0 | 387 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
388 | impl<T:?Sized> Hash for $t<T> { |
389 | #[inline] | |
390 | fn hash<H: Hasher>(&self, _: &mut H) { | |
391 | } | |
392 | } | |
393 | ||
92a42be0 | 394 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
395 | impl<T:?Sized> cmp::PartialEq for $t<T> { |
396 | fn eq(&self, _other: &$t<T>) -> bool { | |
397 | true | |
398 | } | |
399 | } | |
400 | ||
92a42be0 | 401 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
402 | impl<T:?Sized> cmp::Eq for $t<T> { |
403 | } | |
404 | ||
92a42be0 | 405 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
406 | impl<T:?Sized> cmp::PartialOrd for $t<T> { |
407 | fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> { | |
408 | Option::Some(cmp::Ordering::Equal) | |
409 | } | |
410 | } | |
411 | ||
92a42be0 | 412 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
413 | impl<T:?Sized> cmp::Ord for $t<T> { |
414 | fn cmp(&self, _other: &$t<T>) -> cmp::Ordering { | |
415 | cmp::Ordering::Equal | |
416 | } | |
417 | } | |
418 | ||
92a42be0 | 419 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
420 | impl<T:?Sized> Copy for $t<T> { } |
421 | ||
92a42be0 | 422 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
423 | impl<T:?Sized> Clone for $t<T> { |
424 | fn clone(&self) -> $t<T> { | |
425 | $t | |
426 | } | |
427 | } | |
92a42be0 SL |
428 | |
429 | #[stable(feature = "rust1", since = "1.0.0")] | |
430 | impl<T:?Sized> Default for $t<T> { | |
431 | fn default() -> $t<T> { | |
432 | $t | |
433 | } | |
434 | } | |
85aaf69f SL |
435 | ) |
436 | } | |
437 | ||
9e0c209e | 438 | /// Zero-sized type used to mark things that "act like" they own a `T`. |
9346a6ac | 439 | /// |
9e0c209e SL |
440 | /// Adding a `PhantomData<T>` field to your type tells the compiler that your |
441 | /// type acts as though it stores a value of type `T`, even though it doesn't | |
442 | /// really. This information is used when computing certain safety properties. | |
9cc50fc6 | 443 | /// |
9e0c209e SL |
444 | /// For a more in-depth explanation of how to use `PhantomData<T>`, please see |
445 | /// [the Nomicon](../../nomicon/phantom-data.html). | |
9cc50fc6 | 446 | /// |
e9174d1e SL |
447 | /// # A ghastly note 👻👻👻 |
448 | /// | |
9e0c209e SL |
449 | /// Though they both have scary names, `PhantomData` and 'phantom types' are |
450 | /// related, but not identical. A phantom type parameter is simply a type | |
451 | /// parameter which is never used. In Rust, this often causes the compiler to | |
452 | /// complain, and the solution is to add a "dummy" use by way of `PhantomData`. | |
1a4d82fc | 453 | /// |
c34b1796 | 454 | /// # Examples |
1a4d82fc | 455 | /// |
9e0c209e | 456 | /// ## Unused lifetime parameters |
1a4d82fc | 457 | /// |
9e0c209e SL |
458 | /// Perhaps the most common use case for `PhantomData` is a struct that has an |
459 | /// unused lifetime parameter, typically as part of some unsafe code. For | |
460 | /// example, here is a struct `Slice` that has two pointers of type `*const T`, | |
461 | /// presumably pointing into an array somewhere: | |
85aaf69f | 462 | /// |
041b39d2 | 463 | /// ```compile_fail,E0392 |
9346a6ac AL |
464 | /// struct Slice<'a, T> { |
465 | /// start: *const T, | |
466 | /// end: *const T, | |
1a4d82fc JJ |
467 | /// } |
468 | /// ``` | |
469 | /// | |
9346a6ac AL |
470 | /// The intention is that the underlying data is only valid for the |
471 | /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this | |
472 | /// intent is not expressed in the code, since there are no uses of | |
473 | /// the lifetime `'a` and hence it is not clear what data it applies | |
474 | /// to. We can correct this by telling the compiler to act *as if* the | |
9e0c209e | 475 | /// `Slice` struct contained a reference `&'a T`: |
1a4d82fc | 476 | /// |
c34b1796 | 477 | /// ``` |
9346a6ac | 478 | /// use std::marker::PhantomData; |
1a4d82fc | 479 | /// |
92a42be0 | 480 | /// # #[allow(dead_code)] |
9cc50fc6 | 481 | /// struct Slice<'a, T: 'a> { |
9346a6ac AL |
482 | /// start: *const T, |
483 | /// end: *const T, | |
9e0c209e | 484 | /// phantom: PhantomData<&'a T>, |
9346a6ac | 485 | /// } |
c34b1796 | 486 | /// ``` |
1a4d82fc | 487 | /// |
9e0c209e SL |
488 | /// This also in turn requires the annotation `T: 'a`, indicating |
489 | /// that any references in `T` are valid over the lifetime `'a`. | |
490 | /// | |
491 | /// When initializing a `Slice` you simply provide the value | |
492 | /// `PhantomData` for the field `phantom`: | |
493 | /// | |
494 | /// ``` | |
495 | /// # #![allow(dead_code)] | |
496 | /// # use std::marker::PhantomData; | |
497 | /// # struct Slice<'a, T: 'a> { | |
498 | /// # start: *const T, | |
499 | /// # end: *const T, | |
500 | /// # phantom: PhantomData<&'a T>, | |
501 | /// # } | |
502 | /// fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> { | |
503 | /// let ptr = vec.as_ptr(); | |
504 | /// Slice { | |
505 | /// start: ptr, | |
506 | /// end: unsafe { ptr.offset(vec.len() as isize) }, | |
507 | /// phantom: PhantomData, | |
508 | /// } | |
509 | /// } | |
510 | /// ``` | |
1a4d82fc | 511 | /// |
9346a6ac | 512 | /// ## Unused type parameters |
1a4d82fc | 513 | /// |
9e0c209e | 514 | /// It sometimes happens that you have unused type parameters which |
9346a6ac AL |
515 | /// indicate what type of data a struct is "tied" to, even though that |
516 | /// data is not actually found in the struct itself. Here is an | |
9e0c209e SL |
517 | /// example where this arises with [FFI]. The foreign interface uses |
518 | /// handles of type `*mut ()` to refer to Rust values of different | |
519 | /// types. We track the Rust type using a phantom type parameter on | |
520 | /// the struct `ExternalResource` which wraps a handle. | |
521 | /// | |
041b39d2 | 522 | /// [FFI]: ../../book/first-edition/ffi.html |
c34b1796 AL |
523 | /// |
524 | /// ``` | |
92a42be0 | 525 | /// # #![allow(dead_code)] |
9e0c209e | 526 | /// # trait ResType { } |
c34b1796 AL |
527 | /// # struct ParamType; |
528 | /// # mod foreign_lib { | |
9e0c209e SL |
529 | /// # pub fn new(_: usize) -> *mut () { 42 as *mut () } |
530 | /// # pub fn do_stuff(_: *mut (), _: usize) {} | |
c34b1796 AL |
531 | /// # } |
532 | /// # fn convert_params(_: ParamType) -> usize { 42 } | |
533 | /// use std::marker::PhantomData; | |
534 | /// use std::mem; | |
535 | /// | |
536 | /// struct ExternalResource<R> { | |
537 | /// resource_handle: *mut (), | |
538 | /// resource_type: PhantomData<R>, | |
539 | /// } | |
540 | /// | |
541 | /// impl<R: ResType> ExternalResource<R> { | |
542 | /// fn new() -> ExternalResource<R> { | |
543 | /// let size_of_res = mem::size_of::<R>(); | |
544 | /// ExternalResource { | |
545 | /// resource_handle: foreign_lib::new(size_of_res), | |
546 | /// resource_type: PhantomData, | |
547 | /// } | |
548 | /// } | |
549 | /// | |
550 | /// fn do_stuff(&self, param: ParamType) { | |
551 | /// let foreign_params = convert_params(param); | |
552 | /// foreign_lib::do_stuff(self.resource_handle, foreign_params); | |
553 | /// } | |
554 | /// } | |
555 | /// ``` | |
556 | /// | |
9e0c209e | 557 | /// ## Ownership and the drop check |
9346a6ac | 558 | /// |
9e0c209e SL |
559 | /// Adding a field of type `PhantomData<T>` indicates that your |
560 | /// type owns data of type `T`. This in turn implies that when your | |
561 | /// type is dropped, it may drop one or more instances of the type | |
562 | /// `T`. This has bearing on the Rust compiler's [drop check] | |
563 | /// analysis. | |
9346a6ac AL |
564 | /// |
565 | /// If your struct does not in fact *own* the data of type `T`, it is | |
566 | /// better to use a reference type, like `PhantomData<&'a T>` | |
567 | /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so | |
568 | /// as not to indicate ownership. | |
9e0c209e SL |
569 | /// |
570 | /// [drop check]: ../../nomicon/dropck.html | |
d9579d0f | 571 | #[lang = "phantom_data"] |
85aaf69f SL |
572 | #[stable(feature = "rust1", since = "1.0.0")] |
573 | pub struct PhantomData<T:?Sized>; | |
1a4d82fc | 574 | |
85aaf69f | 575 | impls! { PhantomData } |
1a4d82fc | 576 | |
85aaf69f | 577 | mod impls { |
92a42be0 | 578 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 579 | unsafe impl<'a, T: Sync + ?Sized> Send for &'a T {} |
92a42be0 | 580 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
581 | unsafe impl<'a, T: Send + ?Sized> Send for &'a mut T {} |
582 | } | |
cc61c64b XL |
583 | |
584 | /// Compiler-internal trait used to determine whether a type contains | |
585 | /// any `UnsafeCell` internally, but not through an indirection. | |
586 | /// This affects, for example, whether a `static` of that type is | |
587 | /// placed in read-only static memory or writable static memory. | |
7cac9316 | 588 | #[lang = "freeze"] |
2c00a5a8 | 589 | unsafe auto trait Freeze {} |
cc61c64b XL |
590 | |
591 | impl<T: ?Sized> !Freeze for UnsafeCell<T> {} | |
592 | unsafe impl<T: ?Sized> Freeze for PhantomData<T> {} | |
593 | unsafe impl<T: ?Sized> Freeze for *const T {} | |
594 | unsafe impl<T: ?Sized> Freeze for *mut T {} | |
595 | unsafe impl<'a, T: ?Sized> Freeze for &'a T {} | |
596 | unsafe impl<'a, T: ?Sized> Freeze for &'a mut T {} | |
0531ce1d | 597 | |
94b46f34 | 598 | /// Types which can be moved out of a `PinMut`. |
0531ce1d | 599 | /// |
94b46f34 | 600 | /// The `Unpin` trait is used to control the behavior of the [`PinMut`] type. If a |
0531ce1d | 601 | /// type implements `Unpin`, it is safe to move a value of that type out of the |
94b46f34 | 602 | /// `PinMut` pointer. |
0531ce1d XL |
603 | /// |
604 | /// This trait is automatically implemented for almost every type. | |
83c7162d | 605 | /// |
94b46f34 | 606 | /// [`PinMut`]: ../mem/struct.PinMut.html |
0531ce1d | 607 | #[unstable(feature = "pin", issue = "49150")] |
94b46f34 XL |
608 | pub auto trait Unpin {} |
609 | ||
610 | /// A type which does not implement `Unpin`. | |
611 | /// | |
612 | /// If a type contains a `Pinned`, it will not implement `Unpin` by default. | |
613 | #[unstable(feature = "pin", issue = "49150")] | |
614 | #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] | |
615 | pub struct Pinned; | |
616 | ||
617 | #[unstable(feature = "pin", issue = "49150")] | |
618 | impl !Unpin for Pinned {} | |
83c7162d XL |
619 | |
620 | /// Implementations of `Copy` for primitive types. | |
621 | /// | |
622 | /// Implementations that cannot be described in Rust | |
623 | /// are implemented in `SelectionContext::copy_clone_conditions()` in librustc. | |
83c7162d XL |
624 | mod copy_impls { |
625 | ||
626 | use super::Copy; | |
627 | ||
628 | macro_rules! impl_copy { | |
629 | ($($t:ty)*) => { | |
630 | $( | |
631 | #[stable(feature = "rust1", since = "1.0.0")] | |
632 | impl Copy for $t {} | |
633 | )* | |
634 | } | |
635 | } | |
636 | ||
637 | impl_copy! { | |
638 | usize u8 u16 u32 u64 u128 | |
639 | isize i8 i16 i32 i64 i128 | |
640 | f32 f64 | |
641 | bool char | |
642 | } | |
643 | ||
644 | #[unstable(feature = "never_type", issue = "35121")] | |
645 | impl Copy for ! {} | |
646 | ||
647 | #[stable(feature = "rust1", since = "1.0.0")] | |
648 | impl<T: ?Sized> Copy for *const T {} | |
649 | ||
650 | #[stable(feature = "rust1", since = "1.0.0")] | |
651 | impl<T: ?Sized> Copy for *mut T {} | |
652 | ||
653 | // Shared references can be copied, but mutable references *cannot*! | |
654 | #[stable(feature = "rust1", since = "1.0.0")] | |
655 | impl<'a, T: ?Sized> Copy for &'a T {} | |
656 | ||
657 | } |