use {
pyo3::{
intern,
{prelude::*, types::*},
},
std::{ffi::*, ptr::*},
};
pub fn into_capsule<'py, ValueT>(value: ValueT, name: CString, py: Python<'py>) -> PyResult<Bound<'py, PyCapsule>>
where
ValueT: 'static + Send + Sync,
{
PyCapsule::new(py, value, Some(name))
}
pub fn get_capsule_ptr<ValueT>(any: &Bound<'_, PyAny>, name: &CStr) -> PyResult<NonNull<ValueT>> {
Ok(any.cast::<PyCapsule>()?.pointer_checked(Some(name))?.cast())
}
pub fn clone_capsule<ValueT>(any: &Bound<'_, PyAny>, name: &CStr) -> PyResult<ValueT>
where
ValueT: Clone,
{
let capsule: NonNull<ValueT> = get_capsule_ptr(any, name)?;
Ok(unsafe { capsule.as_ref().clone() })
}
pub fn clone_capsule_attr<ValueT>(any: &Bound<'_, PyAny>, name: &CStr) -> PyResult<ValueT>
where
ValueT: Clone,
{
clone_capsule_from_attr(any, intern!(any.py(), "capsule"), name)
}
pub fn clone_capsule_from_attr<ValueT>(
any: &Bound<'_, PyAny>,
attr: &Bound<'_, PyString>,
name: &CStr,
) -> PyResult<ValueT>
where
ValueT: Clone,
{
clone_capsule(&any.getattr(attr)?, name)
}