1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use gobject as ffi;
use gtype;
use gtype::GType;
use refcount::Refcount;
use types::gpointer;
use wrap::Wrapper;
use std::mem::transmute;
pub unsafe trait ObjectType {
fn get_type() -> GType;
}
impl<T> Refcount for T where T: ObjectType + Wrapper {
unsafe fn inc_ref(&self) {
ffi::g_object_ref(self.as_mut_ptr() as gpointer);
}
unsafe fn dec_ref(&self) {
ffi::g_object_unref(self.as_mut_ptr() as gpointer);
}
}
pub trait Upcast<T> {
fn upcast(&self) -> &T;
}
impl<T> Upcast<T> for T {
#[inline]
fn upcast(&self) -> &T { self }
}
pub fn type_of<T>() -> GType where T: ObjectType {
<T as ObjectType>::get_type()
}
pub fn is_instance_of<T, U>(object: &T) -> bool
where T: ObjectType, U: ObjectType
{
gtype::check_instance_is_a(object, type_of::<U>())
}
fn assert_instance_of<T, U>(object: &T)
where T: ObjectType, U: ObjectType
{
let dest_type = type_of::<U>();
assert!(gtype::check_instance_is_a(object, dest_type),
"invalid cast to type {}", dest_type.name())
}
pub fn cast<T, U>(source: &T) -> &U
where T: ObjectType, U: ObjectType
{
assert_instance_of::<T, U>(source);
unsafe { transmute(source) }
}