Skip to content
This repository was archived by the owner on Jun 8, 2021. It is now read-only.

Commit 2063013

Browse files
committed
Add constructor for getting any class struct from a glib::Type
1 parent 26aa57c commit 2063013

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/object.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,45 @@ pub unsafe trait IsClassFor: Sized + 'static {
125125
Some(&mut *klass)
126126
}
127127
}
128+
129+
/// Gets the class struct corresponding to `type_`.
130+
///
131+
/// This will return `None` if `type_` is not a subclass of `Self`.
132+
fn from_type(type_: Type) -> Option<ClassRef<Self>> {
133+
if !type_.is_a(&Self::Instance::static_type()) {
134+
return None;
135+
}
136+
137+
unsafe {
138+
let ptr = gobject_ffi::g_type_class_ref(type_.to_glib());
139+
if ptr.is_null() {
140+
None
141+
} else {
142+
Some(ClassRef(ptr::NonNull::new_unchecked(ptr as *mut Self)))
143+
}
144+
}
145+
}
146+
}
147+
148+
#[derive(Debug)]
149+
pub struct ClassRef<T: IsClassFor>(ptr::NonNull<T>);
150+
151+
impl<T: IsClassFor> ops::Deref for ClassRef<T> {
152+
type Target = T;
153+
154+
fn deref(&self) -> &T {
155+
unsafe {
156+
self.0.as_ref()
157+
}
158+
}
159+
}
160+
161+
impl<T: IsClassFor> Drop for ClassRef<T> {
162+
fn drop(&mut self) {
163+
unsafe {
164+
gobject_ffi::g_type_class_unref(self.0.as_ptr() as *mut _);
165+
}
166+
}
128167
}
129168

130169
/// Upcasting and downcasting support.

0 commit comments

Comments
 (0)