simplify instance ptr, droped #[py::ptr] annotation attr

This commit is contained in:
Nikolay Kim 2017-06-19 20:55:07 -07:00
parent b4deb673c7
commit 7b5521fdb3
22 changed files with 405 additions and 451 deletions

View File

@ -17,7 +17,6 @@ mod py_class;
mod py_impl;
mod py_proto;
mod py_method;
mod py_ptr;
mod args;
mod defs;
mod func;
@ -120,24 +119,3 @@ pub fn methods(_: TokenStream, input: TokenStream) -> TokenStream {
TokenStream::from_str(s.as_str()).unwrap()
}
#[proc_macro_attribute]
pub fn ptr(attr: TokenStream, input: TokenStream) -> TokenStream {
// Construct a string representation of the type definition
let source = input.to_string();
let cls = syn::Ident::from(&attr.to_string()[1..attr.to_string().len()-1]);
// Parse the string representation into a syntax tree
let mut ast = syn::parse_derive_input(&source).unwrap();
// Build the output
let expanded = py_ptr::build_ptr(cls, &mut ast);
// Return the generated impl as a TokenStream
let mut tokens = Tokens::new();
ast.to_tokens(&mut tokens);
let s = String::from(tokens.as_str()) + expanded.as_str();
TokenStream::from_str(s.as_str()).unwrap()
}

View File

@ -60,6 +60,35 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
}
}
impl _pyo3::ToPyObject for #cls
{
#[inline]
fn to_object<'p>(&self, py: _pyo3::Python<'p>) -> _pyo3::PyObject {
_pyo3::PyObject::from_borrowed_ptr(py, self.as_ptr())
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, _py: _pyo3::Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
f(self.as_ptr())
}
}
impl std::convert::AsRef<PyObject> for #cls {
fn as_ref(&self) -> &_pyo3::PyObject {
unsafe{std::mem::transmute(self.as_ptr())}
}
}
impl _pyo3::ToPyPointer for #cls {
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
unsafe {
{self as *const _ as *mut u8}.offset(-offset) as *mut ffi::PyObject
}
}
}
impl std::fmt::Debug for #cls {
fn fmt(&self, f : &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let py = _pyo3::PyObjectWithToken::token(self);
@ -209,34 +238,6 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
}
}
}
impl _pyo3::ToPyObject for #cls
{
#[inline]
fn to_object<'p>(&self, py: _pyo3::Python<'p>) -> _pyo3::PyObject {
_pyo3::PyObject::from_borrowed_ptr(py, self.as_ptr())
}
#[inline]
fn with_borrowed_ptr<F, R>(&self, _py: _pyo3::Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
f(self.as_ptr())
}
}
impl std::convert::AsRef<PyObject> for #cls {
fn as_ref(&self) -> &_pyo3::PyObject {
unsafe{std::mem::transmute(self.as_ptr())}
}
}
impl _pyo3::ToPyPointer for #cls {
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
unsafe {
{self as *const _ as *mut u8}.offset(-offset) as *mut ffi::PyObject
}
}
}
#extra
}

View File

@ -54,7 +54,7 @@ pub fn impl_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec, noargs: b
stringify!(#cls), ".", stringify!(#name), "()");
_pyo3::callback::cb_meth(LOCATION, |py| {
//println!("METH {:?} =====: {:?} {:?} {:?}", LOCATION, slf, args, kwargs);
let slf = #cls::from_borrowed_ptr(slf);
let slf = _pyo3::Ptr::<#cls>::from_borrowed_ptr(slf);
let result = {
let result: #output = {
@ -82,7 +82,7 @@ pub fn impl_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec, noargs: b
stringify!(#cls), ".", stringify!(#name), "()");
_pyo3::callback::cb_meth(LOCATION, |py| {
//println!("METH {:?} =====: {:?} {:?} {:?}", LOCATION, slf, args, kwargs);
let slf = #cls::from_borrowed_ptr(slf);
let slf = _pyo3::Ptr::<#cls>::from_borrowed_ptr(slf);
let args = _pyo3::PyTuple::from_borrowed_ptr(py, args);
let kwargs = _pyo3::argparse::get_kwargs(py, kwargs);
@ -117,7 +117,7 @@ pub fn impl_proto_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) ->
{
const LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
_pyo3::callback::cb_meth(LOCATION, |py| {
let slf = #cls::from_borrowed_ptr(slf);
let slf = _pyo3::Ptr::<#cls>::from_borrowed_ptr(slf);
let args = _pyo3::PyTuple::from_borrowed_ptr(py, args);
let kwargs = _pyo3::argparse::get_kwargs(py, kwargs);
@ -262,7 +262,7 @@ fn impl_wrap_setter(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tok
const LOCATION: &'static str = concat!(
stringify!(#cls), ".setter", stringify!(#name), "()");
_pyo3::callback::cb_setter(LOCATION, |py| {
let slf = #cls::from_borrowed_ptr(slf);
let slf = _pyo3::Ptr::<#cls>::from_borrowed_ptr(slf);
let value = _pyo3::PyObject::from_borrowed_ptr(py, value);
let result = match <#val_ty as _pyo3::FromPyObject>::extract(py, &value) {

View File

@ -1,131 +0,0 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use syn;
use quote::Tokens;
pub fn build_ptr(cls: syn::Ident, ast: &mut syn::DeriveInput) -> Tokens {
let ptr = &ast.ident;
let dummy_const = syn::Ident::new(format!("_IMPL_PYO3_CLS_PTR_{}", ast.ident));
quote! {
#[feature(specialization)]
#[allow(non_upper_case_globals, unused_attributes,
unused_qualifications, unused_variables, non_camel_case_types)]
const #dummy_const: () = {
use std;
extern crate pyo3 as _pyo3;
// thread-safe, because any python related operations require a Python<'p> token.
unsafe impl Send for #ptr {}
unsafe impl Sync for #ptr {}
impl _pyo3::ToInstancePtr<#cls> for #cls {
type Target = #ptr;
fn to_inst_ptr(&self) -> #ptr {
#ptr(unsafe{_pyo3::PyPtr::from_borrowed_ptr(self.as_ptr())})
}
unsafe fn from_owned_ptr(ptr: *mut _pyo3::ffi::PyObject) -> #ptr {
#ptr(_pyo3::PyPtr::from_owned_ptr(ptr))
}
unsafe fn from_borrowed_ptr(ptr: *mut _pyo3::ffi::PyObject) -> #ptr {
#ptr(_pyo3::PyPtr::from_borrowed_ptr(ptr))
}
}
impl _pyo3::InstancePtr<#cls> for #ptr {
#[inline]
fn as_ref(&self, _py: Python) -> &#cls {
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
unsafe {
let ptr = (self.as_ptr() as *mut u8).offset(offset) as *mut #cls;
ptr.as_ref().unwrap()
}
}
#[inline]
fn as_mut(&self, _py: Python) -> &mut #cls {
let offset = <#cls as _pyo3::typeob::PyTypeInfo>::offset();
unsafe {
let ptr = (self.as_ptr() as *mut u8).offset(offset) as *mut #cls;
ptr.as_mut().unwrap()
}
}
}
impl std::ops::Deref for #ptr {
type Target = _pyo3::PyPtr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for #ptr {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl _pyo3::PyClone for #ptr {
fn clone_ref(&self, _py: _pyo3::Python) -> #ptr {
#ptr(unsafe{ _pyo3::PyPtr::from_borrowed_ptr(self.as_ptr()) })
}
}
impl _pyo3::ToPyObject for #ptr {
fn to_object(&self, py: Python) -> _pyo3::PyObject {
_pyo3::PyObject::from_borrowed_ptr(py, self.as_ptr())
}
}
impl _pyo3::IntoPyObject for #ptr {
fn into_object(self, _py: Python) -> _pyo3::PyObject {
unsafe {std::mem::transmute(self)}
}
}
impl _pyo3::IntoPyPointer for #ptr {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
fn into_ptr(self) -> *mut ffi::PyObject {
self.0.into_ptr()
}
}
impl _pyo3::PyDowncastInto for #ptr
{
fn downcast_into<'p, I>(py: _pyo3::Python<'p>, ob: I)
-> Result<Self, _pyo3::PyDowncastError<'p>>
where I: _pyo3::IntoPyPointer
{
<#ptr as _pyo3::PyDowncastInto>::downcast_from_ptr(py, ob.into_ptr())
}
fn downcast_from_ptr<'p>(py: _pyo3::Python<'p>, ptr: *mut _pyo3::ffi::PyObject)
-> Result<#ptr, _pyo3::PyDowncastError<'p>>
{
unsafe{
let checked = ffi::PyObject_TypeCheck(
ptr, <#cls as _pyo3::typeob::PyTypeInfo>::type_object()) != 0;
if checked {
Ok(#ptr(PyPtr::from_owned_ptr(ptr)))
} else {
_pyo3::ffi::Py_DECREF(ptr);
Err(_pyo3::PyDowncastError(py, None))
}
}
}
fn unchecked_downcast_into<'p, I>(ob: I) -> Self where I: _pyo3::IntoPyPointer
{
unsafe{
#ptr(_pyo3::PyPtr::from_owned_ptr(ob.into_ptr()))
}
}
}
impl std::convert::From<#ptr> for _pyo3::PyObject {
fn from(ob: #ptr) -> Self {
unsafe{std::mem::transmute(ob)}
}
}
};
}
}

View File

@ -9,7 +9,7 @@ use objects::exc;
use conversion::IntoPyObject;
use ffi::{self, Py_hash_t};
use err::{PyErr, PyResult};
use token::{InstancePtr, ToInstancePtr};
use token::{Ptr, InstancePtr};
use typeob::PyTypeInfo;
@ -198,13 +198,13 @@ pub unsafe fn cb_unary<Slf, F, T, C>(location: &str,
slf: *mut ffi::PyObject, _c: C, f: F) -> C::R
where F: for<'p> FnOnce(Python<'p>, &'p mut Slf) -> PyResult<T>,
F: panic::UnwindSafe,
Slf: PyTypeInfo + ToInstancePtr<Slf>,
Slf: PyTypeInfo,
C: CallbackConverter<T>
{
let guard = AbortOnDrop(location);
let ret = panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let slf = Slf::from_borrowed_ptr(slf);
let slf = Ptr::<Slf>::from_borrowed_ptr(slf);
let result = match f(py, slf.as_mut(py)) {
Ok(val) => {
@ -233,12 +233,12 @@ pub unsafe fn cb_unary<Slf, F, T, C>(location: &str,
pub unsafe fn cb_unary_unit<Slf, F>(location: &str, slf: *mut ffi::PyObject, f: F) -> c_int
where F: for<'p> FnOnce(Python<'p>, &'p mut Slf) -> c_int,
F: panic::UnwindSafe,
Slf: PyTypeInfo + ToInstancePtr<Slf>,
Slf: PyTypeInfo,
{
let guard = AbortOnDrop(location);
let ret = panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let slf = Slf::from_borrowed_ptr(slf);
let slf = Ptr::<Slf>::from_borrowed_ptr(slf);
let result = f(py, slf.as_mut(py));
py.release(slf);

View File

@ -12,7 +12,6 @@ use ffi;
use err::PyResult;
use python::Python;
use callback::PyObjectCallbackConverter;
use token::ToInstancePtr;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -131,7 +130,7 @@ impl<'p, T> PyAsyncAwaitProtocolImpl for T where T: PyAsyncProtocol<'p>
}
}
impl<T> PyAsyncAwaitProtocolImpl for T where T: for<'p> PyAsyncAwaitProtocol<'p> + ToInstancePtr<T>
impl<T> PyAsyncAwaitProtocolImpl for T where T: for<'p> PyAsyncAwaitProtocol<'p>
{
#[inline]
fn am_await() -> Option<ffi::unaryfunc> {
@ -152,7 +151,7 @@ impl<'p, T> PyAsyncAiterProtocolImpl for T where T: PyAsyncProtocol<'p>
}
}
impl<T> PyAsyncAiterProtocolImpl for T where T: for<'p> PyAsyncAiterProtocol<'p> + ToInstancePtr<T>
impl<T> PyAsyncAiterProtocolImpl for T where T: for<'p> PyAsyncAiterProtocol<'p>
{
#[inline]
fn am_aiter() -> Option<ffi::unaryfunc> {
@ -173,7 +172,7 @@ impl<'p, T> PyAsyncAnextProtocolImpl for T where T: PyAsyncProtocol<'p>
}
}
impl<T> PyAsyncAnextProtocolImpl for T where T: for<'p> PyAsyncAnextProtocol<'p> + ToInstancePtr<T>
impl<T> PyAsyncAnextProtocolImpl for T where T: for<'p> PyAsyncAnextProtocol<'p>
{
#[inline]
fn am_anext() -> Option<ffi::unaryfunc> {

View File

@ -15,7 +15,7 @@ use err::{PyErr, PyResult};
use python::{Python, IntoPyPointer};
use objects::PyObject;
use objects::exc;
use token::{InstancePtr, ToInstancePtr};
use token::{Ptr, InstancePtr};
use typeob::PyTypeInfo;
use conversion::{FromPyObject, IntoPyObject};
use callback::{PyObjectCallbackConverter, HashConverter, BoolCallbackConverter};
@ -175,7 +175,7 @@ impl<'p, T> PyObjectGetAttrProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectGetAttrProtocolImpl for T where T: for<'p> PyObjectGetAttrProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectGetAttrProtocolImpl for T where T: for<'p> PyObjectGetAttrProtocol<'p>
{
#[inline]
fn tp_getattro() -> Option<ffi::binaryfunc> {
@ -196,7 +196,7 @@ impl<'p, T> PyObjectSetAttrProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectSetAttrProtocolImpl for T where T: for<'p> PyObjectSetAttrProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectSetAttrProtocolImpl for T where T: for<'p> PyObjectSetAttrProtocol<'p>
{
#[inline]
fn tp_setattro() -> Option<ffi::setattrofunc> {
@ -215,7 +215,7 @@ impl<'p, T> PyObjectDelAttrProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectDelAttrProtocolImpl for T where T: for<'p> PyObjectDelAttrProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectDelAttrProtocolImpl for T where T: for<'p> PyObjectDelAttrProtocol<'p>
{
#[inline]
default fn tp_delattro() -> Option<ffi::setattrofunc> {
@ -223,7 +223,7 @@ impl<T> PyObjectDelAttrProtocolImpl for T where T: for<'p> PyObjectDelAttrProtoc
}
}
impl<T> PyObjectDelAttrProtocolImpl for T
where T: for<'p> PyObjectSetAttrProtocol<'p> + for<'p> PyObjectDelAttrProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyObjectSetAttrProtocol<'p> + for<'p> PyObjectDelAttrProtocol<'p>
{
#[inline]
fn tp_delattro() -> Option<ffi::setattrofunc> {
@ -243,7 +243,7 @@ impl<'p, T> PyObjectStrProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectStrProtocolImpl for T where T: for<'p> PyObjectStrProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectStrProtocolImpl for T where T: for<'p> PyObjectStrProtocol<'p>
{
#[inline]
fn tp_str() -> Option<ffi::unaryfunc> {
@ -262,7 +262,7 @@ impl<'p, T> PyObjectReprProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectReprProtocolImpl for T where T: for<'p> PyObjectReprProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectReprProtocolImpl for T where T: for<'p> PyObjectReprProtocol<'p>
{
#[inline]
fn tp_repr() -> Option<ffi::unaryfunc> {
@ -318,7 +318,7 @@ impl<'p, T> PyObjectHashProtocolImpl for T where T: PyObjectProtocol<'p>
}
}
impl<T> PyObjectHashProtocolImpl for T
where T: for<'p> PyObjectHashProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyObjectHashProtocol<'p>
{
#[inline]
fn tp_hash() -> Option<ffi::hashfunc> {
@ -336,7 +336,7 @@ impl<'p, T> PyObjectBoolProtocolImpl for T where T: PyObjectProtocol<'p>
None
}
}
impl<T> PyObjectBoolProtocolImpl for T where T: for<'p> PyObjectBoolProtocol<'p> + ToInstancePtr<T>
impl<T> PyObjectBoolProtocolImpl for T where T: for<'p> PyObjectBoolProtocol<'p>
{
#[inline]
fn nb_bool() -> Option<ffi::inquiry> {
@ -355,21 +355,21 @@ impl<'p, T> PyObjectRichcmpProtocolImpl for T where T: PyObjectProtocol<'p>
}
}
impl<T> PyObjectRichcmpProtocolImpl for T
where T: for<'p> PyObjectRichcmpProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyObjectRichcmpProtocol<'p>
{
#[inline]
fn tp_richcompare() -> Option<ffi::richcmpfunc> {
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject,
op: c_int) -> *mut ffi::PyObject
where T: for<'p> PyObjectRichcmpProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyObjectRichcmpProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".__richcmp__()");
let guard = ::callback::AbortOnDrop(LOCATION);
let ret = std::panic::catch_unwind(|| {
let py = Python::assume_gil_acquired();
let slf = T::from_borrowed_ptr(slf);
let slf = Ptr::<T>::from_borrowed_ptr(slf);
let arg = PyObject::from_borrowed_ptr(py, arg);
let result = {

View File

@ -10,7 +10,6 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::Python;
use token::ToInstancePtr;
use typeob::PyTypeInfo;
use callback::UnitCallbackConverter;
@ -45,7 +44,7 @@ impl<T> PyBufferProtocolImpl for T {
default fn tp_as_buffer() -> Option<ffi::PyBufferProcs> { None }
}
impl<'p, T> PyBufferProtocolImpl for T where T: PyBufferProtocol<'p> + ToInstancePtr<T>
impl<'p, T> PyBufferProtocolImpl for T where T: PyBufferProtocol<'p>
{
#[inline]
fn tp_as_buffer() -> Option<ffi::PyBufferProcs> {
@ -70,14 +69,14 @@ impl<'p, T> PyBufferGetBufferProtocolImpl for T where T: PyBufferProtocol<'p>
}
impl<T> PyBufferGetBufferProtocolImpl for T
where T: for<'p> PyBufferGetBufferProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyBufferGetBufferProtocol<'p>
{
#[inline]
fn cb_bf_getbuffer() -> Option<ffi::getbufferproc> {
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg1: *mut ffi::Py_buffer,
arg2: c_int) -> c_int
where T: for<'p> PyBufferGetBufferProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyBufferGetBufferProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".buffer_get::<PyBufferProtocol>()");
::callback::cb_unary::<T, _, _, _>(LOCATION, slf, UnitCallbackConverter, |py, slf| {

View File

@ -13,7 +13,6 @@ use python::Python;
use objects::{PyType, PyObject};
use callback::{PyObjectCallbackConverter, UnitCallbackConverter};
use typeob::PyTypeInfo;
use token::ToInstancePtr;
use class::methods::PyMethodDef;
use conversion::{IntoPyObject, FromPyObject};
@ -67,7 +66,7 @@ impl<'p, T> PyDescrGetProtocolImpl for T where T: PyDescrProtocol<'p> {
None
}
}
impl<T> PyDescrGetProtocolImpl for T where T: for<'p> PyDescrGetProtocol<'p> + ToInstancePtr<T>
impl<T> PyDescrGetProtocolImpl for T where T: for<'p> PyDescrGetProtocol<'p>
{
fn tp_descr_get() -> Option<ffi::descrgetfunc> {
py_ternary_func!(PyDescrGetProtocol, T::__get__, T::Success, PyObjectCallbackConverter)
@ -81,7 +80,7 @@ impl<'p, T> PyDescrSetProtocolImpl for T where T: PyDescrProtocol<'p> {
None
}
}
impl<T> PyDescrSetProtocolImpl for T where T: for<'p> PyDescrSetProtocol<'p> + ToInstancePtr<T>
impl<T> PyDescrSetProtocolImpl for T where T: for<'p> PyDescrSetProtocol<'p>
{
fn tp_descr_set() -> Option<ffi::descrsetfunc> {
py_ternary_func!(PyDescrSetProtocol, T::__set__, (), UnitCallbackConverter, c_int)

View File

@ -9,7 +9,7 @@ use std::os::raw::{c_int, c_void};
use ffi;
use python::{Python, ToPyPointer};
use callback::AbortOnDrop;
use token::{InstancePtr, ToInstancePtr};
use token::{Ptr, InstancePtr};
use typeob::PyTypeInfo;
pub struct PyTraverseError(c_int);
@ -86,21 +86,21 @@ impl<'p, T> PyGCTraverseProtocolImpl for T where T: PyGCProtocol<'p>
}
#[doc(hidden)]
impl<T> PyGCTraverseProtocolImpl for T where T: for<'p> PyGCTraverseProtocol<'p> + ToInstancePtr<T>
impl<T> PyGCTraverseProtocolImpl for T where T: for<'p> PyGCTraverseProtocol<'p>
{
#[inline]
fn tp_traverse() -> Option<ffi::traverseproc> {
unsafe extern "C" fn tp_traverse<T>(slf: *mut ffi::PyObject,
visit: ffi::visitproc,
arg: *mut c_void) -> c_int
where T: for<'p> PyGCTraverseProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyGCTraverseProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".__traverse__()");
let guard = AbortOnDrop(LOCATION);
let py = Python::assume_gil_acquired();
let visit = PyVisit { visit: visit, arg: arg, _py: py };
let slf = T::from_borrowed_ptr(slf);
let slf = Ptr::<T>::from_borrowed_ptr(slf);
let ret = match slf.as_ref(py).__traverse__(py, visit) {
Ok(()) => 0,
@ -127,18 +127,18 @@ impl<'p, T> PyGCClearProtocolImpl for T where T: PyGCProtocol<'p>
}
}
impl<T> PyGCClearProtocolImpl for T where T: for<'p> PyGCClearProtocol<'p> + ToInstancePtr<T>
impl<T> PyGCClearProtocolImpl for T where T: for<'p> PyGCClearProtocol<'p>
{
#[inline]
fn tp_clear() -> Option<ffi::inquiry> {
unsafe extern "C" fn tp_clear<T>(slf: *mut ffi::PyObject) -> c_int
where T: for<'p> PyGCClearProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyGCClearProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".__clear__()");
let guard = AbortOnDrop(LOCATION);
let py = Python::assume_gil_acquired();
let slf = T::from_borrowed_ptr(slf);
let slf = Ptr::<T>::from_borrowed_ptr(slf);
T::__clear__(&mut slf.as_mut(py), py);
mem::forget(guard);
0

View File

@ -9,7 +9,6 @@
use ffi;
use err::PyResult;
use python::Python;
use token::ToInstancePtr;
use typeob::PyTypeInfo;
use callback::{PyObjectCallbackConverter, IterNextResultConverter};
@ -66,7 +65,7 @@ impl<'p, T> PyIterIterProtocolImpl for T where T: PyIterProtocol<'p>
}
}
impl<T> PyIterIterProtocolImpl for T where T: for<'p> PyIterIterProtocol<'p> + ToInstancePtr<T>
impl<T> PyIterIterProtocolImpl for T where T: for<'p> PyIterIterProtocol<'p>
{
#[inline]
fn tp_iter() -> Option<ffi::getiterfunc> {
@ -87,7 +86,7 @@ impl<'p, T> PyIterNextProtocolImpl for T
}
}
impl<T> PyIterNextProtocolImpl for T where T: for<'p> PyIterNextProtocol<'p> + ToInstancePtr<T>
impl<T> PyIterNextProtocolImpl for T where T: for<'p> PyIterNextProtocol<'p>
{
#[inline]
fn tp_iternext() -> Option<ffi::iternextfunc> {

View File

@ -8,13 +8,13 @@ macro_rules! py_unary_func {
};
($trait:ident, $class:ident :: $f:ident, $res_type:ty, $conv:expr, $ret_type:ty) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject) -> $ret_type
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let result = {
let res = slf.as_mut(py).$f(py).into();
$crate::callback::cb_convert($conv, py, res)
@ -33,13 +33,13 @@ macro_rules! py_unary_func {
($trait:ident, $class:ident :: $f:ident, $res_type:ty, $conv:ty) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject)
-> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p> + ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let result = {
let res = slf.as_mut(py).$f(py).into();
$crate::callback::cb_convert($conv, py, res)
@ -59,7 +59,7 @@ macro_rules! py_len_func {
($trait:ident, $class:ident :: $f:ident, $conv:expr) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject)
-> $crate::ffi::Py_ssize_t
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_unary::<T, _, _, _>(LOCATION, slf, $conv, |py, slf| {
@ -80,13 +80,13 @@ macro_rules! py_binary_func{
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject) -> $return
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let result = {
@ -114,13 +114,13 @@ macro_rules! py_binary_self_func{
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject) -> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = T::from_borrowed_ptr(slf);
let slf1 = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let arg = $crate::PyObject::from_borrowed_ptr(py, arg);
let result = {
@ -159,13 +159,13 @@ macro_rules! py_ssizearg_func {
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: $crate::Py_ssize_t) -> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let result = {
let result = slf.as_mut(py).$f(py, arg as isize).into();
$crate::callback::cb_convert($conv, py, result)
@ -188,13 +188,13 @@ macro_rules! py_ternary_func{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
arg1: *mut $crate::ffi::PyObject,
arg2: *mut $crate::ffi::PyObject) -> $return_type
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py, arg2);
@ -227,13 +227,13 @@ macro_rules! py_ternary_self_func{
arg1: *mut $crate::ffi::PyObject,
arg2: *mut $crate::ffi::PyObject)
-> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = T::from_borrowed_ptr(slf);
let slf1 = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let arg1 = $crate::PyObject::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObject::from_borrowed_ptr(py, arg2);
@ -272,7 +272,7 @@ macro_rules! py_func_set{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
name: *mut $crate::ffi::PyObject,
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
@ -321,7 +321,7 @@ macro_rules! py_func_del{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
name: *mut $crate::ffi::PyObject,
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
@ -330,7 +330,7 @@ macro_rules! py_func_del{
LOCATION, $crate::callback::UnitCallbackConverter, |py|
{
if value.is_null() {
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let name = PyObject::from_borrowed_ptr(py, name);
let result = {
@ -373,7 +373,7 @@ macro_rules! py_func_set_del{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
name: *mut $crate::ffi::PyObject,
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p> + for<'p> $trait2<'p> + $crate::ToInstancePtr<T>
where T: for<'p> $trait<'p> + for<'p> $trait2<'p>
{
use token::InstancePtr;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
@ -381,7 +381,7 @@ macro_rules! py_func_set_del{
$crate::callback::cb_pyfunc::<_, _, ()>(
LOCATION, $crate::callback::UnitCallbackConverter, |py|
{
let slf = T::from_borrowed_ptr(slf);
let slf = $crate::Ptr::<T>::from_borrowed_ptr(slf);
let name = PyObject::from_borrowed_ptr(py, name);
let result = {

View File

@ -9,7 +9,6 @@ use python::Python;
use objects::{exc, PyObject};
use callback::{PyObjectCallbackConverter, LenResultConverter};
use conversion::{IntoPyObject, FromPyObject};
use token::ToInstancePtr;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -144,7 +143,7 @@ impl<'p, T> PyMappingLenProtocolImpl for T where T: PyMappingProtocol<'p>
}
}
impl<T> PyMappingLenProtocolImpl for T where T: for<'p> PyMappingLenProtocol<'p> + ToInstancePtr<T>
impl<T> PyMappingLenProtocolImpl for T where T: for<'p> PyMappingLenProtocol<'p>
{
#[inline]
fn mp_length() -> Option<ffi::lenfunc> {
@ -164,7 +163,7 @@ impl<'p, T> PyMappingGetItemProtocolImpl for T where T: PyMappingProtocol<'p>
}
}
impl<T> PyMappingGetItemProtocolImpl for T where T: for<'p> PyMappingGetItemProtocol<'p> + ToInstancePtr<T>
impl<T> PyMappingGetItemProtocolImpl for T where T: for<'p> PyMappingGetItemProtocol<'p>
{
#[inline]
fn mp_subscript() -> Option<ffi::binaryfunc> {
@ -185,7 +184,7 @@ impl<'p, T> PyMappingSetItemProtocolImpl for T where T: PyMappingProtocol<'p>
}
}
impl<T> PyMappingSetItemProtocolImpl for T where T: for<'p> PyMappingSetItemProtocol<'p> + ToInstancePtr<T>
impl<T> PyMappingSetItemProtocolImpl for T where T: for<'p> PyMappingSetItemProtocol<'p>
{
#[inline]
fn mp_ass_subscript() -> Option<ffi::objobjargproc> {
@ -206,7 +205,7 @@ impl<'p, T> PyMappingDelItemProtocolImpl for T where T: PyMappingProtocol<'p>
}
}
impl<T> PyMappingDelItemProtocolImpl for T where T: for<'p> PyMappingDelItemProtocol<'p> + ToInstancePtr<T>
impl<T> PyMappingDelItemProtocolImpl for T where T: for<'p> PyMappingDelItemProtocol<'p>
{
#[inline]
default fn mp_del_subscript() -> Option<ffi::objobjargproc> {
@ -216,7 +215,7 @@ impl<T> PyMappingDelItemProtocolImpl for T where T: for<'p> PyMappingDelItemProt
impl<T> PyMappingDelItemProtocolImpl for T
where T: for<'p> PyMappingSetItemProtocol<'p> + for<'p> PyMappingDelItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyMappingSetItemProtocol<'p> + for<'p> PyMappingDelItemProtocol<'p>
{
#[inline]
fn mp_del_subscript() -> Option<ffi::objobjargproc> {

View File

@ -10,7 +10,7 @@ use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
use class::basic::PyObjectProtocolImpl;
use ::{IntoPyObject, FromPyObject, ToInstancePtr};
use ::{IntoPyObject, FromPyObject};
/// Number interface
#[allow(unused_variables)]
@ -555,7 +555,7 @@ trait PyNumberAddProtocolImpl {
impl<'p, T> PyNumberAddProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_add() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberAddProtocolImpl for T where T: for<'p> PyNumberAddProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberAddProtocolImpl for T where T: for<'p> PyNumberAddProtocol<'p> {
fn nb_add() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberAddProtocol, T::__add__, T::Success, PyObjectCallbackConverter)
}
@ -567,7 +567,7 @@ trait PyNumberSubProtocolImpl {
impl<'p, T> PyNumberSubProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_subtract() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberSubProtocolImpl for T where T: for<'p> PyNumberSubProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberSubProtocolImpl for T where T: for<'p> PyNumberSubProtocol<'p> {
fn nb_subtract() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberSubProtocol, T::__sub__, T::Success, PyObjectCallbackConverter)
}
@ -579,7 +579,7 @@ trait PyNumberMulProtocolImpl {
impl<'p, T> PyNumberMulProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_multiply() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberMulProtocolImpl for T where T: for<'p> PyNumberMulProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberMulProtocolImpl for T where T: for<'p> PyNumberMulProtocol<'p> {
fn nb_multiply() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberMulProtocol, T::__mul__, T::Success, PyObjectCallbackConverter)
}
@ -591,7 +591,7 @@ trait PyNumberMatmulProtocolImpl {
impl<'p, T> PyNumberMatmulProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_matrix_multiply() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberMatmulProtocolImpl for T where T: for<'p> PyNumberMatmulProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberMatmulProtocolImpl for T where T: for<'p> PyNumberMatmulProtocol<'p> {
fn nb_matrix_multiply() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberMatmulProtocol,
T::__matmul__, T::Success, PyObjectCallbackConverter)
@ -605,7 +605,7 @@ impl<'p, T> PyNumberTruedivProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_true_divide() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberTruedivProtocolImpl for T
where T: for<'p> PyNumberTruedivProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberTruedivProtocol<'p>
{
fn nb_true_divide() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberTruedivProtocol,
@ -620,7 +620,7 @@ impl<'p, T> PyNumberFloordivProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_floor_divide() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberFloordivProtocolImpl for T
where T: for<'p> PyNumberFloordivProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberFloordivProtocol<'p>
{
fn nb_floor_divide() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberFloordivProtocol,
@ -634,7 +634,7 @@ trait PyNumberModProtocolImpl {
impl<'p, T> PyNumberModProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_remainder() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberModProtocolImpl for T where T: for<'p> PyNumberModProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberModProtocolImpl for T where T: for<'p> PyNumberModProtocol<'p> {
fn nb_remainder() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberModProtocol, T::__mod__, T::Success, PyObjectCallbackConverter)
}
@ -646,7 +646,7 @@ trait PyNumberDivmodProtocolImpl {
impl<'p, T> PyNumberDivmodProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_divmod() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberDivmodProtocolImpl for T where T: for<'p> PyNumberDivmodProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberDivmodProtocolImpl for T where T: for<'p> PyNumberDivmodProtocol<'p> {
fn nb_divmod() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberDivmodProtocol,
T::__divmod__, T::Success, PyObjectCallbackConverter)
@ -659,7 +659,7 @@ trait PyNumberPowProtocolImpl {
impl<'p, T> PyNumberPowProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_power() -> Option<ffi::ternaryfunc> {None}
}
impl<T> PyNumberPowProtocolImpl for T where T: for<'p> PyNumberPowProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberPowProtocolImpl for T where T: for<'p> PyNumberPowProtocol<'p> {
fn nb_power() -> Option<ffi::ternaryfunc> {
py_ternary_func!(PyNumberPowProtocol,
T::__pow__, <T as PyNumberPowProtocol>::Success,
@ -673,7 +673,7 @@ trait PyNumberLShiftProtocolImpl {
impl<'p, T> PyNumberLShiftProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_lshift() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberLShiftProtocolImpl for T where T: for<'p> PyNumberLShiftProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberLShiftProtocolImpl for T where T: for<'p> PyNumberLShiftProtocol<'p> {
fn nb_lshift() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberLShiftProtocol,
T::__lshift__, T::Success, PyObjectCallbackConverter)
@ -686,7 +686,7 @@ trait PyNumberRShiftProtocolImpl {
impl<'p, T> PyNumberRShiftProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_rshift() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberRShiftProtocolImpl for T where T: for<'p> PyNumberRShiftProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberRShiftProtocolImpl for T where T: for<'p> PyNumberRShiftProtocol<'p> {
fn nb_rshift() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberRShiftProtocol,
T::__rshift__, T::Success, PyObjectCallbackConverter)
@ -700,7 +700,7 @@ trait PyNumberAndProtocolImpl {
impl<'p, T> PyNumberAndProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_and() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberAndProtocolImpl for T where T: for<'p> PyNumberAndProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberAndProtocolImpl for T where T: for<'p> PyNumberAndProtocol<'p> {
fn nb_and() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberAndProtocol,
T::__and__, T::Success, PyObjectCallbackConverter)
@ -713,7 +713,7 @@ trait PyNumberXorProtocolImpl {
impl<'p, T> PyNumberXorProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_xor() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberXorProtocolImpl for T where T: for<'p> PyNumberXorProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberXorProtocolImpl for T where T: for<'p> PyNumberXorProtocol<'p> {
fn nb_xor() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberXorProtocol,
T::__xor__, T::Success, PyObjectCallbackConverter)
@ -726,7 +726,7 @@ trait PyNumberOrProtocolImpl {
impl<'p, T> PyNumberOrProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_or() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberOrProtocolImpl for T where T: for<'p> PyNumberOrProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberOrProtocolImpl for T where T: for<'p> PyNumberOrProtocol<'p> {
fn nb_or() -> Option<ffi::binaryfunc> {
py_binary_func!(PyNumberOrProtocol,
T::__or__, T::Success, PyObjectCallbackConverter)
@ -740,7 +740,7 @@ trait PyNumberIAddProtocolImpl {
impl<'p, T> PyNumberIAddProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_add() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIAddProtocolImpl for T where T: for<'p> PyNumberIAddProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIAddProtocolImpl for T where T: for<'p> PyNumberIAddProtocol<'p> {
fn nb_inplace_add() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIAddProtocol, T::__iadd__)
}
@ -752,7 +752,7 @@ trait PyNumberISubProtocolImpl {
impl<'p, T> PyNumberISubProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_subtract() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberISubProtocolImpl for T where T: for<'p> PyNumberISubProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberISubProtocolImpl for T where T: for<'p> PyNumberISubProtocol<'p> {
fn nb_inplace_subtract() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberISubProtocol, T::__isub__)
}
@ -764,7 +764,7 @@ trait PyNumberIMulProtocolImpl {
impl<'p, T> PyNumberIMulProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_multiply() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIMulProtocolImpl for T where T: for<'p> PyNumberIMulProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIMulProtocolImpl for T where T: for<'p> PyNumberIMulProtocol<'p> {
fn nb_inplace_multiply() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIMulProtocol, T::__imul__)
}
@ -777,7 +777,7 @@ impl<'p, T> PyNumberIMatmulProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_matrix_multiply() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIMatmulProtocolImpl for T
where T: for<'p> PyNumberIMatmulProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberIMatmulProtocol<'p>
{
fn nb_inplace_matrix_multiply() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIMatmulProtocol, T::__imatmul__)
@ -791,7 +791,7 @@ impl<'p, T> PyNumberITruedivProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_true_divide() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberITruedivProtocolImpl for T
where T: for<'p> PyNumberITruedivProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberITruedivProtocol<'p>
{
fn nb_inplace_true_divide() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberITruedivProtocol, T::__itruediv__)
@ -805,7 +805,7 @@ impl<'p, T> PyNumberIFloordivProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_floor_divide() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIFloordivProtocolImpl for T
where T: for<'p> PyNumberIFloordivProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberIFloordivProtocol<'p>
{
fn nb_inplace_floor_divide() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIFloordivProtocol, T::__ifloordiv__)
@ -818,7 +818,7 @@ trait PyNumberIModProtocolImpl {
impl<'p, T> PyNumberIModProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_remainder() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIModProtocolImpl for T where T: for<'p> PyNumberIModProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIModProtocolImpl for T where T: for<'p> PyNumberIModProtocol<'p> {
fn nb_inplace_remainder() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIModProtocol, T::__imod__)
}
@ -830,7 +830,7 @@ trait PyNumberIPowProtocolImpl {
impl<'p, T> PyNumberIPowProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_power() -> Option<ffi::ternaryfunc> {None}
}
impl<T> PyNumberIPowProtocolImpl for T where T: for<'p> PyNumberIPowProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIPowProtocolImpl for T where T: for<'p> PyNumberIPowProtocol<'p> {
fn nb_inplace_power() -> Option<ffi::ternaryfunc> {
py_ternary_self_func!(PyNumberIPowProtocol, T::__ipow__)
}
@ -843,7 +843,7 @@ impl<'p, T> PyNumberILShiftProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_lshift() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberILShiftProtocolImpl for T
where T: for<'p> PyNumberILShiftProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberILShiftProtocol<'p>
{
fn nb_inplace_lshift() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberILShiftProtocol, T::__ilshift__)
@ -857,7 +857,7 @@ impl<'p, T> PyNumberIRShiftProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_rshift() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIRShiftProtocolImpl for T
where T: for<'p> PyNumberIRShiftProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberIRShiftProtocol<'p>
{
fn nb_inplace_rshift() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIRShiftProtocol, T::__irshift__)
@ -871,7 +871,7 @@ trait PyNumberIAndProtocolImpl {
impl<'p, T> PyNumberIAndProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_and() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIAndProtocolImpl for T where T: for<'p> PyNumberIAndProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIAndProtocolImpl for T where T: for<'p> PyNumberIAndProtocol<'p> {
fn nb_inplace_and() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIAndProtocol, T::__iand__)
}
@ -883,7 +883,7 @@ trait PyNumberIXorProtocolImpl {
impl<'p, T> PyNumberIXorProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_xor() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIXorProtocolImpl for T where T: for<'p> PyNumberIXorProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIXorProtocolImpl for T where T: for<'p> PyNumberIXorProtocol<'p> {
fn nb_inplace_xor() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIXorProtocol, T::__ixor__)
}
@ -895,7 +895,7 @@ trait PyNumberIOrProtocolImpl {
impl<'p, T> PyNumberIOrProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_inplace_or() -> Option<ffi::binaryfunc> {None}
}
impl<T> PyNumberIOrProtocolImpl for T where T: for<'p> PyNumberIOrProtocol<'p> + ToInstancePtr<T> {
impl<T> PyNumberIOrProtocolImpl for T where T: for<'p> PyNumberIOrProtocol<'p> {
fn nb_inplace_or() -> Option<ffi::binaryfunc> {
py_binary_self_func!(PyNumberIOrProtocol, T::__ior__)
}
@ -1007,7 +1007,7 @@ trait PyNumberNegProtocolImpl {
impl<'p, T> PyNumberNegProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_negative() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberNegProtocolImpl for T where T: for<'p> PyNumberNegProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberNegProtocolImpl for T where T: for<'p> PyNumberNegProtocol<'p>
{
#[inline]
fn nb_negative() -> Option<ffi::unaryfunc> {
@ -1021,7 +1021,7 @@ trait PyNumberPosProtocolImpl {
impl<'p, T> PyNumberPosProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_positive() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberPosProtocolImpl for T where T: for<'p> PyNumberPosProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberPosProtocolImpl for T where T: for<'p> PyNumberPosProtocol<'p>
{
fn nb_positive() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberPosProtocol, T::__pos__, T::Success, PyObjectCallbackConverter)
@ -1034,7 +1034,7 @@ trait PyNumberAbsProtocolImpl {
impl<'p, T> PyNumberAbsProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_absolute() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberAbsProtocolImpl for T where T: for<'p> PyNumberAbsProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberAbsProtocolImpl for T where T: for<'p> PyNumberAbsProtocol<'p>
{
fn nb_absolute() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberAbsProtocol, T::__abs__, T::Success, PyObjectCallbackConverter)
@ -1047,7 +1047,7 @@ trait PyNumberInvertProtocolImpl {
impl<'p, T> PyNumberInvertProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_invert() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberInvertProtocolImpl for T where T: for<'p> PyNumberInvertProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberInvertProtocolImpl for T where T: for<'p> PyNumberInvertProtocol<'p>
{
fn nb_invert() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberInvertProtocol, T::__invert__,
@ -1061,7 +1061,7 @@ trait PyNumberIntProtocolImpl {
impl<'p, T> PyNumberIntProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_int() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberIntProtocolImpl for T where T: for<'p> PyNumberIntProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberIntProtocolImpl for T where T: for<'p> PyNumberIntProtocol<'p>
{
fn nb_int() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberIntProtocol, T::__int__,
@ -1075,7 +1075,7 @@ trait PyNumberFloatProtocolImpl {
impl<'p, T> PyNumberFloatProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_float() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberFloatProtocolImpl for T where T: for<'p> PyNumberFloatProtocol<'p> + ToInstancePtr<T>
impl<T> PyNumberFloatProtocolImpl for T where T: for<'p> PyNumberFloatProtocol<'p>
{
fn nb_float() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberFloatProtocol, T::__float__,
@ -1090,7 +1090,7 @@ impl<'p, T> PyNumberIndexProtocolImpl for T where T: PyNumberProtocol<'p> {
default fn nb_index() -> Option<ffi::unaryfunc> {None}
}
impl<T> PyNumberIndexProtocolImpl for T
where T: for<'p> PyNumberIndexProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PyNumberIndexProtocol<'p>
{
fn nb_index() -> Option<ffi::unaryfunc> {
py_unary_func!(PyNumberIndexProtocol,

View File

@ -11,7 +11,6 @@ use err::{PyErr, PyResult};
use objects::exc;
use objects::PyObject;
use callback::{PyObjectCallbackConverter, LenResultConverter, BoolCallbackConverter};
use token::ToInstancePtr;
use typeob::PyTypeInfo;
use conversion::{IntoPyObject, FromPyObject};
@ -164,7 +163,7 @@ impl<'p, T> PySequenceLenProtocolImpl for T where T: PySequenceProtocol<'p>
}
}
impl<T> PySequenceLenProtocolImpl for T where T: for<'p> PySequenceLenProtocol<'p> + ToInstancePtr<T>
impl<T> PySequenceLenProtocolImpl for T where T: for<'p> PySequenceLenProtocol<'p>
{
#[inline]
fn sq_length() -> Option<ffi::lenfunc> {
@ -185,7 +184,7 @@ impl<'p, T> PySequenceGetItemProtocolImpl for T where T: PySequenceProtocol<'p>
}
impl<T> PySequenceGetItemProtocolImpl for T
where T: for<'p> PySequenceGetItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceGetItemProtocol<'p>
{
#[inline]
fn sq_item() -> Option<ffi::ssizeargfunc> {
@ -207,14 +206,14 @@ impl<'p, T> PySequenceSetItemProtocolImpl for T where T: PySequenceProtocol<'p>
}
impl<T> PySequenceSetItemProtocolImpl for T
where T: for<'p> PySequenceSetItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceSetItemProtocol<'p>
{
#[inline]
fn sq_ass_item() -> Option<ffi::ssizeobjargproc> {
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
key: ffi::Py_ssize_t,
value: *mut ffi::PyObject) -> c_int
where T: for<'p> PySequenceSetItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceSetItemProtocol<'p>
{
const LOCATION: &'static str = "foo.__setitem__()";
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
@ -258,14 +257,14 @@ impl<'p, T> PySequenceDelItemProtocolImpl for T where T: PySequenceProtocol<'p>
}
impl<T> PySequenceDelItemProtocolImpl for T
where T: for<'p> PySequenceDelItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceDelItemProtocol<'p>
{
#[inline]
default fn sq_del_item() -> Option<ffi::ssizeobjargproc> {
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
key: ffi::Py_ssize_t,
value: *mut ffi::PyObject) -> c_int
where T: for<'p> PySequenceDelItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceDelItemProtocol<'p>
{
const LOCATION: &'static str = "T.__detitem__()";
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
@ -292,7 +291,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
}
impl<T> PySequenceDelItemProtocolImpl for T
where T: for<'p> PySequenceSetItemProtocol<'p> + for<'p> PySequenceDelItemProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceSetItemProtocol<'p> + for<'p> PySequenceDelItemProtocol<'p>
{
#[inline]
fn sq_del_item() -> Option<ffi::ssizeobjargproc> {
@ -300,7 +299,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
key: ffi::Py_ssize_t,
value: *mut ffi::PyObject) -> c_int
where T: for<'p> PySequenceSetItemProtocol<'p> +
for<'p> PySequenceDelItemProtocol<'p> + ToInstancePtr<T>
for<'p> PySequenceDelItemProtocol<'p>
{
const LOCATION: &'static str = "T.__set/del_item__()";
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
@ -349,7 +348,7 @@ impl<'p, T> PySequenceContainsProtocolImpl for T where T: PySequenceProtocol<'p>
}
impl<T> PySequenceContainsProtocolImpl for T
where T: for<'p> PySequenceContainsProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceContainsProtocol<'p>
{
#[inline]
fn sq_contains() -> Option<ffi::objobjproc> {
@ -371,7 +370,7 @@ impl<'p, T> PySequenceConcatProtocolImpl for T where T: PySequenceProtocol<'p>
}
impl<T> PySequenceConcatProtocolImpl for T
where T: for<'p> PySequenceConcatProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceConcatProtocol<'p>
{
#[inline]
fn sq_concat() -> Option<ffi::binaryfunc> {
@ -393,7 +392,7 @@ impl<'p, T> PySequenceRepeatProtocolImpl for T
}
}
impl<T> PySequenceRepeatProtocolImpl for T where T: for<'p> PySequenceRepeatProtocol<'p> + ToInstancePtr<T>
impl<T> PySequenceRepeatProtocolImpl for T where T: for<'p> PySequenceRepeatProtocol<'p>
{
#[inline]
fn sq_repeat() -> Option<ffi::ssizeargfunc> {
@ -415,7 +414,7 @@ impl<'p, T> PySequenceInplaceConcatProtocolImpl for T where T: PySequenceProtoco
}
impl<T> PySequenceInplaceConcatProtocolImpl for T
where T: for<'p> PySequenceInplaceConcatProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceInplaceConcatProtocol<'p>
{
#[inline]
fn sq_inplace_concat() -> Option<ffi::binaryfunc> {
@ -437,7 +436,7 @@ impl<'p, T> PySequenceInplaceRepeatProtocolImpl for T where T: PySequenceProtoco
}
impl<T> PySequenceInplaceRepeatProtocolImpl for T
where T: for<'p> PySequenceInplaceRepeatProtocol<'p> + ToInstancePtr<T>
where T: for<'p> PySequenceInplaceRepeatProtocol<'p>
{
#[inline]
fn sq_inplace_repeat() -> Option<ffi::ssizeargfunc> {

View File

@ -156,8 +156,8 @@ pub use ffi::{Py_ssize_t, Py_hash_t};
mod pointers;
pub use pointers::PyPtr;
mod token;
pub use token::{PyToken, PyObjectWithToken, ToInstancePtr, InstancePtr};
pub mod token;
pub use token::{PyToken, PyObjectWithToken, InstancePtr, Ptr};
pub use err::{PyErr, PyResult, PyDowncastError, ToPyErr};
pub use objects::*;

View File

@ -43,6 +43,12 @@ impl IntoPyObject for String {
PyString::new(py, &self).into()
}
}
impl<'a> IntoPyObject for &'a String {
#[inline]
fn into_object(self, py: Python) -> PyObject {
PyString::new(py, self).into()
}
}
/// Allows extracting strings from Python objects.
/// Accepts Python `str` and `unicode` objects.

View File

@ -9,7 +9,7 @@ use std::os::raw::c_int;
use ffi;
use typeob::{PyTypeInfo, PyTypeObject, PyObjectAlloc};
use token::{PyToken, ToInstancePtr};
use token::{Ptr, PyToken};
use objects::{PyObject, PyType, PyBool, PyDict, PyModule};
use err::{PyErr, PyResult, PyDowncastError, ToPyErr};
use pythonrun::GILGuard;
@ -231,11 +231,11 @@ impl<'p> Python<'p> {
/// Create new python object and move T instance under python management
#[inline]
pub fn init<T, F>(self, f: F) -> PyResult<T::Target>
pub fn init<T, F>(self, f: F) -> PyResult<Ptr<T>>
where F: FnOnce(PyToken) -> T,
T: ToInstancePtr<T> + PyTypeInfo + PyObjectAlloc<T>
T: PyTypeInfo + PyObjectAlloc<T>
{
::token::init(self, f)
Ptr::new(self, f)
}
/// Release PyObject reference

View File

@ -1,11 +1,14 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use std;
use std::rc::Rc;
use std::marker::PhantomData;
use ffi;
use err::PyResult;
use python::{Python, IntoPyPointer};
use err::{PyResult, PyErr, PyDowncastError};
use objects::PyObject;
use conversion::{ToPyObject, IntoPyObject};
use python::{Python, IntoPyPointer, ToPyPointer, PyDowncastInto};
use typeob::{PyTypeInfo, PyObjectAlloc};
@ -17,36 +20,10 @@ impl PyToken {
}
}
/// Create new python object and move T instance under python management
#[inline]
pub fn init<T, F>(py: Python, f: F) -> PyResult<T::Target>
where F: FnOnce(PyToken) -> T,
T: ToInstancePtr<T> + PyTypeInfo + PyObjectAlloc<T>
{
let ob = f(PyToken(PhantomData));
let ob = unsafe {
let ob = try!(<T as PyObjectAlloc<T>>::alloc(py, ob));
T::from_owned_ptr(ob)
};
Ok(ob)
}
pub trait PyObjectWithToken : Sized {
fn token(&self) -> Python;
}
pub trait ToInstancePtr<T> : Sized {
type Target: InstancePtr<T> + IntoPyPointer;
fn to_inst_ptr(&self) -> Self::Target;
unsafe fn from_owned_ptr(*mut ffi::PyObject) -> Self::Target;
unsafe fn from_borrowed_ptr(*mut ffi::PyObject) -> Self::Target;
}
pub trait InstancePtr<T> : Sized {
fn as_ref(&self, py: Python) -> &T;
@ -91,3 +68,222 @@ pub trait InstancePtr<T> : Sized {
result
}
}
/// Wrapper around unsafe `*mut ffi::PyObject` pointer. Decrement ref counter on `Drop`
pub struct Ptr<T>(*mut ffi::PyObject, std::marker::PhantomData<T>);
// `PyPtr` is thread-safe, because any python related operations require a Python<'p> token.
unsafe impl<T> Send for Ptr<T> {}
unsafe impl<T> Sync for Ptr<T> {}
impl<T> Ptr<T> {
/// Creates a `Ptr<T>` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `Ptr<T>`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> Ptr<T> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0,
format!("REFCNT: {:?} - {:?}", ptr, ffi::Py_REFCNT(ptr)));
Ptr(ptr, std::marker::PhantomData)
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn from_owned_ptr_or_panic(ptr: *mut ffi::PyObject) -> Ptr<T>
{
if ptr.is_null() {
::err::panic_after_error();
} else {
unsafe{ Ptr::from_owned_ptr(ptr) }
}
}
/// Construct `Ptr<T>` from the result of a Python FFI call that
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<Ptr<T>>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(unsafe{ Ptr::from_owned_ptr(ptr) })
}
}
/// Creates a `Ptr<T>` instance for the given Python FFI pointer.
/// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_borrowed_ptr(ptr: *mut ffi::PyObject) -> Ptr<T> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0,
format!("REFCNT: {:?} - {:?}", ptr, ffi::Py_REFCNT(ptr)));
ffi::Py_INCREF(ptr);
Ptr::from_owned_ptr(ptr)
}
/// Gets the reference count of the ffi::PyObject pointer.
#[inline]
pub fn get_refcnt(&self) -> isize {
unsafe { ffi::Py_REFCNT(self.0) }
}
/// Get reference to &PyObject.
#[inline]
pub fn as_object<'p>(&self, _py: Python<'p>) -> &PyObject {
unsafe { std::mem::transmute(self) }
}
/// Clone self, Calls Py_INCREF() on the ptr.
#[inline]
pub fn clone_ref(&self, _py: Python) -> Ptr<T> {
unsafe { Ptr::from_borrowed_ptr(self.0) }
}
/// Casts the `Ptr<T>` imstance to a concrete Python object type.
/// Fails with `PyDowncastError` if the object is not of the expected type.
#[inline]
pub fn cast_into<D>(self, py: Python) -> Result<D, PyDowncastError>
where D: PyDowncastInto
{
<D as PyDowncastInto>::downcast_into(py, self)
}
/// Calls `ffi::Py_DECREF` and sets ptr to null value.
#[inline]
pub unsafe fn drop_ref(&mut self) {
ffi::Py_DECREF(self.0);
self.0 = std::ptr::null_mut();
}
}
impl<T> Ptr<T> where T: PyTypeInfo,
{
/// Create new python object and move T instance under python management
pub fn new<F>(py: Python, f: F) -> PyResult<Ptr<T>>
where F: FnOnce(::PyToken) -> T,
T: PyObjectAlloc<T>
{
let ob = f(PyToken(PhantomData));
let ob = unsafe {
let ob = try!(<T as PyObjectAlloc<T>>::alloc(py, ob));
Ptr::from_owned_ptr(ob)
};
Ok(ob)
}
}
impl<T> InstancePtr<T> for Ptr<T> where T: PyTypeInfo {
#[inline]
fn as_ref(&self, _py: Python) -> &T {
let offset = <T as PyTypeInfo>::offset();
unsafe {
let ptr = (self.as_ptr() as *mut u8).offset(offset) as *mut T;
ptr.as_ref().unwrap()
}
}
#[inline]
fn as_mut(&self, _py: Python) -> &mut T {
let offset = <T as PyTypeInfo>::offset();
unsafe {
let ptr = (self.as_ptr() as *mut u8).offset(offset) as *mut T;
ptr.as_mut().unwrap()
}
}
}
impl<T> ToPyObject for Ptr<T> {
fn to_object(&self, py: Python) -> PyObject {
PyObject::from_borrowed_ptr(py, self.as_ptr())
}
}
impl<T> IntoPyObject for Ptr<T> {
/// Converts `Ptr` instance -> PyObject.
/// Consumes `self` without calling `Py_DECREF()`
#[inline]
fn into_object(self, _py: Python) -> PyObject {
unsafe { std::mem::transmute(self) }
}
}
impl<T> ToPyPointer for Ptr<T> {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.0
}
}
impl<T> IntoPyPointer for Ptr<T> {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
fn into_ptr(self) -> *mut ffi::PyObject {
let ptr = self.0;
std::mem::forget(self);
ptr
}
}
impl<T> PartialEq for Ptr<T> {
#[inline]
fn eq(&self, o: &Ptr<T>) -> bool {
self.0 == o.0
}
}
/// Dropping a `PyPtr` instance decrements the reference count on the object by 1.
impl<T> Drop for Ptr<T> {
fn drop(&mut self) {
if !self.0.is_null() {
let _gil_guard = Python::acquire_gil();
unsafe { ffi::Py_DECREF(self.0); }
}
}
}
impl<T> std::convert::From<Ptr<T>> for PyObject {
fn from(ob: Ptr<T>) -> Self {
unsafe{std::mem::transmute(ob)}
}
}
impl<'a, T> std::convert::From<&'a T> for Ptr<T>
where T: ToPyPointer
{
fn from(ob: &'a T) -> Self {
unsafe { Ptr::from_borrowed_ptr(ob.as_ptr()) }
}
}
impl<'a, T> std::convert::From<&'a mut T> for Ptr<T>
where T: ToPyPointer
{
fn from(ob: &'a mut T) -> Self {
unsafe { Ptr::from_borrowed_ptr(ob.as_ptr()) }
}
}
impl<'a, T> std::convert::From<&'a T> for PyObject
where T: ToPyPointer,
{
fn from(ob: &'a T) -> Self {
unsafe { Ptr::<T>::from_borrowed_ptr(ob.as_ptr()) }.into()
}
}
impl<'a, T> std::convert::From<&'a mut T> for PyObject
where T: ToPyPointer,
{
fn from(ob: &'a mut T) -> Self {
unsafe { Ptr::<T>::from_borrowed_ptr(ob.as_ptr()) }.into()
}
}

View File

@ -14,8 +14,6 @@ struct TestClass {
vec: Vec<u8>,
token: PyToken,
}
#[py::ptr(TestClass)]
struct TestClassPtr(PyPtr);
#[py::proto]
impl class::PyBufferProtocol for TestClass {

View File

@ -96,14 +96,11 @@ struct EmptyClassWithNew {
token: PyToken
}
#[py::ptr(EmptyClassWithNew)]
struct EmptyClassWithNewPtr(PyPtr);
#[py::methods]
impl EmptyClassWithNew {
#[__new__]
fn __new__(cls: &PyType, py: Python) -> PyResult<EmptyClassWithNewPtr> {
py.init(|t| EmptyClassWithNew{token: t})
fn __new__(cls: &PyType, py: Python) -> PyResult<Ptr<EmptyClassWithNew>> {
Ptr::new(py, |t| EmptyClassWithNew{token: t})
}
}
@ -121,14 +118,11 @@ struct NewWithOneArg {
token: PyToken
}
#[py::ptr(NewWithOneArg)]
struct NewWithOneArgPtr(PyPtr);
#[py::methods]
impl NewWithOneArg {
#[new]
fn __new__(_cls: &PyType, py: Python, arg: i32) -> PyResult<NewWithOneArgPtr> {
py.init(|t| NewWithOneArg{_data: arg, token: t})
fn __new__(_cls: &PyType, py: Python, arg: i32) -> PyResult<Ptr<NewWithOneArg>> {
Ptr::new(py, |t| NewWithOneArg{_data: arg, token: t})
}
}
@ -150,14 +144,12 @@ struct NewWithTwoArgs {
token: PyToken
}
#[py::ptr(NewWithTwoArgs)]
struct NewWithTwoArgsPtr(PyPtr);
#[py::methods]
impl NewWithTwoArgs {
#[new]
fn __new__(_cls: &PyType, py: Python, arg1: i32, arg2: i32) -> PyResult<NewWithTwoArgsPtr> {
py.init(|t| NewWithTwoArgs{_data1: arg1, _data2: arg2, token: t})
fn __new__(_cls: &PyType, py: Python, arg1: i32, arg2: i32) -> PyResult<Ptr<NewWithTwoArgs>>
{
Ptr::new(py, |t| NewWithTwoArgs{_data1: arg1, _data2: arg2, token: t})
}
}
@ -175,20 +167,17 @@ fn new_with_two_args() {
#[py::class(freelist=10)]
struct ClassWithFreelist{token: PyToken}
#[py::ptr(ClassWithFreelist)]
struct ClassWithFreelistPtr(PyPtr);
#[test]
fn class_with_freelist() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = py.init(|t| ClassWithFreelist{token: t}).unwrap();
let inst2 = py.init(|t| ClassWithFreelist{token: t}).unwrap();
let inst = Ptr::new(py, |t| ClassWithFreelist{token: t}).unwrap();
let inst2 = Ptr::new(py, |t| ClassWithFreelist{token: t}).unwrap();
let ptr = inst.as_ptr();
drop(inst);
let inst3 = py.init(|t| ClassWithFreelist{token: t}).unwrap();
let inst3 = Ptr::new(py, |t| ClassWithFreelist{token: t}).unwrap();
assert_eq!(ptr, inst3.as_ptr());
}
@ -207,8 +196,6 @@ struct DataIsDropped {
member2: TestDropCall,
token: PyToken,
}
#[py::ptr(DataIsDropped)]
struct DataIsDroppedPtr(PyPtr);
#[test]
fn data_is_dropped() {
@ -217,7 +204,7 @@ fn data_is_dropped() {
let drop_called1 = Arc::new(AtomicBool::new(false));
let drop_called2 = Arc::new(AtomicBool::new(false));
let inst = py.init(|t| DataIsDropped{
let inst = Ptr::new(py, |t| DataIsDropped{
member1: TestDropCall { drop_called: drop_called1.clone() },
member2: TestDropCall { drop_called: drop_called2.clone() },
token: t
@ -235,8 +222,6 @@ struct InstanceMethod {
member: i32,
token: PyToken
}
#[py::ptr(InstanceMethod)]
struct InstanceMethodPtr(PyPtr);
#[py::methods]
impl InstanceMethod {
@ -251,7 +236,7 @@ fn instance_method() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = py.init(|t| InstanceMethod{member: 42, token: t}).unwrap();
let obj = Ptr::new(py, |t| InstanceMethod{member: 42, token: t}).unwrap();
assert!(obj.as_ref(py).method(py).unwrap() == 42);
let d = PyDict::new(py);
d.set_item(py, "obj", obj).unwrap();
@ -264,8 +249,6 @@ struct InstanceMethodWithArgs {
member: i32,
token: PyToken
}
#[py::ptr(InstanceMethodWithArgs)]
struct InstanceMethodWithArgsPtr(PyPtr);
#[py::methods]
impl InstanceMethodWithArgs {
@ -279,7 +262,7 @@ fn instance_method_with_args() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = py.init(|t| InstanceMethodWithArgs{member: 7, token: t}).unwrap();
let obj = Ptr::new(py, |t| InstanceMethodWithArgs{member: 7, token: t}).unwrap();
assert!(obj.as_ref(py).method(py, 6).unwrap() == 42);
let d = PyDict::new(py);
d.set_item(py, "obj", obj).unwrap();
@ -291,14 +274,11 @@ fn instance_method_with_args() {
#[py::class]
struct ClassMethod {token: PyToken}
#[py::ptr(ClassMethod)]
struct ClassMethodPtr(PyPtr);
#[py::methods]
impl ClassMethod {
#[new]
fn __new__(cls: &PyType, py: Python) -> PyResult<ClassMethodPtr> {
py.init(|t| ClassMethod{token: t})
fn __new__(cls: &PyType, py: Python) -> PyResult<Ptr<ClassMethod>> {
Ptr::new(py, |t| ClassMethod{token: t})
}
#[classmethod]
@ -322,9 +302,6 @@ fn class_method() {
#[py::class]
struct ClassMethodWithArgs{token: PyToken}
#[py::ptr(ClassMethodWithArgs)]
struct ClassMethodWithArgsPtr(PyPtr);
#[py::methods]
impl ClassMethodWithArgs {
#[classmethod]
@ -348,14 +325,11 @@ struct StaticMethod {
token: PyToken
}
#[py::ptr(StaticMethod)]
struct StaticMethodPtr(PyPtr);
#[py::methods]
impl StaticMethod {
#[new]
fn __new__(cls: &PyType, py: Python) -> PyResult<StaticMethodPtr> {
py.init(|t| StaticMethod{token: t})
fn __new__(cls: &PyType, py: Python) -> PyResult<Ptr<StaticMethod>> {
Ptr::new(py, |t| StaticMethod{token: t})
}
#[staticmethod]
@ -379,9 +353,6 @@ fn static_method() {
#[py::class]
struct StaticMethodWithArgs{token: PyToken}
#[py::ptr(StaticMethodWithArgs)]
struct StaticMethodWithArgsPtr(PyPtr);
#[py::methods]
impl StaticMethodWithArgs {
@ -410,9 +381,6 @@ struct GCIntegration {
token: PyToken,
}
#[py::ptr(GCIntegration)]
struct GCIntegrationPtr(PyPtr);
#[py::proto]
impl PyGCProtocol for GCIntegration {
fn __traverse__(&self, py: Python, visit: PyVisit) -> Result<(), PyTraverseError> {
@ -430,7 +398,7 @@ fn gc_integration() {
let py = gil.python();
let drop_called = Arc::new(AtomicBool::new(false));
let inst = py.init(|t| GCIntegration{
let inst = Ptr::new(py, |t| GCIntegration{
self_ref: RefCell::new(py.None()),
dropped: TestDropCall { drop_called: drop_called.clone() },
token: t}).unwrap();
@ -448,9 +416,6 @@ pub struct Len {
token: PyToken,
}
#[py::ptr(Len)]
pub struct LenPtr(PyPtr);
#[py::proto]
impl PyMappingProtocol for Len {
fn __len__(&self, py: Python) -> PyResult<usize> {
@ -463,14 +428,14 @@ fn len() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = py.init(|t| Len{l: 10, token: t}).unwrap();
let inst = Ptr::new(py, |t| Len{l: 10, token: t}).unwrap();
py_assert!(py, inst, "len(inst) == 10");
unsafe {
assert_eq!(ffi::PyObject_Size(inst.as_ptr()), 10);
assert_eq!(ffi::PyMapping_Size(inst.as_ptr()), 10);
}
let inst = py.init(|t| Len{l: (isize::MAX as usize) + 1, token: t}).unwrap();
let inst = Ptr::new(py, |t| Len{l: (isize::MAX as usize) + 1, token: t}).unwrap();
py_expect_exception!(py, inst, "len(inst)", OverflowError);
}
@ -480,13 +445,10 @@ struct Iterator{
token: PyToken,
}
#[py::ptr(Iterator)]
struct IteratorPtr(PyPtr);
#[py::proto]
impl PyIterProtocol for Iterator {
fn __iter__(&mut self, py: Python) -> PyResult<IteratorPtr> {
Ok(self.to_inst_ptr())
fn __iter__(&mut self, py: Python) -> PyResult<Ptr<Iterator>> {
Ok(self.into())
}
fn __next__(&mut self, py: Python) -> PyResult<Option<i32>> {
@ -499,7 +461,7 @@ fn iterator() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = py.init(|t| Iterator{iter: Box::new(5..8), token: t}).unwrap();
let inst = Ptr::new(py, |t| Iterator{iter: Box::new(5..8), token: t}).unwrap();
py_assert!(py, inst, "iter(inst) is inst");
py_assert!(py, inst, "list(inst) == [5, 6, 7]");
}
@ -507,9 +469,6 @@ fn iterator() {
#[py::class]
struct StringMethods {token: PyToken}
#[py::ptr(StringMethods)]
struct StringMethodsPtr(PyPtr);
#[py::proto]
impl<'p> PyObjectProtocol<'p> for StringMethods {
fn __str__(&self, py: Python) -> PyResult<&'static str> {
@ -539,7 +498,7 @@ fn string_methods() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = py.init(|t| StringMethods{token: t}).unwrap();
let obj = Ptr::new(py, |t| StringMethods{token: t}).unwrap();
py_assert!(py, obj, "str(obj) == 'str'");
py_assert!(py, obj, "repr(obj) == 'repr'");
py_assert!(py, obj, "'{0:x}'.format(obj) == 'format(x)'");
@ -552,7 +511,7 @@ fn string_methods() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = py.init(|t| StringMethods{token: t}).unwrap();
let obj = Ptr::new(py, |t| StringMethods{token: t}).unwrap();
py_assert!(py, obj, "str(obj) == 'str'");
py_assert!(py, obj, "repr(obj) == 'repr'");
py_assert!(py, obj, "unicode(obj) == 'unicode'");
@ -566,9 +525,6 @@ struct Comparisons {
token: PyToken,
}
#[py::ptr(Comparisons)]
struct ComparisonsPtr(PyPtr);
#[py::proto]
impl PyObjectProtocol for Comparisons {
fn __hash__(&self, py: Python) -> PyResult<usize> {
@ -585,10 +541,10 @@ fn comparisons() {
let gil = Python::acquire_gil();
let py = gil.python();
let zero = py.init(|t| Comparisons{val: 0, token: t}).unwrap();
let one = py.init(|t| Comparisons{val: 1, token: t}).unwrap();
let ten = py.init(|t| Comparisons{val: 10, token: t}).unwrap();
let minus_one = py.init(|t| Comparisons{val: -1, token: t}).unwrap();
let zero = Ptr::new(py, |t| Comparisons{val: 0, token: t}).unwrap();
let one = Ptr::new(py, |t| Comparisons{val: 1, token: t}).unwrap();
let ten = Ptr::new(py, |t| Comparisons{val: 10, token: t}).unwrap();
let minus_one = Ptr::new(py, |t| Comparisons{val: -1, token: t}).unwrap();
py_assert!(py, one, "hash(one) == 1");
py_assert!(py, ten, "hash(ten) == 10");
py_assert!(py, minus_one, "hash(minus_one) == -2");
@ -603,9 +559,6 @@ struct Sequence {
token: PyToken
}
#[py::ptr(Sequence)]
struct SequencePtr(PyPtr);
#[py::proto]
impl PySequenceProtocol for Sequence {
fn __len__(&self, py: Python) -> PyResult<usize> {
@ -634,9 +587,6 @@ fn sequence() {
#[py::class]
struct Callable {token: PyToken}
#[py::ptr(Callable)]
struct CallablePtr(PyPtr);
#[py::methods]
impl Callable {
@ -666,9 +616,6 @@ struct SetItem {
token: PyToken,
}
#[py::ptr(SetItem)]
struct SetItemPtr(PyPtr);
#[py::proto]
impl PyMappingProtocol<'a> for SetItem {
fn __setitem__(&mut self, py: Python, key: i32, val: i32) -> PyResult<()> {
@ -696,9 +643,6 @@ struct DelItem {
token: PyToken,
}
#[py::ptr(DelItem)]
struct DelItemPtr(PyPtr);
#[py::proto]
impl PyMappingProtocol<'a> for DelItem {
fn __delitem__(&mut self, py: Python, key: i32) -> PyResult<()> {
@ -724,9 +668,6 @@ struct SetDelItem {
token: PyToken,
}
#[py::ptr(SetDelItem)]
struct SetDelItemPtr(PyPtr);
#[py::proto]
impl PyMappingProtocol for SetDelItem {
fn __setitem__(&mut self, py: Python, key: i32, val: i32) -> PyResult<()> {
@ -755,9 +696,6 @@ fn setdelitem() {
#[py::class]
struct Reversed {token: PyToken}
#[py::ptr(Reversed)]
struct ReversedPtr(PyPtr);
#[py::proto]
impl PyMappingProtocol for Reversed{
fn __reversed__(&self, py: Python) -> PyResult<&'static str> {
@ -777,9 +715,6 @@ fn reversed() {
#[py::class]
struct Contains {token: PyToken}
#[py::ptr(Contains)]
struct ContainsPtr(PyPtr);
#[py::proto]
impl PySequenceProtocol for Contains {
fn __contains__(&self, py: Python, item: i32) -> PyResult<bool> {
@ -803,9 +738,6 @@ fn contains() {
#[py::class]
struct UnaryArithmetic {token: PyToken}
#[py::ptr(UnaryArithmetic)]
struct UnaryArithmeticPtr(PyPtr);
#[py::proto]
impl PyNumberProtocol for UnaryArithmetic {
@ -844,9 +776,6 @@ struct BinaryArithmetic {
token: PyToken
}
#[py::ptr(BinaryArithmetic)]
struct BinaryArithmeticPtr(PyPtr);
#[py::proto]
impl PyObjectProtocol for BinaryArithmetic {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
@ -921,9 +850,6 @@ struct RichComparisons {
token: PyToken
}
#[py::ptr(RichComparisons)]
struct RichComparisonsPtr(PyPtr);
#[py::proto]
impl PyObjectProtocol for RichComparisons {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
@ -947,9 +873,6 @@ struct RichComparisons2 {
py: PyToken
}
#[py::ptr(RichComparisons2)]
struct RichComparisons2Ptr(PyPtr);
#[py::proto]
impl PyObjectProtocol for RichComparisons2 {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
@ -1025,9 +948,6 @@ struct InPlaceOperations {
token: PyToken,
}
#[py::ptr(InPlaceOperations)]
struct InPlaceOperationsPtr(PyPtr);
#[py::proto]
impl PyObjectProtocol for InPlaceOperations {
fn __repr__(&self, py: Python) -> PyResult<String> {
@ -1114,9 +1034,6 @@ struct ContextManager {
token: PyToken,
}
#[py::ptr(ContextManager)]
struct ContextManagerPtr(PyPtr);
#[py::proto]
impl<'p> PyContextProtocol<'p> for ContextManager {
@ -1163,9 +1080,6 @@ struct ClassWithProperties {
token: PyToken,
}
#[py::ptr(ClassWithProperties)]
struct ClassWithPropertiesPtr(PyPtr);
#[py::methods]
impl ClassWithProperties {

View File

@ -24,8 +24,6 @@ fn test_basics() {
struct Test {
token: PyToken
}
#[py::ptr(Test)]
struct TestPtr(PyPtr);
#[py::proto]
impl<'p> PyMappingProtocol<'p> for Test