1 // Copyright 2013 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.
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.
11 //! This module implements the `Any` trait, which enables dynamic typing
12 //! of any type, through runtime reflection.
14 //! `Any` itself can be used to get a `TypeId`, and has more features when used as a trait object.
15 //! As `&Any` (a borrowed trait object), it has the `is` and `as_ref` methods, to test if the
16 //! contained value is of a given type, and to get a reference to the inner value as a type. As
17 //! `&mut Any`, there is also the `as_mut` method, for getting a mutable reference to the inner
18 //! value. `~Any` adds the `move` method, which will unwrap a `~T` from the object. See the
19 //! extension traits (`*Ext`) for the full details.
22 use option::{Option, Some, None};
24 use unstable::intrinsics;
26 use unstable::intrinsics::TypeId;
28 ///////////////////////////////////////////////////////////////////////////////
30 ///////////////////////////////////////////////////////////////////////////////
32 /// The `Any` trait is implemented by all types, and can be used as a trait object
33 /// for dynamic typing
35 /// Get the `TypeId` of `self`
36 fn get_type_id(&self) -> TypeId;
38 /// Get a void pointer to `self`
39 fn as_void_ptr(&self) -> *Void;
41 /// Get a mutable void pointer to `self`
42 fn as_mut_void_ptr(&mut self) -> *mut Void;
45 impl<T: 'static> Any for T {
46 /// Get the `TypeId` of `self`
47 fn get_type_id(&self) -> TypeId {
51 /// Get a void pointer to `self`
52 fn as_void_ptr(&self) -> *Void {
56 /// Get a mutable void pointer to `self`
57 fn as_mut_void_ptr(&mut self) -> *mut Void {
58 self as *mut T as *mut Void
62 ///////////////////////////////////////////////////////////////////////////////
63 // Extension methods for Any trait objects.
64 // Implemented as three extension traits so that generics work.
65 ///////////////////////////////////////////////////////////////////////////////
67 /// Extension methods for a referenced `Any` trait object
68 pub trait AnyRefExt<'a> {
69 /// Returns true if the boxed type is the same as `T`
70 fn is<T: 'static>(self) -> bool;
72 /// Returns some reference to the boxed value if it is of type `T`, or
73 /// `None` if it isn't.
74 fn as_ref<T: 'static>(self) -> Option<&'a T>;
77 impl<'a> AnyRefExt<'a> for &'a Any {
79 fn is<T: 'static>(self) -> bool {
80 // Get TypeId of the type this function is instantiated with
81 let t = TypeId::of::<T>();
83 // Get TypeId of the type in the trait object
84 let boxed = self.get_type_id();
86 // Compare both TypeIds on equality
91 fn as_ref<T: 'static>(self) -> Option<&'a T> {
93 Some(unsafe { transmute(self.as_void_ptr()) })
100 /// Extension methods for a mutable referenced `Any` trait object
101 pub trait AnyMutRefExt<'a> {
102 /// Returns some mutable reference to the boxed value if it is of type `T`, or
103 /// `None` if it isn't.
104 fn as_mut<T: 'static>(self) -> Option<&'a mut T>;
107 impl<'a> AnyMutRefExt<'a> for &'a mut Any {
109 fn as_mut<T: 'static>(self) -> Option<&'a mut T> {
111 Some(unsafe { transmute(self.as_mut_void_ptr()) })
118 /// Extension methods for a owning `Any` trait object
119 pub trait AnyOwnExt {
120 /// Returns the boxed value if it is of type `T`, or
121 /// `None` if it isn't.
122 fn move<T: 'static>(self) -> Option<~T>;
125 impl AnyOwnExt for ~Any {
127 fn move<T: 'static>(self) -> Option<~T> {
130 // Extract the pointer to the boxed value, temporary alias with self
131 let ptr: ~T = transmute(self.as_void_ptr());
133 // Prevent destructor on self being run
134 intrinsics::forget(self);
144 ///////////////////////////////////////////////////////////////////////////////
145 // Trait implementations
146 ///////////////////////////////////////////////////////////////////////////////
148 impl ToStr for ~Any {
149 fn to_str(&self) -> ~str { ~"~Any" }
152 impl<'a> ToStr for &'a Any {
153 fn to_str(&self) -> ~str { ~"&Any" }
159 use super::AnyRefExt;
160 use option::{Some, None};
165 static TEST: &'static str = "Test";
168 fn any_as_void_ptr() {
169 let (a, b, c) = (~5u as ~Any, ~TEST as ~Any, ~Test as ~Any);
174 assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
175 assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
176 assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
178 let (a, b, c) = (@5u as @Any, @TEST as @Any, @Test as @Any);
183 assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
184 assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
185 assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
187 let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
192 assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
193 assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
194 assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
197 let mut y: &'static str = "Test";
198 let (a, b, c) = (&mut 5u as &mut Any,
205 assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
206 assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
207 assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
209 let (a, b, c) = (5u, "hello", Test);
210 let (a_r, b_r, c_r) = (&a as &Any, &b as &Any, &c as &Any);
212 assert_eq!(a.as_void_ptr(), a_r.as_void_ptr());
213 assert_eq!(b.as_void_ptr(), b_r.as_void_ptr());
214 assert_eq!(c.as_void_ptr(), c_r.as_void_ptr());
218 fn any_as_mut_void_ptr() {
219 let y: &'static str = "Test";
220 let mut a = ~5u as ~Any;
221 let mut b = ~y as ~Any;
222 let mut c = ~Test as ~Any;
224 let a_ptr = a.as_mut_void_ptr();
225 let b_ptr = b.as_mut_void_ptr();
226 let c_ptr = c.as_mut_void_ptr();
228 let a_r: &mut Any = a;
229 let b_r: &mut Any = b;
230 let c_r: &mut Any = c;
232 assert_eq!(a_ptr, a_r.as_mut_void_ptr());
233 assert_eq!(b_ptr, b_r.as_mut_void_ptr());
234 assert_eq!(c_ptr, c_r.as_mut_void_ptr());
237 let mut y: &'static str = "Test";
238 let a = &mut 5u as &mut Any;
239 let b = &mut y as &mut Any;
240 let c = &mut x as &mut Any;
242 let a_ptr = a.as_mut_void_ptr();
243 let b_ptr = b.as_mut_void_ptr();
244 let c_ptr = c.as_mut_void_ptr();
246 let a_r: &mut Any = a;
247 let b_r: &mut Any = b;
248 let c_r: &mut Any = c;
250 assert_eq!(a_ptr, a_r.as_mut_void_ptr());
251 assert_eq!(b_ptr, b_r.as_mut_void_ptr());
252 assert_eq!(c_ptr, c_r.as_mut_void_ptr());
254 let y: &'static str = "Test";
259 let a_ptr = a.as_mut_void_ptr();
260 let b_ptr = b.as_mut_void_ptr();
261 let c_ptr = c.as_mut_void_ptr();
263 let (a_r, b_r, c_r) = (&mut a as &mut Any, &mut b as &mut Any, &mut c as &mut Any);
265 assert_eq!(a_ptr, a_r.as_mut_void_ptr());
266 assert_eq!(b_ptr, b_r.as_mut_void_ptr());
267 assert_eq!(c_ptr, c_r.as_mut_void_ptr());
271 fn any_referenced() {
272 let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
274 assert!(a.is::<uint>());
275 assert!(!b.is::<uint>());
276 assert!(!c.is::<uint>());
278 assert!(!a.is::<&'static str>());
279 assert!(b.is::<&'static str>());
280 assert!(!c.is::<&'static str>());
282 assert!(!a.is::<Test>());
283 assert!(!b.is::<Test>());
284 assert!(c.is::<Test>());
289 let (a, b, c) = (~5u as ~Any, ~TEST as ~Any, ~Test as ~Any);
291 assert!(a.is::<uint>());
292 assert!(!b.is::<uint>());
293 assert!(!c.is::<uint>());
295 assert!(!a.is::<&'static str>());
296 assert!(b.is::<&'static str>());
297 assert!(!c.is::<&'static str>());
299 assert!(!a.is::<Test>());
300 assert!(!b.is::<Test>());
301 assert!(c.is::<Test>());
306 let (a, b, c) = (@5u as @Any, @TEST as @Any, @Test as @Any);
308 assert!(a.is::<uint>());
309 assert!(!b.is::<uint>());
310 assert!(!c.is::<uint>());
312 assert!(!a.is::<&'static str>());
313 assert!(b.is::<&'static str>());
314 assert!(!c.is::<&'static str>());
316 assert!(!a.is::<Test>());
317 assert!(!b.is::<Test>());
318 assert!(c.is::<Test>());
325 match a.as_ref::<uint>() {
327 x => fail!("Unexpected value {:?}", x)
330 match a.as_ref::<Test>() {
332 x => fail!("Unexpected value {:?}", x)
341 let a_r = &mut a as &mut Any;
342 let tmp: &mut uint = b;
343 let b_r = tmp as &mut Any;
345 match a_r.as_mut::<uint>() {
350 x => fail!("Unexpected value {:?}", x)
353 match b_r.as_mut::<uint>() {
358 x => fail!("Unexpected value {:?}", x)
361 match a_r.as_mut::<Test>() {
363 x => fail!("Unexpected value {:?}", x)
366 match b_r.as_mut::<Test>() {
368 x => fail!("Unexpected value {:?}", x)
371 match a_r.as_mut::<uint>() {
373 x => fail!("Unexpected value {:?}", x)
376 match b_r.as_mut::<uint>() {
378 x => fail!("Unexpected value {:?}", x)
385 let b = ~Test as ~Any;
387 assert_eq!(a.move(), Some(~8u));
388 assert_eq!(b.move(), Some(~Test));
391 let b = ~Test as ~Any;
393 assert_eq!(a.move(), None::<~Test>);
394 assert_eq!(b.move(), None::<~uint>);