Store type ids in a static BTreeMap

static variables inside generic functions are shared between all
instances of the function, we can't use that for storing our generated
type id.
This commit is contained in:
Sebastian Dröge 2017-09-24 22:47:14 +03:00
parent 1260dc42bb
commit 395a002f4a

View file

@ -10,6 +10,9 @@ use std::ffi::CString;
use std::ptr;
use std::mem;
use std::sync::atomic::AtomicBool;
use std::any::TypeId;
use std::collections::BTreeMap;
use std::sync::Mutex;
use glib_ffi;
use gobject_ffi;
@ -373,13 +376,21 @@ unsafe extern "C" fn set_property<T: ObjectType>(
);
}
static mut TYPES: *mut Mutex<BTreeMap<TypeId, glib::Type>> = 0 as *mut _;
pub unsafe fn get_type<T: ObjectType>() -> glib_ffi::GType {
use std::sync::{Once, ONCE_INIT};
static mut TYPE: glib_ffi::GType = gobject_ffi::G_TYPE_INVALID;
static ONCE: Once = ONCE_INIT;
ONCE.call_once(|| {
TYPES = Box::into_raw(Box::new(Mutex::new(BTreeMap::new())));
});
let mut types = (*TYPES).lock().unwrap();
types
.entry(TypeId::of::<T>())
.or_insert_with(|| {
let type_info = gobject_ffi::GTypeInfo {
class_size: mem::size_of::<ClassStruct<T>>() as u16,
base_init: None,
@ -398,7 +409,8 @@ pub unsafe fn get_type<T: ObjectType>() -> glib_ffi::GType {
loop {
let type_name = CString::new(format!("{}-{}", T::NAME, idx)).unwrap();
if gobject_ffi::g_type_from_name(type_name.as_ptr()) == gobject_ffi::G_TYPE_INVALID
if gobject_ffi::g_type_from_name(type_name.as_ptr()) ==
gobject_ffi::G_TYPE_INVALID
{
break type_name;
}
@ -406,15 +418,14 @@ pub unsafe fn get_type<T: ObjectType>() -> glib_ffi::GType {
}
};
TYPE = gobject_ffi::g_type_register_static(
from_glib(gobject_ffi::g_type_register_static(
T::glib_type().to_glib(),
type_name.as_ptr(),
&type_info,
gobject_ffi::G_TYPE_FLAG_ABSTRACT,
);
});
TYPE
))
})
.to_glib()
}
unsafe extern "C" fn sub_class_init<T: ObjectType>(