use std::borrow::Cow;
use std::ffi::CStr;
use err::{PyErr, PyResult};
use ffi;
use instance::{Py, PyObjectWithToken};
use object::PyObject;
use python::{Python, ToPyPointer};
use typeob::{PyTypeInfo, PyTypeObject};
#[repr(transparent)]
pub struct PyType(PyObject);
pyobject_native_type!(PyType, ffi::PyType_Type, ffi::PyType_Check);
impl PyType {
#[inline]
pub fn new<T: PyTypeInfo>() -> Py<PyType> {
unsafe { Py::from_borrowed_ptr(T::type_object() as *const _ as *mut ffi::PyObject) }
}
#[inline]
pub unsafe fn as_type_ptr(&self) -> *mut ffi::PyTypeObject {
self.as_ptr() as *mut ffi::PyTypeObject
}
#[inline]
pub unsafe fn from_type_ptr(py: Python, p: *mut ffi::PyTypeObject) -> &PyType {
py.from_borrowed_ptr::<PyType>(p as *mut ffi::PyObject)
}
pub fn name(&self) -> Cow<str> {
unsafe { CStr::from_ptr((*self.as_type_ptr()).tp_name).to_string_lossy() }
}
pub fn is_subclass<T>(&self) -> PyResult<bool>
where
T: PyTypeObject,
{
let result = unsafe { ffi::PyObject_IsSubclass(self.as_ptr(), T::type_object().as_ptr()) };
if result == -1 {
Err(PyErr::fetch(self.py()))
} else if result == 1 {
Ok(true)
} else {
Ok(false)
}
}
pub fn is_instance<T: ToPyPointer>(&self, obj: &T) -> PyResult<bool> {
let result = unsafe { ffi::PyObject_IsInstance(obj.as_ptr(), self.as_ptr()) };
if result == -1 {
Err(PyErr::fetch(self.py()))
} else if result == 1 {
Ok(true)
} else {
Ok(false)
}
}
}