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