]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
doc: remove incomplete sentence
[rust.git] / src / libcore / any.rs
1 // Copyright 2013-2014 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 //! Traits for dynamic typing of any `'static` type (through runtime reflection)
12 //!
13 //! This module implements the `Any` trait, which enables dynamic typing
14 //! of any `'static` type through runtime reflection.
15 //!
16 //! `Any` itself can be used to get a `TypeId`, and has more features when used
17 //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
18 //! `as_ref` methods, to test if the contained value is of a given type, and to
19 //! get a reference to the inner value as a type. As`&mut Any`, there is also
20 //! the `as_mut` method, for getting a mutable reference to the inner value.
21 //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the
22 //! object.  See the extension traits (`*Ext`) for the full details.
23 //!
24 //! Note that &Any is limited to testing whether a value is of a specified
25 //! concrete type, and cannot be used to test whether a type implements a trait.
26 //!
27 //! # Examples
28 //!
29 //! Consider a situation where we want to log out a value passed to a function.
30 //! We know the value we're working on implements Show, but we don't know its
31 //! concrete type.  We want to give special treatment to certain types: in this
32 //! case printing out the length of String values prior to their value.
33 //! We don't know the concrete type of our value at compile time, so we need to
34 //! use runtime reflection instead.
35 //!
36 //! ```rust
37 //! use std::fmt::Show;
38 //! use std::any::{Any, AnyRefExt};
39 //!
40 //! // Logger function for any type that implements Show.
41 //! fn log<T: Any+Show>(value: &T) {
42 //!     let value_any = value as &Any;
43 //!
44 //!     // try to convert our value to a String.  If successful, we want to
45 //!     // output the String's length as well as its value.  If not, it's a
46 //!     // different type: just print it out unadorned.
47 //!     match value_any.downcast_ref::<String>() {
48 //!         Some(as_string) => {
49 //!             println!("String ({}): {}", as_string.len(), as_string);
50 //!         }
51 //!         None => {
52 //!             println!("{}", value);
53 //!         }
54 //!     }
55 //! }
56 //!
57 //! // This function wants to log its parameter out prior to doing work with it.
58 //! fn do_work<T: Show+'static>(value: &T) {
59 //!     log(value);
60 //!     // ...do some other work
61 //! }
62 //!
63 //! fn main() {
64 //!     let my_string = "Hello World".to_string();
65 //!     do_work(&my_string);
66 //!
67 //!     let my_i8: i8 = 100;
68 //!     do_work(&my_i8);
69 //! }
70 //! ```
71
72 #![stable]
73
74 use mem::{transmute};
75 use option::Option;
76 use option::Option::{Some, None};
77 use raw::TraitObject;
78 use intrinsics::TypeId;
79
80 ///////////////////////////////////////////////////////////////////////////////
81 // Any trait
82 ///////////////////////////////////////////////////////////////////////////////
83
84 /// The `Any` trait is implemented by all `'static` types, and can be used for
85 /// dynamic typing
86 ///
87 /// Every type with no non-`'static` references implements `Any`, so `Any` can
88 /// be used as a trait object to emulate the effects dynamic typing.
89 #[stable]
90 pub trait Any: 'static {
91     /// Get the `TypeId` of `self`
92     #[experimental = "this method will likely be replaced by an associated static"]
93     fn get_type_id(&self) -> TypeId;
94 }
95
96 impl<T: 'static> Any for T {
97     fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
98 }
99
100 ///////////////////////////////////////////////////////////////////////////////
101 // Extension methods for Any trait objects.
102 // Implemented as three extension traits so that the methods can be generic.
103 ///////////////////////////////////////////////////////////////////////////////
104
105 /// Extension methods for a referenced `Any` trait object
106 #[unstable = "this trait will not be necessary once DST lands, it will be a \
107               part of `impl Any`"]
108 pub trait AnyRefExt<'a> {
109     /// Returns true if the boxed type is the same as `T`
110     #[stable]
111     fn is<T: 'static>(self) -> bool;
112
113     /// Returns some reference to the boxed value if it is of type `T`, or
114     /// `None` if it isn't.
115     #[unstable = "naming conventions around acquiring references may change"]
116     fn downcast_ref<T: 'static>(self) -> Option<&'a T>;
117 }
118
119 #[stable]
120 impl<'a> AnyRefExt<'a> for &'a Any {
121     #[inline]
122     fn is<T: 'static>(self) -> bool {
123         // Get TypeId of the type this function is instantiated with
124         let t = TypeId::of::<T>();
125
126         // Get TypeId of the type in the trait object
127         let boxed = self.get_type_id();
128
129         // Compare both TypeIds on equality
130         t == boxed
131     }
132
133     #[inline]
134     fn downcast_ref<T: 'static>(self) -> Option<&'a T> {
135         if self.is::<T>() {
136             unsafe {
137                 // Get the raw representation of the trait object
138                 let to: TraitObject = transmute(self);
139
140                 // Extract the data pointer
141                 Some(transmute(to.data))
142             }
143         } else {
144             None
145         }
146     }
147 }
148
149 /// Extension methods for a mutable referenced `Any` trait object
150 #[unstable = "this trait will not be necessary once DST lands, it will be a \
151               part of `impl Any`"]
152 pub trait AnyMutRefExt<'a> {
153     /// Returns some mutable reference to the boxed value if it is of type `T`, or
154     /// `None` if it isn't.
155     #[unstable = "naming conventions around acquiring references may change"]
156     fn downcast_mut<T: 'static>(self) -> Option<&'a mut T>;
157 }
158
159 #[stable]
160 impl<'a> AnyMutRefExt<'a> for &'a mut Any {
161     #[inline]
162     fn downcast_mut<T: 'static>(self) -> Option<&'a mut T> {
163         if self.is::<T>() {
164             unsafe {
165                 // Get the raw representation of the trait object
166                 let to: TraitObject = transmute(self);
167
168                 // Extract the data pointer
169                 Some(transmute(to.data))
170             }
171         } else {
172             None
173         }
174     }
175 }