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