|
1 | 1 | use std::future::Future;
|
| 2 | +use std::mem; |
2 | 3 |
|
3 | 4 | use crate::coroutine::cancel::ThrowCallback;
|
4 |
| -use crate::{coroutine::Coroutine, types::PyString, IntoPy, PyErr, PyObject}; |
| 5 | +use crate::pyclass::boolean_struct::False; |
| 6 | +use crate::{ |
| 7 | + coroutine::Coroutine, types::PyString, IntoPy, Py, PyAny, PyCell, PyClass, PyErr, PyObject, |
| 8 | + PyRef, PyRefMut, PyResult, Python, |
| 9 | +}; |
5 | 10 |
|
6 | 11 | pub fn new_coroutine<F, T, E>(
|
7 | 12 | name: &PyString,
|
|
16 | 21 | {
|
17 | 22 | Coroutine::new(Some(name.into()), qualname_prefix, throw_callback, future)
|
18 | 23 | }
|
| 24 | + |
| 25 | +fn get_ptr<T: PyClass>(obj: &Py<T>) -> *mut T { |
| 26 | + // SAFETY: Py<T> can be casted as *const PyCell<T> |
| 27 | + unsafe { &*(obj.as_ptr() as *const PyCell<T>) }.get_ptr() |
| 28 | +} |
| 29 | + |
| 30 | +struct RefGuard<T: PyClass>(Py<T>); |
| 31 | + |
| 32 | +impl<T: PyClass> Drop for RefGuard<T> { |
| 33 | + fn drop(&mut self) { |
| 34 | + Python::with_gil(|gil| self.0.as_ref(gil).release_ref()) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +pub unsafe fn ref_method_future<'a, T: PyClass, F: Future + 'a>( |
| 39 | + self_: &PyAny, |
| 40 | + fut: impl FnOnce(&'a T) -> F, |
| 41 | +) -> PyResult<impl Future<Output = F::Output>> { |
| 42 | + let ref_: PyRef<'_, T> = self_.extract()?; |
| 43 | + // SAFETY: `PyRef::as_ptr` returns a borrowed reference |
| 44 | + let guard = RefGuard(unsafe { Py::<T>::from_borrowed_ptr(self_.py(), ref_.as_ptr()) }); |
| 45 | + mem::forget(ref_); |
| 46 | + Ok(async move { fut(unsafe { &*get_ptr(&guard.0) }).await }) |
| 47 | +} |
| 48 | + |
| 49 | +struct RefMutGuard<T: PyClass>(Py<T>); |
| 50 | + |
| 51 | +impl<T: PyClass> Drop for RefMutGuard<T> { |
| 52 | + fn drop(&mut self) { |
| 53 | + Python::with_gil(|gil| self.0.as_ref(gil).release_mut()) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +pub fn mut_method_future<'a, T: PyClass<Frozen = False>, F: Future + 'a>( |
| 58 | + self_: &PyAny, |
| 59 | + fut: impl FnOnce(&'a mut T) -> F, |
| 60 | +) -> PyResult<impl Future<Output = F::Output>> { |
| 61 | + let mut_: PyRefMut<'_, T> = self_.extract()?; |
| 62 | + // SAFETY: `PyRefMut::as_ptr` returns a borrowed reference |
| 63 | + let guard = RefMutGuard(unsafe { Py::<T>::from_borrowed_ptr(self_.py(), mut_.as_ptr()) }); |
| 64 | + mem::forget(mut_); |
| 65 | + Ok(async move { fut(unsafe { &mut *get_ptr(&guard.0) }).await }) |
| 66 | +} |
0 commit comments