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