2017-05-29 04:19:29 +00:00
|
|
|
// Copyright (c) 2017-present PyO3 Project and Contributors
|
|
|
|
|
2017-06-01 16:45:00 +00:00
|
|
|
use std::rc::Rc;
|
2017-05-29 04:19:29 +00:00
|
|
|
use std::marker::PhantomData;
|
|
|
|
|
2017-06-04 00:27:26 +00:00
|
|
|
use ffi;
|
2017-06-02 16:23:48 +00:00
|
|
|
use err::PyResult;
|
2017-06-04 00:27:26 +00:00
|
|
|
use python::{Python, IntoPyPointer};
|
2017-05-29 04:19:29 +00:00
|
|
|
use typeob::{PyTypeInfo, PyObjectAlloc};
|
|
|
|
|
|
|
|
|
2017-06-01 22:06:48 +00:00
|
|
|
pub struct PyToken(PhantomData<Rc<()>>);
|
2017-05-29 04:19:29 +00:00
|
|
|
|
2017-06-01 22:06:48 +00:00
|
|
|
impl PyToken {
|
2017-05-29 04:19:29 +00:00
|
|
|
pub fn token<'p>(&'p self) -> Python<'p> {
|
|
|
|
unsafe { Python::assume_gil_acquired() }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-04 00:27:26 +00:00
|
|
|
/// Create new python object and move T instance under python management
|
2017-05-29 04:19:29 +00:00
|
|
|
#[inline]
|
2017-06-04 00:27:26 +00:00
|
|
|
pub fn with<'p, T, F>(py: Python<'p>, f: F) -> PyResult<T::ParkTarget>
|
2017-06-01 22:06:48 +00:00
|
|
|
where F: FnOnce(PyToken) -> T,
|
2017-06-04 00:27:26 +00:00
|
|
|
T: Park<T> + PyTypeInfo + PyObjectAlloc<Type=T>
|
2017-05-29 04:19:29 +00:00
|
|
|
{
|
2017-06-04 00:27:26 +00:00
|
|
|
let ob = f(PyToken(PhantomData));
|
|
|
|
|
|
|
|
let ob = unsafe {
|
|
|
|
let ob = try!(<T as PyObjectAlloc>::alloc(py, ob));
|
|
|
|
T::from_owned_ptr(ob)
|
|
|
|
};
|
|
|
|
Ok(ob)
|
2017-05-29 04:19:29 +00:00
|
|
|
}
|
|
|
|
|
2017-06-01 22:06:48 +00:00
|
|
|
pub trait PyObjectWithToken : Sized {
|
2017-05-29 04:19:29 +00:00
|
|
|
fn token<'p>(&'p self) -> Python<'p>;
|
|
|
|
}
|
2017-06-04 00:27:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
pub trait Park<T> : Sized {
|
|
|
|
type ParkTarget: PythonPtr<T> + IntoPyPointer;
|
|
|
|
|
|
|
|
fn park(&self) -> Self::ParkTarget;
|
|
|
|
|
|
|
|
unsafe fn from_owned_ptr(*mut ffi::PyObject) -> Self::ParkTarget;
|
|
|
|
|
|
|
|
unsafe fn from_borrowed_ptr(*mut ffi::PyObject) -> Self::ParkTarget;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait PythonPtr<T> : Sized {
|
|
|
|
|
|
|
|
fn as_ref(&self, py: Python) -> &T;
|
|
|
|
|
|
|
|
fn as_mut(&self, py: Python) -> &mut T;
|
|
|
|
|
|
|
|
}
|