]> git.lizzy.rs Git - rust.git/blob - src/libcore/kinds.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / libcore / kinds.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Primitive traits representing basic 'kinds' of types
12 //!
13 //! Rust types can be classified in various useful ways according to
14 //! intrinsic properties of the type. These classifications, often called
15 //! 'kinds', are represented as traits.
16 //!
17 //! They cannot be implemented by user code, but are instead implemented
18 //! by the compiler automatically for the types to which they apply.
19
20 /// Types able to be transferred across task boundaries.
21 #[lang="send"]
22 pub trait Send for Sized? {
23     // empty.
24 }
25
26 /// Types with a constant size known at compile-time.
27 #[lang="sized"]
28 pub trait Sized for Sized? {
29     // Empty.
30 }
31
32 /// Types that can be copied by simply copying bits (i.e. `memcpy`).
33 #[lang="copy"]
34 pub trait Copy for Sized? {
35     // Empty.
36 }
37
38 /// Types that can be safely shared between tasks when aliased.
39 ///
40 /// The precise definition is: a type `T` is `Sync` if `&T` is
41 /// thread-safe. In other words, there is no possibility of data races
42 /// when passing `&T` references between tasks.
43 ///
44 /// As one would expect, primitive types like `u8` and `f64` are all
45 /// `Sync`, and so are simple aggregate types containing them (like
46 /// tuples, structs and enums). More instances of basic `Sync` types
47 /// include "immutable" types like `&T` and those with simple
48 /// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
49 /// collection types. (Generic parameters need to be `Sync` for their
50 /// container to be `Sync`.)
51 ///
52 /// A somewhat surprising consequence of the definition is `&mut T` is
53 /// `Sync` (if `T` is `Sync`) even though it seems that it might
54 /// provide unsynchronised mutation. The trick is a mutable reference
55 /// stored in an aliasable reference (that is, `& &mut T`) becomes
56 /// read-only, as if it were a `& &T`, hence there is no risk of a data
57 /// race.
58 ///
59 /// Types that are not `Sync` are those that have "interior
60 /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
61 /// in `std::cell`. These types allow for mutation of their contents
62 /// even when in an immutable, aliasable slot, e.g. the contents of
63 /// `&Cell<T>` can be `.set`, and do not ensure data races are
64 /// impossible, hence they cannot be `Sync`. A higher level example
65 /// of a non-`Sync` type is the reference counted pointer
66 /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
67 /// reference, which modifies the reference counts in a non-atomic
68 /// way.
69 ///
70 /// For cases when one does need thread-safe interior mutability,
71 /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
72 /// the `sync` crate do ensure that any mutation cannot cause data
73 /// races.  Hence these types are `Sync`.
74 ///
75 /// Users writing their own types with interior mutability (or anything
76 /// else that is not thread-safe) should use the `NoSync` marker type
77 /// (from `std::kinds::marker`) to ensure that the compiler doesn't
78 /// consider the user-defined type to be `Sync`.  Any types with
79 /// interior mutability must also use the `std::cell::UnsafeCell` wrapper
80 /// around the value(s) which can be mutated when behind a `&`
81 /// reference; not doing this is undefined behaviour (for example,
82 /// `transmute`-ing from `&T` to `&mut T` is illegal).
83 #[lang="sync"]
84 pub trait Sync for Sized? {
85     // Empty
86 }
87
88 /// Marker types are special types that are used with unsafe code to
89 /// inform the compiler of special constraints. Marker types should
90 /// only be needed when you are creating an abstraction that is
91 /// implemented using unsafe code. In that case, you may want to embed
92 /// some of the marker types below into your type.
93 pub mod marker {
94     /// A marker type whose type parameter `T` is considered to be
95     /// covariant with respect to the type itself. This is (typically)
96     /// used to indicate that an instance of the type `T` is being stored
97     /// into memory and read from, even though that may not be apparent.
98     ///
99     /// For more information about variance, refer to this Wikipedia
100     /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
101     ///
102     /// *Note:* It is very unusual to have to add a covariant constraint.
103     /// If you are not sure, you probably want to use `InvariantType`.
104     ///
105     /// # Example
106     ///
107     /// Given a struct `S` that includes a type parameter `T`
108     /// but does not actually *reference* that type parameter:
109     ///
110     /// ```ignore
111     /// use std::mem;
112     ///
113     /// struct S<T> { x: *() }
114     /// fn get<T>(s: &S<T>) -> T {
115     ///    unsafe {
116     ///        let x: *T = mem::transmute(s.x);
117     ///        *x
118     ///    }
119     /// }
120     /// ```
121     ///
122     /// The type system would currently infer that the value of
123     /// the type parameter `T` is irrelevant, and hence a `S<int>` is
124     /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
125     /// any `U`). But this is incorrect because `get()` converts the
126     /// `*()` into a `*T` and reads from it. Therefore, we should include the
127     /// a marker field `CovariantType<T>` to inform the type checker that
128     /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
129     /// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
130     /// for some lifetime `'a`, but not the other way around).
131     #[lang="covariant_type"]
132     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
133     pub struct CovariantType<T>;
134
135     /// A marker type whose type parameter `T` is considered to be
136     /// contravariant with respect to the type itself. This is (typically)
137     /// used to indicate that an instance of the type `T` will be consumed
138     /// (but not read from), even though that may not be apparent.
139     ///
140     /// For more information about variance, refer to this Wikipedia
141     /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
142     ///
143     /// *Note:* It is very unusual to have to add a contravariant constraint.
144     /// If you are not sure, you probably want to use `InvariantType`.
145     ///
146     /// # Example
147     ///
148     /// Given a struct `S` that includes a type parameter `T`
149     /// but does not actually *reference* that type parameter:
150     ///
151     /// ```
152     /// use std::mem;
153     ///
154     /// struct S<T> { x: *const () }
155     /// fn get<T>(s: &S<T>, v: T) {
156     ///    unsafe {
157     ///        let x: fn(T) = mem::transmute(s.x);
158     ///        x(v)
159     ///    }
160     /// }
161     /// ```
162     ///
163     /// The type system would currently infer that the value of
164     /// the type parameter `T` is irrelevant, and hence a `S<int>` is
165     /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
166     /// any `U`). But this is incorrect because `get()` converts the
167     /// `*()` into a `fn(T)` and then passes a value of type `T` to it.
168     ///
169     /// Supplying a `ContravariantType` marker would correct the
170     /// problem, because it would mark `S` so that `S<T>` is only a
171     /// subtype of `S<U>` if `U` is a subtype of `T`; given that the
172     /// function requires arguments of type `T`, it must also accept
173     /// arguments of type `U`, hence such a conversion is safe.
174     #[lang="contravariant_type"]
175     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
176     pub struct ContravariantType<T>;
177
178     /// A marker type whose type parameter `T` is considered to be
179     /// invariant with respect to the type itself. This is (typically)
180     /// used to indicate that instances of the type `T` may be read or
181     /// written, even though that may not be apparent.
182     ///
183     /// For more information about variance, refer to this Wikipedia
184     /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
185     ///
186     /// # Example
187     ///
188     /// The Cell type is an example which uses unsafe code to achieve
189     /// "interior" mutability:
190     ///
191     /// ```
192     /// pub struct Cell<T> { value: T }
193     /// # fn main() {}
194     /// ```
195     ///
196     /// The type system would infer that `value` is only read here and
197     /// never written, but in fact `Cell` uses unsafe code to achieve
198     /// interior mutability.
199     #[lang="invariant_type"]
200     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
201     pub struct InvariantType<T>;
202
203     /// As `CovariantType`, but for lifetime parameters. Using
204     /// `CovariantLifetime<'a>` indicates that it is ok to substitute
205     /// a *longer* lifetime for `'a` than the one you originally
206     /// started with (e.g., you could convert any lifetime `'foo` to
207     /// `'static`). You almost certainly want `ContravariantLifetime`
208     /// instead, or possibly `InvariantLifetime`. The only case where
209     /// it would be appropriate is that you have a (type-casted, and
210     /// hence hidden from the type system) function pointer with a
211     /// signature like `fn(&'a T)` (and no other uses of `'a`). In
212     /// this case, it is ok to substitute a larger lifetime for `'a`
213     /// (e.g., `fn(&'static T)`), because the function is only
214     /// becoming more selective in terms of what it accepts as
215     /// argument.
216     ///
217     /// For more information about variance, refer to this Wikipedia
218     /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
219     #[lang="covariant_lifetime"]
220     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
221     pub struct CovariantLifetime<'a>;
222
223     /// As `ContravariantType`, but for lifetime parameters. Using
224     /// `ContravariantLifetime<'a>` indicates that it is ok to
225     /// substitute a *shorter* lifetime for `'a` than the one you
226     /// originally started with (e.g., you could convert `'static` to
227     /// any lifetime `'foo`). This is appropriate for cases where you
228     /// have an unsafe pointer that is actually a pointer into some
229     /// memory with lifetime `'a`, and thus you want to limit the
230     /// lifetime of your data structure to `'a`. An example of where
231     /// this is used is the iterator for vectors.
232     ///
233     /// For more information about variance, refer to this Wikipedia
234     /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
235     #[lang="contravariant_lifetime"]
236     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
237     pub struct ContravariantLifetime<'a>;
238
239     /// As `InvariantType`, but for lifetime parameters. Using
240     /// `InvariantLifetime<'a>` indicates that it is not ok to
241     /// substitute any other lifetime for `'a` besides its original
242     /// value. This is appropriate for cases where you have an unsafe
243     /// pointer that is actually a pointer into memory with lifetime `'a`,
244     /// and this pointer is itself stored in an inherently mutable
245     /// location (such as a `Cell`).
246     #[lang="invariant_lifetime"]
247     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
248     pub struct InvariantLifetime<'a>;
249
250     /// A type which is considered "not sendable", meaning that it cannot
251     /// be safely sent between tasks, even if it is owned. This is
252     /// typically embedded in other types, such as `Gc`, to ensure that
253     /// their instances remain thread-local.
254     #[lang="no_send_bound"]
255     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
256     pub struct NoSend;
257
258     /// A type which is considered "not POD", meaning that it is not
259     /// implicitly copyable. This is typically embedded in other types to
260     /// ensure that they are never copied, even if they lack a destructor.
261     #[lang="no_copy_bound"]
262     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
263     pub struct NoCopy;
264
265     /// A type which is considered "not sync", meaning that
266     /// its contents are not threadsafe, hence they cannot be
267     /// shared between tasks.
268     #[lang="no_sync_bound"]
269     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
270     pub struct NoSync;
271
272     /// A type which is considered managed by the GC. This is typically
273     /// embedded in other types.
274     #[lang="managed_bound"]
275     #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
276     pub struct Managed;
277 }