diff --git a/src/type_object.rs b/src/type_object.rs index 6c1d8581..878558a7 100644 --- a/src/type_object.rs +++ b/src/type_object.rs @@ -352,36 +352,24 @@ where // basic methods ::tp_as_object(type_object); + fn to_ptr(value: Option) -> *mut T { + value + .map(|v| Box::into_raw(Box::new(v))) + .unwrap_or_else(ptr::null_mut) + } + // number methods - if let Some(meth) = ::tp_as_number() { - type_object.tp_as_number = Box::into_raw(Box::new(meth)); - } else { - type_object.tp_as_number = ::std::ptr::null_mut() - } - + type_object.tp_as_number = to_ptr(::tp_as_number()); // mapping methods - if let Some(meth) = ::tp_as_mapping() { - type_object.tp_as_mapping = Box::into_raw(Box::new(meth)); - } else { - type_object.tp_as_mapping = ::std::ptr::null_mut() - } - + type_object.tp_as_mapping = + to_ptr(::tp_as_mapping()); // sequence methods - if let Some(meth) = ::tp_as_sequence() { - type_object.tp_as_sequence = Box::into_raw(Box::new(meth)); - } else { - type_object.tp_as_sequence = ::std::ptr::null_mut() - } - + type_object.tp_as_sequence = + to_ptr(::tp_as_sequence()); // async methods - async_methods::(type_object); - + type_object.tp_as_async = to_ptr(::tp_as_async()); // buffer protocol - if let Some(meth) = ::tp_as_buffer() { - type_object.tp_as_buffer = Box::into_raw(Box::new(meth)); - } else { - type_object.tp_as_buffer = ::std::ptr::null_mut() - } + type_object.tp_as_buffer = to_ptr(::tp_as_buffer()); // normal methods let (new, init, call, mut methods) = py_class_method_defs::(); @@ -428,14 +416,6 @@ where } } -fn async_methods(type_info: &mut ffi::PyTypeObject) { - if let Some(meth) = ::tp_as_async() { - type_info.tp_as_async = Box::into_raw(Box::new(meth)); - } else { - type_info.tp_as_async = ::std::ptr::null_mut() - } -} - unsafe extern "C" fn tp_dealloc_callback(obj: *mut ffi::PyObject) where T: PyObjectAlloc,