52dee675d2069038424775e29396769299d39ffc
[anymap] / src / unchecked_any.rs
1 use raw::Any;
2 use std::mem;
3 #[cfg(feature = "nightly")]
4 use std::raw::TraitObject;
5
6 #[cfg(not(feature = "nightly"))]
7 #[repr(C)]
8 #[allow(raw_pointer_derive)]
9 #[derive(Copy, Clone)]
10 struct TraitObject {
11 pub data: *mut (),
12 pub vtable: *mut (),
13 }
14
15 #[allow(missing_docs)] // Bogus warning (it’s not public outside the crate), ☹
16 pub trait UncheckedAnyExt {
17 unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T;
18 unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T;
19 unsafe fn downcast_unchecked<T: 'static>(self: Box<Self>) -> Box<T>;
20 }
21
22 impl UncheckedAnyExt for Any {
23 unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
24 mem::transmute(mem::transmute::<_, TraitObject>(self).data)
25 }
26
27 unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T {
28 mem::transmute(mem::transmute::<_, TraitObject>(self).data)
29 }
30
31 unsafe fn downcast_unchecked<T: 'static>(self: Box<Any>) -> Box<T> {
32 mem::transmute(mem::transmute::<_, TraitObject>(self).data)
33 }
34 }