refactor IntoPyObject trait; rename pptr into pyptr, introduce pptr pointers

This commit is contained in:
Nikolay Kim 2017-05-30 16:29:13 -07:00
parent 3b90c569f7
commit b8913a3705
38 changed files with 485 additions and 254 deletions

View file

@ -24,7 +24,7 @@ use libc;
use ffi; use ffi;
use exc; use exc;
use err::{self, PyResult}; use err::{self, PyResult};
use pyptr::{Py}; use pointers::{Py};
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use objects::PyObject; use objects::PyObject;

View file

@ -4,7 +4,7 @@ use std::os::raw::c_int;
use std::{any, mem, ptr, isize, io, panic}; use std::{any, mem, ptr, isize, io, panic};
use libc; use libc;
use pyptr::Py; use pointers::Py;
use python::{Python, IntoPythonPointer}; use python::{Python, IntoPythonPointer};
use objects::exc; use objects::exc;
use conversion::IntoPyObject; use conversion::IntoPyObject;

View file

@ -39,22 +39,22 @@ pub trait PyAsyncProtocol<'p>: PyTypeInfo + Sized + 'static {
pub trait PyAsyncAwaitProtocol<'p>: PyAsyncProtocol<'p> { pub trait PyAsyncAwaitProtocol<'p>: PyAsyncProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyAsyncAiterProtocol<'p>: PyAsyncProtocol<'p> { pub trait PyAsyncAiterProtocol<'p>: PyAsyncProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyAsyncAnextProtocol<'p>: PyAsyncProtocol<'p> { pub trait PyAsyncAnextProtocol<'p>: PyAsyncProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyAsyncAenterProtocol<'p>: PyAsyncProtocol<'p> { pub trait PyAsyncAenterProtocol<'p>: PyAsyncProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -62,7 +62,7 @@ pub trait PyAsyncAexitProtocol<'p>: PyAsyncProtocol<'p> {
type ExcType: ::FromPyObject<'p>; type ExcType: ::FromPyObject<'p>;
type ExcValue: ::FromPyObject<'p>; type ExcValue: ::FromPyObject<'p>;
type Traceback: ::FromPyObject<'p>; type Traceback: ::FromPyObject<'p>;
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -15,7 +15,7 @@ use python::{Python, IntoPythonPointer};
use objects::PyObject; use objects::PyObject;
use objects::exc; use objects::exc;
use typeob::PyTypeInfo; use typeob::PyTypeInfo;
use conversion::{ToPyObject, FromPyObject, IntoPyObject}; use conversion::{FromPyObject, IntoPyObject};
use callback::{PyObjectCallbackConverter, HashConverter, BoolCallbackConverter}; use callback::{PyObjectCallbackConverter, HashConverter, BoolCallbackConverter};
use class::methods::PyMethodDef; use class::methods::PyMethodDef;
@ -63,7 +63,7 @@ pub trait PyObjectProtocol<'p>: PyTypeInfo + Sized + 'static {
pub trait PyObjectGetAttrProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectGetAttrProtocol<'p>: PyObjectProtocol<'p> {
type Name: FromPyObject<'p>; type Name: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyObjectSetAttrProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectSetAttrProtocol<'p>: PyObjectProtocol<'p> {
@ -76,16 +76,16 @@ pub trait PyObjectDelAttrProtocol<'p>: PyObjectProtocol<'p> {
type Result: Into<PyResult<()>>; type Result: Into<PyResult<()>>;
} }
pub trait PyObjectStrProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectStrProtocol<'p>: PyObjectProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyObjectReprProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectReprProtocol<'p>: PyObjectProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyObjectFormatProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectFormatProtocol<'p>: PyObjectProtocol<'p> {
type Format: FromPyObject<'p>; type Format: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyObjectHashProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectHashProtocol<'p>: PyObjectProtocol<'p> {
@ -95,12 +95,12 @@ pub trait PyObjectBoolProtocol<'p>: PyObjectProtocol<'p> {
type Result: Into<PyResult<bool>>; type Result: Into<PyResult<bool>>;
} }
pub trait PyObjectBytesProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectBytesProtocol<'p>: PyObjectProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyObjectRichcmpProtocol<'p>: PyObjectProtocol<'p> { pub trait PyObjectRichcmpProtocol<'p>: PyObjectProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -396,7 +396,6 @@ fn extract_op(py: Python, op: c_int) -> PyResult<CompareOp> {
ffi::Py_GE => Ok(CompareOp::Ge), ffi::Py_GE => Ok(CompareOp::Ge),
_ => Err(PyErr::new_lazy_init( _ => Err(PyErr::new_lazy_init(
py.get_type::<exc::ValueError>(), py.get_type::<exc::ValueError>(),
Some("tp_richcompare called with invalid comparison operator" Some("tp_richcompare called with invalid comparison operator".into_object(py))))
.to_object(py))))
} }
} }

View file

@ -25,7 +25,7 @@ pub trait PyContextProtocol<'p>: PyTypeInfo {
} }
pub trait PyContextEnterProtocol<'p>: PyContextProtocol<'p> { pub trait PyContextEnterProtocol<'p>: PyContextProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -33,7 +33,7 @@ pub trait PyContextExitProtocol<'p>: PyContextProtocol<'p> {
type ExcType: ::FromPyObject<'p>; type ExcType: ::FromPyObject<'p>;
type ExcValue: ::FromPyObject<'p>; type ExcValue: ::FromPyObject<'p>;
type Traceback: ::FromPyObject<'p>; type Traceback: ::FromPyObject<'p>;
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -14,7 +14,7 @@ use objects::{PyType, PyObject};
use callback::{PyObjectCallbackConverter, UnitCallbackConverter}; use callback::{PyObjectCallbackConverter, UnitCallbackConverter};
use typeob::PyTypeInfo; use typeob::PyTypeInfo;
use class::methods::PyMethodDef; use class::methods::PyMethodDef;
use conversion::{ToPyObject, FromPyObject}; use conversion::{IntoPyObject, FromPyObject};
/// Descriptor interface /// Descriptor interface
@ -37,7 +37,7 @@ pub trait PyDescrProtocol<'p>: PyTypeInfo {
pub trait PyDescrGetProtocol<'p>: PyDescrProtocol<'p> { pub trait PyDescrGetProtocol<'p>: PyDescrProtocol<'p> {
type Inst: FromPyObject<'p>; type Inst: FromPyObject<'p>;
type Owner: FromPyObject<'p>; type Owner: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -7,7 +7,7 @@ use std::mem;
use std::os::raw::{c_int, c_void}; use std::os::raw::{c_int, c_void};
use ffi; use ffi;
use pyptr::Py; use pointers::Py;
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use callback::AbortOnDrop; use callback::AbortOnDrop;
use typeob::PyTypeInfo; use typeob::PyTypeInfo;

View file

@ -25,12 +25,12 @@ pub trait PyIterProtocol<'p> : PyTypeInfo {
} }
pub trait PyIterIterProtocol<'p>: PyIterProtocol<'p> { pub trait PyIterIterProtocol<'p>: PyIterProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyIterNextProtocol<'p>: PyIterProtocol<'p> { pub trait PyIterNextProtocol<'p>: PyIterProtocol<'p> {
type Success: ::ToPyObject; type Success: ::IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -9,7 +9,7 @@ use python::Python;
use objects::exc; use objects::exc;
use objects::PyObject; use objects::PyObject;
use callback::{PyObjectCallbackConverter, LenResultConverter}; use callback::{PyObjectCallbackConverter, LenResultConverter};
use conversion::{ToPyObject, FromPyObject}; use conversion::{IntoPyObject, FromPyObject};
use typeob::PyTypeInfo; use typeob::PyTypeInfo;
use class::methods::PyMethodDef; use class::methods::PyMethodDef;
@ -51,7 +51,7 @@ pub trait PyMappingLenProtocol<'p>: PyMappingProtocol<'p> {
pub trait PyMappingGetItemProtocol<'p>: PyMappingProtocol<'p> { pub trait PyMappingGetItemProtocol<'p>: PyMappingProtocol<'p> {
type Key: FromPyObject<'p>; type Key: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -67,7 +67,7 @@ pub trait PyMappingDelItemProtocol<'p>: PyMappingProtocol<'p> {
} }
pub trait PyMappingIterProtocol<'p>: PyMappingProtocol<'p> { pub trait PyMappingIterProtocol<'p>: PyMappingProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -77,7 +77,7 @@ pub trait PyMappingContainsProtocol<'p>: PyMappingProtocol<'p> {
} }
pub trait PyMappingReversedProtocol<'p>: PyMappingProtocol<'p> { pub trait PyMappingReversedProtocol<'p>: PyMappingProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -10,7 +10,7 @@ use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo; use typeob::PyTypeInfo;
use class::methods::PyMethodDef; use class::methods::PyMethodDef;
use class::basic::PyObjectProtocolImpl; use class::basic::PyObjectProtocolImpl;
use ::{c_void, ToPyObject, IntoPyObject, FromPyObject}; use ::{c_void, IntoPyObject, FromPyObject};
/// Number interface /// Number interface
#[allow(unused_variables)] #[allow(unused_variables)]
@ -125,12 +125,12 @@ pub trait PyNumberProtocol<'p>: PyTypeInfo {
pub trait PyNumberAddProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberAddProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberSubProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberSubProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> {
@ -140,131 +140,131 @@ pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> {
} }
pub trait PyNumberMatmulProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberMatmulProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberTruedivProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberTruedivProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberFloordivProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberFloordivProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberModProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberModProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberDivmodProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberDivmodProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberPowProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberPowProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Modulo: FromPyObject<'p>; type Modulo: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberLShiftProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberLShiftProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRShiftProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRShiftProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberAndProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberAndProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberXorProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberXorProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberOrProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberOrProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRAddProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRAddProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRSubProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRSubProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRMulProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRMulProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRMatmulProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRMatmulProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRTruedivProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRTruedivProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRFloordivProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRFloordivProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRModProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRModProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRDivmodProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRDivmodProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRPowProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRPowProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Modulo: FromPyObject<'p>; type Modulo: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRLShiftProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRLShiftProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRRShiftProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRRShiftProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRAndProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRAndProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRXorProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRXorProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberROrProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberROrProtocol<'p>: PyNumberProtocol<'p> {
type Other: FromPyObject<'p>; type Other: FromPyObject<'p>;
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
@ -327,39 +327,39 @@ pub trait PyNumberIOrProtocol<'p>: PyNumberProtocol<'p> {
} }
pub trait PyNumberNegProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberNegProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberPosProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberPosProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberAbsProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberAbsProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberInvertProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberInvertProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberComplexProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberComplexProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberIntProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberIntProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberFloatProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberFloatProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberRoundProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberRoundProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }
pub trait PyNumberIndexProtocol<'p>: PyNumberProtocol<'p> { pub trait PyNumberIndexProtocol<'p>: PyNumberProtocol<'p> {
type Success: ToPyObject; type Success: IntoPyObject;
type Result: Into<PyResult<Self::Success>>; type Result: Into<PyResult<Self::Success>>;
} }

View file

@ -1,6 +1,6 @@
use ffi; use ffi;
use err::PyResult; use err::PyResult;
use pyptr::PyPtr; use pointers::{pptr, PyPtr};
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use objects::{PyObject, PyTuple}; use objects::{PyObject, PyTuple};
use token::PyObjectMarker; use token::PyObjectMarker;
@ -30,7 +30,7 @@ pub trait IntoPyObject {
/// Converts self into a Python object. (Consumes self) /// Converts self into a Python object. (Consumes self)
#[inline] #[inline]
fn into_object(self, py: Python) -> PyPtr<PyObjectMarker> fn into_object(self, py: Python) -> pptr
where Self: Sized; where Self: Sized;
} }
@ -101,9 +101,9 @@ impl <'p, T: ?Sized> RefFromPyObject<'p> for T
impl<T> IntoPyObject for T where T: ToPyObject impl<T> IntoPyObject for T where T: ToPyObject
{ {
#[inline] #[inline]
default fn into_object(self, py: Python) -> PyPtr<PyObjectMarker> default fn into_object(self, py: Python) -> pptr
{ {
self.to_object(py) self.to_object(py).park()
} }
} }
@ -132,14 +132,14 @@ impl <T> ToPyObject for Option<T> where T: ToPyObject {
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
match *self { match *self {
Some(ref val) => val.to_object(py), Some(ref val) => val.to_object(py),
None => py.None() None => py.None().into_pobject(),
} }
} }
} }
impl<T> IntoPyObject for Option<T> where T: IntoPyObject { impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
fn into_object(self, py: Python) -> PyPtr<PyObjectMarker> { fn into_object(self, py: Python) -> pptr {
match self { match self {
Some(val) => val.into_object(py), Some(val) => val.into_object(py),
None => py.None() None => py.None()
@ -151,7 +151,7 @@ impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
/// `()` is converted to Python `None`. /// `()` is converted to Python `None`.
impl ToPyObject for () { impl ToPyObject for () {
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
py.None() py.None().into_pobject()
} }
} }

View file

@ -4,13 +4,13 @@ use std::os::raw::c_char;
use libc; use libc;
use ffi; use ffi;
use pyptr::{PyPtr}; use pointers::{pptr, PyPtr};
use python::{ToPythonPointer, IntoPythonPointer, Python}; use python::{ToPythonPointer, IntoPythonPointer, Python};
use objects::{PyObject, PyType, exc}; use objects::{PyObject, PyType, exc};
use native::PyNativeObject; use native::PyNativeObject;
use token::PyObjectMarker; use token::PyObjectMarker;
use typeob::{PyTypeObject}; use typeob::{PyTypeObject};
use conversion::{ToPyObject, ToPyTuple}; use conversion::{ToPyObject, ToPyTuple, IntoPyObject};
/** /**
Defines a new exception type. Defines a new exception type.
@ -83,16 +83,16 @@ macro_rules! py_exception {
#[derive(Debug)] #[derive(Debug)]
pub struct PyErr { pub struct PyErr {
/// The type of the exception. This should be either a `PyClass` or a `PyType`. /// The type of the exception. This should be either a `PyClass` or a `PyType`.
pub ptype: PyPtr<PyObjectMarker>, pub ptype: pptr,
/// The value of the exception. /// The value of the exception.
/// ///
/// This can be either an instance of `ptype`, /// This can be either an instance of `ptype`,
/// a tuple of arguments to be passed to `ptype`'s constructor, /// a tuple of arguments to be passed to `ptype`'s constructor,
/// or a single argument to be passed to `ptype`'s constructor. /// or a single argument to be passed to `ptype`'s constructor.
/// Call `PyErr::instance()` to get the exception instance in all cases. /// Call `PyErr::instance()` to get the exception instance in all cases.
pub pvalue: Option<PyPtr<PyObjectMarker>>, pub pvalue: Option<pptr>,
/// The `PyTraceBack` object associated with the error. /// The `PyTraceBack` object associated with the error.
pub ptraceback: Option<PyPtr<PyObjectMarker>>, pub ptraceback: Option<pptr>,
} }
@ -119,7 +119,7 @@ impl PyErr {
pub fn new<T, V>(py: Python, value: V) -> PyErr pub fn new<T, V>(py: Python, value: V) -> PyErr
where T: PyTypeObject, V: ToPyObject where T: PyTypeObject, V: ToPyObject
{ {
PyErr::new_helper(py, py.get_type::<T>().into_object(), value.to_object(py)) PyErr::new_helper(py, py.get_type::<T>().park(), value.to_object(py))
} }
/// Gets whether an error is present in the Python interpreter's global state. /// Gets whether an error is present in the Python interpreter's global state.
@ -175,20 +175,20 @@ impl PyErr {
// and because we mustn't panic in normalize(). // and because we mustn't panic in normalize().
PyErr { PyErr {
ptype: if ptype.is_null() { ptype: if ptype.is_null() {
py.get_type::<exc::SystemError>().into_object() py.get_type::<exc::SystemError>().park()
} else { } else {
PyPtr::<PyObjectMarker>::from_owned_ptr(ptype).park() pptr::from_owned_ptr(ptype)
}, },
pvalue: PyPtr::from_owned_ptr_or_opt(py, pvalue), pvalue: pptr::from_owned_ptr_or_opt(pvalue),
ptraceback: PyPtr::from_owned_ptr_or_opt(py, ptraceback) ptraceback: pptr::from_owned_ptr_or_opt(ptraceback)
} }
} }
fn new_helper(_py: Python, ty: PyPtr<PyObjectMarker>, value: PyPtr<PyObjectMarker>) -> PyErr { fn new_helper(_py: Python, ty: pptr, value: PyPtr<PyObjectMarker>) -> PyErr {
assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } != 0); assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } != 0);
PyErr { PyErr {
ptype: ty, ptype: ty,
pvalue: Some(value), pvalue: Some(value.park()),
ptraceback: None ptraceback: None
} }
} }
@ -205,21 +205,21 @@ impl PyErr {
fn from_instance_helper<'p>(py: Python, obj: PyPtr<PyObjectMarker>) -> PyErr { fn from_instance_helper<'p>(py: Python, obj: PyPtr<PyObjectMarker>) -> PyErr {
if unsafe { ffi::PyExceptionInstance_Check(obj.as_ptr()) } != 0 { if unsafe { ffi::PyExceptionInstance_Check(obj.as_ptr()) } != 0 {
PyErr { PyErr {
ptype: unsafe { PyPtr::<PyObjectMarker>::from_borrowed_ptr( ptype: unsafe { pptr::from_borrowed_ptr(
ffi::PyExceptionInstance_Class(obj.as_ptr())) }, ffi::PyExceptionInstance_Class(obj.as_ptr())) },
pvalue: Some(obj), pvalue: Some(obj.park()),
ptraceback: None ptraceback: None
} }
} else if unsafe { ffi::PyExceptionClass_Check(obj.as_ptr()) } != 0 { } else if unsafe { ffi::PyExceptionClass_Check(obj.as_ptr()) } != 0 {
PyErr { PyErr {
ptype: unsafe { PyPtr::<PyObjectMarker>::unchecked_downcast_from(obj) }, ptype: obj.park(),
pvalue: None, pvalue: None,
ptraceback: None ptraceback: None
} }
} else { } else {
PyErr { PyErr {
ptype: py.get_type::<exc::TypeError>().into_object(), ptype: py.get_type::<exc::TypeError>().park(),
pvalue: Some("exceptions must derive from BaseException".to_object(py)), pvalue: Some("exceptions must derive from BaseException".into_object(py)),
ptraceback: None ptraceback: None
} }
} }
@ -229,9 +229,9 @@ impl PyErr {
/// `exc` is the exception type; usually one of the standard exceptions like `py.get_type::<exc::RuntimeError>()`. /// `exc` is the exception type; usually one of the standard exceptions like `py.get_type::<exc::RuntimeError>()`.
/// `value` is the exception instance, or a tuple of arguments to pass to the exception constructor. /// `value` is the exception instance, or a tuple of arguments to pass to the exception constructor.
#[inline] #[inline]
pub fn new_lazy_init<'p>(exc: PyType<'p>, value: Option<PyPtr<PyObjectMarker>>) -> PyErr { pub fn new_lazy_init<'p>(exc: PyType<'p>, value: Option<pptr>) -> PyErr {
PyErr { PyErr {
ptype: exc.into_object(), ptype: exc.park(),
pvalue: value, pvalue: value,
ptraceback: None ptraceback: None
} }
@ -246,8 +246,8 @@ impl PyErr {
{ {
let pval = args.to_py_tuple(py); let pval = args.to_py_tuple(py);
PyErr { PyErr {
ptype: exc.into_object(), ptype: exc.park(),
pvalue: Some(pval.into_object()), pvalue: Some(pval.park()),
ptraceback: None ptraceback: None
} }
} }
@ -309,8 +309,8 @@ impl PyErr {
pub fn instance<'p>(&mut self, py: Python<'p>) -> PyObject<'p> { pub fn instance<'p>(&mut self, py: Python<'p>) -> PyObject<'p> {
self.normalize(py); self.normalize(py);
match self.pvalue { match self.pvalue {
Some(ref instance) => instance.as_ref(py).into_pyobject(), Some(ref instance) => instance.as_object(py).clone_object(),
None => py.None().as_ref(py).into_pyobject(), None => py.None().as_object(py).clone_object(),
} }
} }

View file

@ -19,7 +19,7 @@
use std::ptr; use std::ptr;
use ffi; use ffi;
use pyptr::Py; use pointers::Py;
use python::Python; use python::Python;
use objects::PyObject; use objects::PyObject;

View file

@ -64,11 +64,11 @@ pub use pyo3cls::*;
pub mod ffi; pub mod ffi;
pub use ffi::{Py_ssize_t, Py_hash_t}; pub use ffi::{Py_ssize_t, Py_hash_t};
pub mod pyptr; pub mod pointers;
pub use pyptr::{Py, PyPtr}; pub use pointers::{Py, PyPtr, pptr};
mod ppptr; mod ppptr;
pub use ppptr::pptr; pub use ppptr::{pyptr};
mod token; mod token;
pub use token::{PyObjectMarker, PythonToken, PythonObjectWithToken, PythonObjectWithGilToken}; pub use token::{PyObjectMarker, PythonToken, PythonObjectWithToken, PythonObjectWithGilToken};

View file

@ -1,6 +1,6 @@
// Copyright (c) 2017-present PyO3 Project and Contributors // Copyright (c) 2017-present PyO3 Project and Contributors
use pyptr::PyPtr; use pointers::{pptr, PyPtr};
use token::PyObjectMarker; use token::PyObjectMarker;
use objects::PyObject; use objects::PyObject;
@ -8,10 +8,14 @@ pub trait PyBaseObject : Sized {}
pub trait PyNativeObject<'p> : PyBaseObject { pub trait PyNativeObject<'p> : PyBaseObject {
fn park(self) -> pptr;
fn as_object(self) -> PyObject<'p>; fn as_object(self) -> PyObject<'p>;
fn into_object(self) -> PyPtr<PyObjectMarker>; fn into_object(self) -> PyPtr<PyObjectMarker>;
fn clone_object(&self) -> Self;
} }
/*impl<'a, T: Sized> FromPyObject<'a> for T /*impl<'a, T: Sized> FromPyObject<'a> for T

View file

@ -4,10 +4,11 @@
use std::fmt; use std::fmt;
use std::cmp::Ordering; use std::cmp::Ordering;
use ffi; use ffi;
use libc; use libc;
use ppptr::pptr; use pyptr;
use pyptr::{Py, PyPtr}; use pointers::{pptr, Py, PyPtr};
use python::{Python, PyDowncastInto, ToPythonPointer}; use python::{Python, PyDowncastInto, ToPythonPointer};
use objects::{PyObject, PyDict, PyString, PyIterator}; use objects::{PyObject, PyDict, PyString, PyIterator};
use token::PythonObjectWithGilToken; use token::PythonObjectWithGilToken;
@ -373,7 +374,7 @@ impl<'p, T> ObjectProtocol<'p> for T where T: PythonObjectWithGilToken<'p> + ToP
#[inline] #[inline]
fn iter(&self) -> PyResult<PyIterator<'p>> { fn iter(&self) -> PyResult<PyIterator<'p>> {
unsafe { unsafe {
let ptr = pptr::from_owned_ptr_or_err( let ptr = pyptr::from_owned_ptr_or_err(
self.gil(), ffi::PyObject_GetIter(self.as_ptr()))?; self.gil(), ffi::PyObject_GetIter(self.as_ptr()))?;
PyIterator::from_object(self.gil(), ptr).map_err(|e| e.into()) PyIterator::from_object(self.gil(), ptr).map_err(|e| e.into())
} }
@ -425,6 +426,31 @@ impl<'p, T> fmt::Display for PyPtr<T> where T: ObjectProtocol<'p> + PyTypeInfo {
} }
} }
impl fmt::Debug for pptr {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();
// TODO: we shouldn't use fmt::Error when repr() fails
let r = self.as_object(py);
let repr_obj = try!(r.repr().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
impl fmt::Display for pptr {
default fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();
// TODO: we shouldn't use fmt::Error when repr() fails
let r = self.as_object(py);
let repr_obj = try!(r.str().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use python::{Python}; use python::{Python};

View file

@ -1,4 +1,4 @@
use ::{pptr, PyPtr}; use ::{pyptr, PyPtr};
use ffi; use ffi;
use token::PyObjectMarker; use token::PyObjectMarker;
use python::{ToPythonPointer, Python}; use python::{ToPythonPointer, Python};
@ -6,7 +6,7 @@ use native::PyNativeObject;
use conversion::ToPyObject; use conversion::ToPyObject;
/// Represents a Python `bool`. /// Represents a Python `bool`.
pub struct PyBool<'p>(pptr<'p>); pub struct PyBool<'p>(pyptr<'p>);
pyobject_nativetype!(PyBool, PyBool_Check, PyBool_Type); pyobject_nativetype!(PyBool, PyBool_Check, PyBool_Type);
@ -15,7 +15,7 @@ impl<'p> PyBool<'p> {
#[inline] #[inline]
pub fn new(py: Python<'p>, val: bool) -> PyBool<'p> { pub fn new(py: Python<'p>, val: bool) -> PyBool<'p> {
unsafe { PyBool( unsafe { PyBool(
pptr::from_borrowed_ptr(py, if val { ffi::Py_True() } else { ffi::Py_False() }) pyptr::from_borrowed_ptr(py, if val { ffi::Py_True() } else { ffi::Py_False() })
)} )}
} }

View file

@ -7,12 +7,12 @@ use ffi;
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use objects::PyObject; use objects::PyObject;
use err::{PyResult, PyErr}; use err::{PyResult, PyErr};
use ppptr::pptr; use ppptr::pyptr;
use token::PythonObjectWithGilToken; use token::PythonObjectWithGilToken;
/// Represents a Python bytearray. /// Represents a Python bytearray.
pub struct PyByteArray<'p>(pptr<'p>); pub struct PyByteArray<'p>(pyptr<'p>);
pyobject_nativetype!(PyByteArray, PyByteArray_Check, PyByteArray_Type); pyobject_nativetype!(PyByteArray, PyByteArray_Check, PyByteArray_Type);
@ -26,7 +26,7 @@ impl<'p> PyByteArray<'p> {
let ptr = src.as_ptr() as *const c_char; let ptr = src.as_ptr() as *const c_char;
let len = src.len() as ffi::Py_ssize_t; let len = src.len() as ffi::Py_ssize_t;
let ptr = unsafe {ffi::PyByteArray_FromStringAndSize(ptr, len)}; let ptr = unsafe {ffi::PyByteArray_FromStringAndSize(ptr, len)};
unsafe { PyByteArray(pptr::cast_from_owned_ptr_or_panic::<PyByteArray>(py, ptr)) } unsafe { PyByteArray(pyptr::cast_from_owned_ptr_or_panic::<PyByteArray>(py, ptr)) }
} }
/// Creates a new Python bytearray object /// Creates a new Python bytearray object
@ -36,7 +36,7 @@ impl<'p> PyByteArray<'p> {
let res = unsafe {ffi::PyByteArray_FromObject(src.as_ptr())}; let res = unsafe {ffi::PyByteArray_FromObject(src.as_ptr())};
if res != ptr::null_mut() { if res != ptr::null_mut() {
Ok(unsafe{ PyByteArray( Ok(unsafe{ PyByteArray(
pptr::cast_from_owned_ptr_or_panic::<PyByteArray>(src.gil(), res))}) pyptr::cast_from_owned_ptr_or_panic::<PyByteArray>(src.gil(), res))})
} else { } else {
Err(PyErr::fetch(src.gil())) Err(PyErr::fetch(src.gil()))
} }

View file

@ -2,18 +2,18 @@
// //
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython // based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ::pptr; use ::pyptr;
use ffi; use ffi;
use pyptr::PyPtr; use pointers::PyPtr;
use python::{Python, ToPythonPointer, PyDowncastInto}; use python::{Python, ToPythonPointer, PyDowncastInto};
use conversion::{ToPyObject, IntoPyObject}; use conversion::{ToPyObject};
use objects::{PyObject, PyList}; use objects::{PyObject, PyList};
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
use err::{self, PyResult, PyErr}; use err::{self, PyResult, PyErr};
use std::{mem, collections, hash, cmp}; use std::{mem, collections, hash, cmp};
/// Represents a Python `dict`. /// Represents a Python `dict`.
pub struct PyDict<'p>(pptr<'p>); pub struct PyDict<'p>(pyptr<'p>);
pyobject_nativetype!(PyDict, PyDict_Check, PyDict_Type); pyobject_nativetype!(PyDict, PyDict_Check, PyDict_Type);
@ -23,12 +23,12 @@ impl<'p> PyDict<'p> {
/// ///
/// May panic when running out of memory. /// May panic when running out of memory.
pub fn new(py: Python<'p>) -> PyDict<'p> { pub fn new(py: Python<'p>) -> PyDict<'p> {
unsafe { PyDict(pptr::from_owned_ptr_or_panic(py, ffi::PyDict_New())) } unsafe { PyDict(pyptr::from_owned_ptr_or_panic(py, ffi::PyDict_New())) }
} }
/// Construct a new dict with the given raw pointer /// Construct a new dict with the given raw pointer
pub fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyDict<'p> { pub fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyDict<'p> {
unsafe { PyDict(pptr::from_borrowed_ptr(py, ptr)) } unsafe { PyDict(pyptr::from_borrowed_ptr(py, ptr)) }
} }
/// Return a new dictionary that contains the same key-value pairs as self. /// Return a new dictionary that contains the same key-value pairs as self.
@ -36,7 +36,7 @@ impl<'p> PyDict<'p> {
pub fn copy(&'p self) -> PyResult<PyDict<'p>> { pub fn copy(&'p self) -> PyResult<PyDict<'p>> {
unsafe { unsafe {
Ok(PyDict( Ok(PyDict(
pptr::from_owned_ptr_or_err(self.gil(), ffi::PyDict_Copy(self.0.as_ptr()))? pyptr::from_owned_ptr_or_err(self.gil(), ffi::PyDict_Copy(self.0.as_ptr()))?
)) ))
} }
} }
@ -134,7 +134,7 @@ impl <K, V> ToPyObject for collections::HashMap<K, V>
for (key, value) in self { for (key, value) in self {
dict.set_item(key, value).unwrap(); dict.set_item(key, value).unwrap();
}; };
dict.into_object(py) dict.to_object(py)
} }
} }
@ -147,7 +147,7 @@ impl <K, V> ToPyObject for collections::BTreeMap<K, V>
for (key, value) in self { for (key, value) in self {
dict.set_item(key, value).unwrap(); dict.set_item(key, value).unwrap();
}; };
dict.into_object(py) dict.to_object(py)
} }
} }

View file

@ -9,9 +9,10 @@ use std::{self, mem, ops};
use std::ffi::CStr; use std::ffi::CStr;
use ffi; use ffi;
use pyptr::{Py, PyPtr}; use pointers::PyPtr;
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use err::PyResult; use err::PyResult;
use native::PyNativeObject;
use super::tuple::PyTuple; use super::tuple::PyTuple;
use super::typeobject::PyType; use super::typeobject::PyType;
@ -110,10 +111,10 @@ impl UnicodeDecodeError {
impl StopIteration { impl StopIteration {
pub fn stop_iteration<'p>(_py: Python<'p>, args: Py<'p, PyTuple>) { pub fn stop_iteration<'p>(args: PyTuple<'p>) {
unsafe { unsafe {
ffi::PyErr_SetObject( ffi::PyErr_SetObject(
ffi::PyExc_StopIteration as *mut ffi::PyObject, args.into_object().as_ptr()); ffi::PyExc_StopIteration as *mut ffi::PyObject, args.park().as_ptr());
} }
} }
} }

View file

@ -3,7 +3,7 @@
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython // based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ffi; use ffi;
use ppptr::pptr; use ppptr::pyptr;
use python::{Python, ToPythonPointer, IntoPythonPointer}; use python::{Python, ToPythonPointer, IntoPythonPointer};
use objects::PyObject; use objects::PyObject;
use err::{PyErr, PyResult, PyDowncastError}; use err::{PyErr, PyResult, PyDowncastError};
@ -12,7 +12,7 @@ use err::{PyErr, PyResult, PyDowncastError};
/// ///
/// Unlike other python objects, this class includes a `Python<'p>` token /// Unlike other python objects, this class includes a `Python<'p>` token
/// so that PyIterator can implement the rust `Iterator` trait. /// so that PyIterator can implement the rust `Iterator` trait.
pub struct PyIterator<'p>(pptr<'p>); pub struct PyIterator<'p>(pyptr<'p>);
impl <'p> PyIterator<'p> { impl <'p> PyIterator<'p> {
@ -24,7 +24,7 @@ impl <'p> PyIterator<'p> {
unsafe { unsafe {
let ptr = obj.into_ptr(); let ptr = obj.into_ptr();
if ffi::PyIter_Check(ptr) != 0 { if ffi::PyIter_Check(ptr) != 0 {
Ok(PyIterator(pptr::from_borrowed_ptr(py, ptr))) Ok(PyIterator(pyptr::from_borrowed_ptr(py, ptr)))
} else { } else {
ffi::Py_DECREF(ptr); ffi::Py_DECREF(ptr);
Err(PyDowncastError(py, None)) Err(PyDowncastError(py, None))

View file

@ -2,17 +2,17 @@
// //
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython // based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ::pptr; use ::pyptr;
use err::{self, PyResult}; use err::{self, PyResult};
use ffi::{self, Py_ssize_t}; use ffi::{self, Py_ssize_t};
use pyptr::PyPtr; use pointers::PyPtr;
use python::{Python, ToPythonPointer, IntoPythonPointer}; use python::{Python, ToPythonPointer, IntoPythonPointer};
use objects::PyObject; use objects::PyObject;
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
use conversion::{ToPyObject, IntoPyObject}; use conversion::{ToPyObject, IntoPyObject};
/// Represents a Python `list`. /// Represents a Python `list`.
pub struct PyList<'p>(pptr<'p>); pub struct PyList<'p>(pyptr<'p>);
pyobject_nativetype!(PyList, PyList_Check, PyList_Type); pyobject_nativetype!(PyList, PyList_Check, PyList_Type);
@ -24,7 +24,7 @@ impl<'p> PyList<'p> {
for (i, e) in elements.iter().enumerate() { for (i, e) in elements.iter().enumerate() {
ffi::PyList_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr()); ffi::PyList_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr());
} }
PyList(pptr::from_owned_ptr_or_panic(py, ptr)) PyList(pyptr::from_owned_ptr_or_panic(py, ptr))
} }
} }
@ -125,14 +125,14 @@ impl <T> ToPyObject for Vec<T> where T: ToPyObject {
impl <T> IntoPyObject for Vec<T> where T: IntoPyObject { impl <T> IntoPyObject for Vec<T> where T: IntoPyObject {
fn into_object(self, py: Python) -> PyPtr<PyObjectMarker> { fn into_object(self, py: Python) -> ::pptr {
unsafe { unsafe {
let ptr = ffi::PyList_New(self.len() as Py_ssize_t); let ptr = ffi::PyList_New(self.len() as Py_ssize_t);
for (i, e) in self.into_iter().enumerate() { for (i, e) in self.into_iter().enumerate() {
let obj = e.into_object(py).into_ptr(); let obj = e.into_object(py).into_ptr();
ffi::PyList_SetItem(ptr, i as Py_ssize_t, obj); ffi::PyList_SetItem(ptr, i as Py_ssize_t, obj);
} }
PyPtr::from_owned_ptr_or_panic(ptr) ::pptr::from_owned_ptr_or_panic(ptr)
} }
} }
} }

View file

@ -51,12 +51,21 @@ macro_rules! pyobject_nativetype(
impl<'p> $crate::native::PyBaseObject for $name<'p> {} impl<'p> $crate::native::PyBaseObject for $name<'p> {}
impl<'p> $crate::native::PyNativeObject<'p> for $name<'p> { impl<'p> $crate::native::PyNativeObject<'p> for $name<'p> {
fn park(self) -> $crate::pptr {
unsafe { $crate::std::mem::transmute(self) }
}
fn as_object(self) -> $crate::PyObject<'p> { fn as_object(self) -> $crate::PyObject<'p> {
unsafe { $crate::std::mem::transmute(self) } unsafe { $crate::std::mem::transmute(self) }
} }
fn into_object(self) -> $crate::PyPtr<$crate::PyObjectMarker> { fn into_object(self) -> $crate::PyPtr<$crate::PyObjectMarker> {
unsafe { $crate::std::mem::transmute(self) } unsafe { $crate::std::mem::transmute(self) }
} }
fn clone_object(&self) -> $name<'p> {
use $crate::{ToPythonPointer, PythonObjectWithGilToken};
unsafe {
$name(pyptr::from_borrowed_ptr(self.gil(), self.as_ptr()))
}
}
} }
impl<'p> $crate::token::PythonObjectWithGilToken<'p> for $name<'p> { impl<'p> $crate::token::PythonObjectWithGilToken<'p> for $name<'p> {
@ -92,7 +101,7 @@ macro_rules! pyobject_nativetype(
unsafe{ unsafe{
let ptr = ob.into_ptr(); let ptr = ob.into_ptr();
if ffi::$checkfunction(ptr) != 0 { if ffi::$checkfunction(ptr) != 0 {
Ok($name(pptr::from_owned_ptr(py, ptr))) Ok($name(pyptr::from_owned_ptr(py, ptr)))
} else { } else {
$crate::ffi::Py_DECREF(ptr); $crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None)) Err($crate::PyDowncastError(py, None))
@ -105,7 +114,7 @@ macro_rules! pyobject_nativetype(
{ {
unsafe{ unsafe{
if ffi::$checkfunction(ptr) != 0 { if ffi::$checkfunction(ptr) != 0 {
Ok($name(pptr::from_owned_ptr(py, ptr))) Ok($name(pyptr::from_owned_ptr(py, ptr)))
} else { } else {
$crate::ffi::Py_DECREF(ptr); $crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None)) Err($crate::PyDowncastError(py, None))
@ -141,7 +150,7 @@ macro_rules! pyobject_nativetype(
unsafe { unsafe {
if ffi::$checkfunction(py.as_ptr()) != 0 { if ffi::$checkfunction(py.as_ptr()) != 0 {
Ok( $name($crate::pptr::from_borrowed_ptr(py.gil(), py.as_ptr())) ) Ok( $name($crate::pyptr::from_borrowed_ptr(py.gil(), py.as_ptr())) )
} else { } else {
Err(::PyDowncastError(py.gil(), None).into()) Err(::PyDowncastError(py.gil(), None).into())
} }
@ -184,7 +193,7 @@ macro_rules! pyobject_nativetype(
impl<'a> $crate::IntoPyObject for $name<'a> impl<'a> $crate::IntoPyObject for $name<'a>
{ {
#[inline] #[inline]
fn into_object(self, _py: $crate::Python) -> $crate::PyPtr<$crate::PyObjectMarker> fn into_object(self, _py: $crate::Python) -> $crate::pptr
{ {
unsafe { $crate::std::mem::transmute(self) } unsafe { $crate::std::mem::transmute(self) }
} }

View file

@ -7,9 +7,9 @@ use ffi;
use std::os::raw::c_char; use std::os::raw::c_char;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use ::pptr; use ::pyptr;
use conversion::{ToPyObject, ToPyTuple}; use conversion::{ToPyObject, ToPyTuple};
use pyptr::PyPtr; use pointers::PyPtr;
use python::{ToPythonPointer, Python}; use python::{ToPythonPointer, Python};
use token::PythonObjectWithGilToken; use token::PythonObjectWithGilToken;
use objects::{PyObject, PyDict, PyType, exc}; use objects::{PyObject, PyDict, PyType, exc};
@ -18,7 +18,7 @@ use err::{PyResult, PyErr};
/// Represents a Python module object. /// Represents a Python module object.
pub struct PyModule<'p>(pptr<'p>); pub struct PyModule<'p>(pyptr<'p>);
pyobject_nativetype!(PyModule, PyModule_Check, PyModule_Type); pyobject_nativetype!(PyModule, PyModule_Check, PyModule_Type);
@ -28,7 +28,7 @@ impl<'p> PyModule<'p> {
pub fn new(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> { pub fn new(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> {
let name = CString::new(name).unwrap(); let name = CString::new(name).unwrap();
unsafe { unsafe {
let ptr = pptr::cast_from_owned_nullptr::<PyModule>( let ptr = pyptr::cast_from_owned_ptr_or_err::<PyModule>(
py, ffi::PyModule_New(name.as_ptr()))?; py, ffi::PyModule_New(name.as_ptr()))?;
Ok(PyModule(ptr)) Ok(PyModule(ptr))
} }
@ -38,7 +38,7 @@ impl<'p> PyModule<'p> {
pub fn import(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> { pub fn import(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> {
let name = CString::new(name).unwrap(); let name = CString::new(name).unwrap();
unsafe { unsafe {
let ptr = pptr::cast_from_owned_nullptr::<PyModule>( let ptr = pyptr::cast_from_owned_ptr_or_err::<PyModule>(
py, ffi::PyImport_ImportModule(name.as_ptr()))?; py, ffi::PyImport_ImportModule(name.as_ptr()))?;
Ok(PyModule(ptr)) Ok(PyModule(ptr))
} }

View file

@ -7,14 +7,14 @@ extern crate num_traits;
use self::num_traits::cast::cast; use self::num_traits::cast::cast;
use std::os::raw::{c_long, c_double}; use std::os::raw::{c_long, c_double};
use ::{PyPtr, pptr}; use ::{PyPtr, pyptr};
use ffi; use ffi;
use super::exc; use super::exc;
use objects::PyObject; use objects::PyObject;
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
use python::{ToPythonPointer, Python}; use python::{ToPythonPointer, Python};
use err::{PyResult, PyErr}; use err::{PyResult, PyErr};
use conversion::{ToPyObject, FromPyObject, IntoPyObject}; use conversion::{ToPyObject, FromPyObject};
/// Represents a Python `int` object. /// Represents a Python `int` object.
/// ///
@ -22,7 +22,7 @@ use conversion::{ToPyObject, FromPyObject, IntoPyObject};
/// by using [ToPyObject](trait.ToPyObject.html) /// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract) /// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types. /// with the primitive Rust integer types.
pub struct PyLong<'p>(pptr<'p>); pub struct PyLong<'p>(pyptr<'p>);
pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type); pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type);
/// Represents a Python `float` object. /// Represents a Python `float` object.
@ -31,7 +31,7 @@ pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type);
/// by using [ToPyObject](trait.ToPyObject.html) /// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract) /// and [extract](struct.PyObject.html#method.extract)
/// with `f32`/`f64`. /// with `f32`/`f64`.
pub struct PyFloat<'p>(pptr<'p>); pub struct PyFloat<'p>(pyptr<'p>);
pyobject_nativetype!(PyFloat, PyFloat_Check, PyFloat_Type); pyobject_nativetype!(PyFloat, PyFloat_Check, PyFloat_Type);
@ -39,7 +39,7 @@ impl<'p> PyFloat<'p> {
/// Creates a new Python `float` object. /// Creates a new Python `float` object.
pub fn new(py: Python<'p>, val: c_double) -> PyFloat<'p> { pub fn new(py: Python<'p>, val: c_double) -> PyFloat<'p> {
unsafe { unsafe {
PyFloat(pptr::from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val))) PyFloat(pyptr::from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val)))
} }
} }
@ -170,7 +170,7 @@ int_convert_u64_or_i64!(u64, ffi::PyLong_FromUnsignedLongLong, ffi::PyLong_AsUns
impl ToPyObject for f64 { impl ToPyObject for f64 {
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyFloat::new(py, *self).into_object(py) PyFloat::new(py, *self).to_object(py)
} }
} }
@ -189,7 +189,7 @@ fn overflow_error(py: Python) -> PyErr {
impl ToPyObject for f32 { impl ToPyObject for f32 {
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyFloat::new(py, *self as f64).into_object(py) PyFloat::new(py, *self as f64).to_object(py)
} }
} }

View file

@ -2,13 +2,13 @@
use std; use std;
use ::pptr; use ::pyptr;
use ffi; use ffi;
use err::{PyResult, PyDowncastError}; use err::{PyResult, PyDowncastError};
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
pub struct PyObject<'p>(pptr<'p>); pub struct PyObject<'p>(pyptr<'p>);
pyobject_nativetype!(PyObject, PyObject_Check, PyBaseObject_Type); pyobject_nativetype!(PyObject, PyObject_Check, PyBaseObject_Type);
@ -17,20 +17,20 @@ impl<'p> PyObject<'p> {
#[inline] #[inline]
pub fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> { pub fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> {
unsafe { PyObject(pptr::from_owned_ptr(py, ptr)) } unsafe { PyObject(pyptr::from_owned_ptr(py, ptr)) }
} }
#[inline] #[inline]
pub fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<PyObject<'p>> { -> PyResult<PyObject<'p>> {
unsafe { Ok(PyObject(pptr::from_owned_ptr_or_err(py, ptr)?)) } unsafe { Ok(PyObject(pyptr::from_owned_ptr_or_err(py, ptr)?)) }
} }
#[inline] #[inline]
pub fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<PyObject<'p>> { -> Option<PyObject<'p>> {
unsafe { unsafe {
if let Some(ptr) = pptr::from_owned_ptr_or_opt(py, ptr) { if let Some(ptr) = pyptr::from_owned_ptr_or_opt(py, ptr) {
Some(PyObject(ptr)) Some(PyObject(ptr))
} else { } else {
None None
@ -40,14 +40,14 @@ impl<'p> PyObject<'p> {
#[inline] #[inline]
pub fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> { pub fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> {
unsafe { PyObject(pptr::from_borrowed_ptr(py, ptr)) } unsafe { PyObject(pyptr::from_borrowed_ptr(py, ptr)) }
} }
#[inline] #[inline]
pub fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<PyObject<'p>> { -> Option<PyObject<'p>> {
unsafe { unsafe {
if let Some(ptr) = pptr::from_borrowed_ptr_or_opt(py, ptr) { if let Some(ptr) = pyptr::from_borrowed_ptr_or_opt(py, ptr) {
Some(PyObject(ptr)) Some(PyObject(ptr))
} else { } else {
None None

View file

@ -3,7 +3,7 @@
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython // based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ffi; use ffi;
use ppptr::pptr; use ppptr::pyptr;
use python::{ToPythonPointer, PyDowncastFrom, PyDowncastInto}; use python::{ToPythonPointer, PyDowncastFrom, PyDowncastInto};
use conversion::{FromPyObject, ToPyObject}; use conversion::{FromPyObject, ToPyObject};
use objects::{PyObject, PyList, PyTuple}; use objects::{PyObject, PyList, PyTuple};
@ -16,7 +16,7 @@ use objectprotocol::ObjectProtocol;
/// Represents a reference to a python object supporting the sequence protocol. /// Represents a reference to a python object supporting the sequence protocol.
pub struct PySequence<'p>(pptr<'p>); pub struct PySequence<'p>(pyptr<'p>);
pyobject_nativetype!(PySequence, PySequence_Check); pyobject_nativetype!(PySequence, PySequence_Check);
@ -37,7 +37,7 @@ impl<'p> PySequence<'p> {
#[inline] #[inline]
pub fn concat(&self, other: &PySequence) -> PyResult<PySequence<'p>> { pub fn concat(&self, other: &PySequence) -> PyResult<PySequence<'p>> {
unsafe { unsafe {
Ok(PySequence(pptr::from_owned_ptr_or_err( Ok(PySequence(pyptr::from_owned_ptr_or_err(
self.gil(), self.gil(),
ffi::PySequence_Concat(self.as_ptr(), other.as_ptr()))?)) ffi::PySequence_Concat(self.as_ptr(), other.as_ptr()))?))
} }
@ -49,7 +49,7 @@ impl<'p> PySequence<'p> {
#[inline] #[inline]
pub fn repeat(&self, count: isize) -> PyResult<PySequence<'p>> { pub fn repeat(&self, count: isize) -> PyResult<PySequence<'p>> {
unsafe { unsafe {
Ok(PySequence(pptr::from_owned_ptr_or_err( Ok(PySequence(pyptr::from_owned_ptr_or_err(
self.gil(), self.gil(),
ffi::PySequence_Repeat(self.as_ptr(), count as Py_ssize_t))?)) ffi::PySequence_Repeat(self.as_ptr(), count as Py_ssize_t))?))
} }
@ -59,7 +59,7 @@ impl<'p> PySequence<'p> {
#[inline] #[inline]
pub fn in_place_concat(&self, other: &PySequence) -> PyResult<PySequence<'p>> { pub fn in_place_concat(&self, other: &PySequence) -> PyResult<PySequence<'p>> {
unsafe { unsafe {
Ok(PySequence(pptr::from_owned_ptr_or_err( Ok(PySequence(pyptr::from_owned_ptr_or_err(
self.0.token(), self.0.token(),
ffi::PySequence_InPlaceConcat(self.0.as_ptr(), other.as_ptr()))?)) ffi::PySequence_InPlaceConcat(self.0.as_ptr(), other.as_ptr()))?))
} }
@ -71,7 +71,7 @@ impl<'p> PySequence<'p> {
#[inline] #[inline]
pub fn in_place_repeat(&self, count: isize) -> PyResult<PySequence<'p>> { pub fn in_place_repeat(&self, count: isize) -> PyResult<PySequence<'p>> {
unsafe { unsafe {
Ok(PySequence(pptr::from_owned_ptr_or_err( Ok(PySequence(pyptr::from_owned_ptr_or_err(
self.0.token(), self.0.token(),
ffi::PySequence_InPlaceRepeat(self.as_ptr(), count as Py_ssize_t))?)) ffi::PySequence_InPlaceRepeat(self.as_ptr(), count as Py_ssize_t))?))
} }

View file

@ -3,20 +3,20 @@
use std::{hash, collections}; use std::{hash, collections};
use ffi; use ffi;
use pyptr::PyPtr; use pointers::PyPtr;
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
use conversion::{ToPyObject, IntoPyObject}; use conversion::ToPyObject;
use objects::{PyObject, PyIterator}; use objects::{PyObject, PyIterator};
use err::{self, PyResult, PyErr}; use err::{self, PyResult, PyErr};
use pptr; use pyptr;
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
use objectprotocol::ObjectProtocol; use objectprotocol::ObjectProtocol;
/// Represents a Python `set` /// Represents a Python `set`
pub struct PySet<'p>(pptr<'p>); pub struct PySet<'p>(pyptr<'p>);
/// Represents a Python `frozenset` /// Represents a Python `frozenset`
pub struct PyFrozenSet<'p>(pptr<'p>); pub struct PyFrozenSet<'p>(pyptr<'p>);
pyobject_nativetype!(PySet, PySet_Check, PySet_Type); pyobject_nativetype!(PySet, PySet_Check, PySet_Type);
pyobject_nativetype!(PyFrozenSet, PyFrozenSet_Check, PyFrozenSet_Type); pyobject_nativetype!(PyFrozenSet, PyFrozenSet_Check, PyFrozenSet_Type);
@ -29,7 +29,7 @@ impl<'p> PySet<'p> {
let list = elements.to_object(py); let list = elements.to_object(py);
unsafe { unsafe {
let ptr = ffi::PySet_New(list.as_ptr()); let ptr = ffi::PySet_New(list.as_ptr());
PySet(pptr::from_owned_ptr_or_panic(py, ptr)) PySet(pyptr::from_owned_ptr_or_panic(py, ptr))
} }
} }
@ -95,7 +95,7 @@ impl<T> ToPyObject for collections::HashSet<T>
for val in self { for val in self {
set.add(val).unwrap(); set.add(val).unwrap();
} }
set.into_object(py) set.to_object(py)
} }
} }
@ -107,7 +107,7 @@ impl<T> ToPyObject for collections::BTreeSet<T>
for val in self { for val in self {
set.add(val).unwrap(); set.add(val).unwrap();
} }
set.into_object(py) set.to_object(py)
} }
} }
@ -119,7 +119,7 @@ impl<'p> PyFrozenSet<'p> {
let list = elements.to_object(py); let list = elements.to_object(py);
unsafe { unsafe {
let ptr = ffi::PyFrozenSet_New(list.as_ptr()); let ptr = ffi::PyFrozenSet_New(list.as_ptr());
PyFrozenSet(pptr::from_owned_ptr_or_panic(py, ptr)) PyFrozenSet(pyptr::from_owned_ptr_or_panic(py, ptr))
} }
} }

View file

@ -2,12 +2,12 @@
use std::os::raw::c_long; use std::os::raw::c_long;
use ::pptr; use ::pyptr;
use pyptr::PyPtr; use pointers::PyPtr;
use python::{ToPythonPointer, Python}; use python::{ToPythonPointer, Python};
use err::{PyErr, PyResult}; use err::{PyErr, PyResult};
use ffi::{self, Py_ssize_t}; use ffi::{self, Py_ssize_t};
use conversion::{ToPyObject, IntoPyObject}; use conversion::ToPyObject;
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
/// Represents a Python `slice` indices /// Represents a Python `slice` indices
@ -32,7 +32,7 @@ impl PySliceIndices {
/// Represents a Python `slice`. Only `c_long` indeces supprted /// Represents a Python `slice`. Only `c_long` indeces supprted
/// at the moment by PySlice object. /// at the moment by PySlice object.
pub struct PySlice<'p>(pptr<'p>); pub struct PySlice<'p>(pyptr<'p>);
pyobject_nativetype!(PySlice, PySlice_Check, PySlice_Type); pyobject_nativetype!(PySlice, PySlice_Check, PySlice_Type);
@ -44,7 +44,7 @@ impl<'p> PySlice<'p> {
let ptr = ffi::PySlice_New(ffi::PyLong_FromLong(start as i64), let ptr = ffi::PySlice_New(ffi::PyLong_FromLong(start as i64),
ffi::PyLong_FromLong(stop as i64), ffi::PyLong_FromLong(stop as i64),
ffi::PyLong_FromLong(step as i64)); ffi::PyLong_FromLong(step as i64));
PySlice(pptr::from_owned_ptr_or_panic(py, ptr)) PySlice(pyptr::from_owned_ptr_or_panic(py, ptr))
} }
} }
@ -79,6 +79,6 @@ impl<'p> PySlice<'p> {
impl ToPyObject for PySliceIndices { impl ToPyObject for PySliceIndices {
fn to_object<'p>(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object<'p>(&self, py: Python) -> PyPtr<PyObjectMarker> {
PySlice::new(py, self.start, self.stop, self.step).into_object(py) PySlice::new(py, self.start, self.stop, self.step).to_object(py)
} }
} }

View file

@ -8,21 +8,21 @@ use std::ascii::AsciiExt;
use std::borrow::Cow; use std::borrow::Cow;
use std::os::raw::c_char; use std::os::raw::c_char;
use ::{PyPtr, pptr}; use ::{PyPtr, pyptr};
use ffi; use ffi;
use python::{ToPythonPointer, Python}; use python::{ToPythonPointer, Python};
use super::{exc, PyObject}; use super::{exc, PyObject};
use token::{PyObjectMarker, PythonObjectWithGilToken}; use token::{PyObjectMarker, PythonObjectWithGilToken};
use err::{PyResult, PyErr}; use err::{PyResult, PyErr};
use conversion::{ToPyObject, IntoPyObject, RefFromPyObject}; use conversion::{ToPyObject, RefFromPyObject};
/// Represents a Python string. /// Represents a Python string.
pub struct PyString<'p>(pptr<'p>); pub struct PyString<'p>(pyptr<'p>);
pyobject_nativetype!(PyString, PyUnicode_Check, PyUnicode_Type); pyobject_nativetype!(PyString, PyUnicode_Check, PyUnicode_Type);
/// Represents a Python byte string. /// Represents a Python byte string.
pub struct PyBytes<'p>(pptr<'p>); pub struct PyBytes<'p>(pyptr<'p>);
pyobject_nativetype!(PyBytes, PyBytes_Check, PyBytes_Type); pyobject_nativetype!(PyBytes, PyBytes_Check, PyBytes_Type);
@ -143,7 +143,7 @@ impl<'p> PyString<'p> {
let ptr = s.as_ptr() as *const c_char; let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t; let len = s.len() as ffi::Py_ssize_t;
unsafe { unsafe {
PyString(pptr::from_owned_ptr_or_panic( PyString(pyptr::from_owned_ptr_or_panic(
py, ffi::PyUnicode_FromStringAndSize(ptr, len))) py, ffi::PyUnicode_FromStringAndSize(ptr, len)))
} }
} }
@ -152,7 +152,7 @@ impl<'p> PyString<'p> {
-> PyResult<PyString<'p>> { -> PyResult<PyString<'p>> {
unsafe { unsafe {
Ok(PyString( Ok(PyString(
pptr::from_owned_ptr_or_err( pyptr::from_owned_ptr_or_err(
src.gil(), ffi::PyUnicode_FromEncodedObject( src.gil(), ffi::PyUnicode_FromEncodedObject(
src.as_ptr(), src.as_ptr(),
encoding.as_ptr() as *const i8, encoding.as_ptr() as *const i8,
@ -201,7 +201,7 @@ impl<'p> PyBytes<'p> {
let ptr = s.as_ptr() as *const c_char; let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t; let len = s.len() as ffi::Py_ssize_t;
unsafe { unsafe {
PyBytes(pptr::from_owned_ptr_or_panic( PyBytes(pyptr::from_owned_ptr_or_panic(
py, ffi::PyBytes_FromStringAndSize(ptr, len))) py, ffi::PyBytes_FromStringAndSize(ptr, len)))
} }
} }
@ -221,7 +221,7 @@ impl<'p> PyBytes<'p> {
impl ToPyObject for str { impl ToPyObject for str {
#[inline] #[inline]
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyString::new(py, self).into_object(py) PyString::new(py, self).to_object(py)
} }
} }
@ -230,7 +230,7 @@ impl ToPyObject for str {
impl <'a> ToPyObject for Cow<'a, str> { impl <'a> ToPyObject for Cow<'a, str> {
#[inline] #[inline]
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyString::new(py, self).into_object(py) PyString::new(py, self).to_object(py)
} }
} }
@ -239,7 +239,7 @@ impl <'a> ToPyObject for Cow<'a, str> {
impl ToPyObject for String { impl ToPyObject for String {
#[inline] #[inline]
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyString::new(py, self).into_object(py) PyString::new(py, self).to_object(py)
} }
} }

View file

@ -4,7 +4,7 @@
use std::slice; use std::slice;
use ::{PyPtr, pptr}; use ::{PyPtr, pyptr};
use ffi::{self, Py_ssize_t}; use ffi::{self, Py_ssize_t};
use err::{PyErr, PyResult}; use err::{PyErr, PyResult};
use python::{Python, ToPythonPointer, IntoPythonPointer}; use python::{Python, ToPythonPointer, IntoPythonPointer};
@ -14,7 +14,7 @@ use token::{PyObjectMarker, PythonObjectWithGilToken};
use super::exc; use super::exc;
/// Represents a Python tuple object. /// Represents a Python tuple object.
pub struct PyTuple<'p>(pptr<'p>); pub struct PyTuple<'p>(pyptr<'p>);
pyobject_nativetype!(PyTuple, PyTuple_Check, PyTuple_Type); pyobject_nativetype!(PyTuple, PyTuple_Check, PyTuple_Type);
@ -29,19 +29,19 @@ impl<'p> PyTuple<'p> {
for (i, e) in elements.iter().enumerate() { for (i, e) in elements.iter().enumerate() {
ffi::PyTuple_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr()); ffi::PyTuple_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr());
} }
PyTuple(pptr::from_owned_ptr_or_panic(py, ptr)) PyTuple(pyptr::from_owned_ptr_or_panic(py, ptr))
} }
} }
/// Construct a new tuple with the given raw pointer /// Construct a new tuple with the given raw pointer
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyTuple<'p> { pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyTuple<'p> {
PyTuple(pptr::from_borrowed_ptr(py, ptr)) PyTuple(pyptr::from_borrowed_ptr(py, ptr))
} }
/// Retrieves the empty tuple. /// Retrieves the empty tuple.
pub fn empty(py: Python<'p>) -> PyTuple<'p> { pub fn empty(py: Python<'p>) -> PyTuple<'p> {
unsafe { unsafe {
PyTuple(pptr::from_owned_ptr_or_panic(py, ffi::PyTuple_New(0))) PyTuple(pyptr::from_owned_ptr_or_panic(py, ffi::PyTuple_New(0)))
} }
} }
@ -89,7 +89,7 @@ impl<'p> PyTuple<'p> {
impl<'a> ToPyTuple for PyTuple<'a> { impl<'a> ToPyTuple for PyTuple<'a> {
fn to_py_tuple<'p>(&self, py: Python<'p>) -> PyTuple<'p> { fn to_py_tuple<'p>(&self, py: Python<'p>) -> PyTuple<'p> {
unsafe { PyTuple(pptr::from_borrowed_ptr(py, self.0.as_ptr())) } unsafe { PyTuple(pyptr::from_borrowed_ptr(py, self.0.as_ptr())) }
} }
} }
@ -103,7 +103,7 @@ fn wrong_tuple_length(py: Python, t: &PyTuple, expected_length: usize) -> PyErr
let msg = format!("Expected tuple of length {}, but got tuple of length {}.", let msg = format!("Expected tuple of length {}, but got tuple of length {}.",
expected_length, t.len()); expected_length, t.len());
PyErr::new_lazy_init( PyErr::new_lazy_init(
py.get_type::<exc::ValueError>(), Some(msg.to_object(py))) py.get_type::<exc::ValueError>(), Some(msg.into_object(py)))
} }
macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => { macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => {
@ -111,7 +111,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+
fn to_object<'p>(&self, py: Python<'p>) -> PyPtr<PyObjectMarker> { fn to_object<'p>(&self, py: Python<'p>) -> PyPtr<PyObjectMarker> {
PyTuple::new(py, &[ PyTuple::new(py, &[
$(py_coerce_expr!(self.$n.to_object(py)),)+ $(py_coerce_expr!(self.$n.to_object(py)),)+
]).into_object(py) ]).to_object(py)
} }
} }
@ -175,7 +175,7 @@ pub struct NoArgs;
impl ToPyObject for NoArgs { impl ToPyObject for NoArgs {
fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> { fn to_object(&self, py: Python) -> PyPtr<PyObjectMarker> {
PyTuple::empty(py).into_object(py) PyTuple::empty(py).to_object(py)
} }
} }

View file

@ -5,7 +5,7 @@
use std::ffi::CStr; use std::ffi::CStr;
use std::borrow::Cow; use std::borrow::Cow;
use ::pptr; use ::pyptr;
use ffi; use ffi;
use token::PythonObjectWithGilToken; use token::PythonObjectWithGilToken;
use python::{Python, ToPythonPointer}; use python::{Python, ToPythonPointer};
@ -14,7 +14,7 @@ use objects::{PyObject, PyDict};
use err::PyResult; use err::PyResult;
/// Represents a reference to a Python type object. /// Represents a reference to a Python type object.
pub struct PyType<'p>(pptr<'p>); pub struct PyType<'p>(pyptr<'p>);
pyobject_nativetype!(PyType, PyType_Check, PyType_Type); pyobject_nativetype!(PyType, PyType_Check, PyType_Type);
@ -31,7 +31,7 @@ impl<'p> PyType<'p> {
/// Undefined behavior if the pointer is NULL or invalid. /// Undefined behavior if the pointer is NULL or invalid.
#[inline] #[inline]
pub unsafe fn from_type_ptr(py: Python<'p>, p: *mut ffi::PyTypeObject) -> PyType<'p> { pub unsafe fn from_type_ptr(py: Python<'p>, p: *mut ffi::PyTypeObject) -> PyType<'p> {
PyType(pptr::from_borrowed_ptr(py, p as *mut ffi::PyObject)) PyType(pyptr::from_borrowed_ptr(py, p as *mut ffi::PyObject))
} }
/// Gets the name of the PyType. /// Gets the name of the PyType.

View file

@ -14,11 +14,203 @@ use token::{PyObjectMarker, PythonObjectWithGilToken};
use typeob::{PyTypeInfo, PyObjectAlloc}; use typeob::{PyTypeInfo, PyObjectAlloc};
#[allow(non_camel_case_types)]
pub struct pptr(*mut ffi::PyObject);
// `pptr` is thread-safe, because all operations on it require a Python<'p> token.
unsafe impl Send for pptr {}
unsafe impl Sync for pptr {}
impl pptr {
/// Creates a `pptr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `pptr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> pptr {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
pptr(ptr)
}
/// Creates a `pptr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `pptr`.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_owned_ptr_or_opt(ptr: *mut ffi::PyObject) -> Option<pptr> {
if ptr.is_null() {
None
} else {
Some(pptr::from_owned_ptr(ptr))
}
}
/// Construct `pptr` from the result of a Python FFI call that
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`; undefined behavior if the
/// pointer is invalid.
pub unsafe fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<pptr>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(pptr::from_owned_ptr(ptr))
}
}
/// Construct `pptr` instance for the given Python FFI pointer.
/// Panics if the pointer is `null`; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_owned_ptr_or_panic(ptr: *mut ffi::PyObject) -> pptr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
pptr::from_owned_ptr(ptr)
}
}
/// Creates a `pptr` 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) -> pptr {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr);
pptr::from_owned_ptr(ptr)
}
/// Creates a `pptr` instance for the given Python FFI pointer.
/// Calls Py_INCREF() on the ptr.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_borrowed_ptr_or_opt(ptr: *mut ffi::PyObject) -> Option<pptr> {
if ptr.is_null() {
None
} else {
Some(pptr::from_borrowed_ptr(ptr))
}
}
/// Construct `pptr` instance for the given Python FFI pointer.
/// Calls Py_INCREF() on the ptr.
/// Panics if the pointer is `null`; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_borrowed_ptr_or_panic(ptr: *mut ffi::PyObject) -> pptr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
pptr::from_borrowed_ptr(ptr)
}
}
/// Gets the reference count of the PyObject pointer.
#[inline]
pub fn get_refcnt(&self) -> isize {
unsafe { ffi::Py_REFCNT(self.0) }
}
/// Get reference to &PyObject<'p>
#[inline]
pub fn as_object<'p>(&self, _py: Python<'p>) -> &PyObject<'p> {
unsafe { std::mem::transmute(self) }
}
/// Converts `pptr` instance -> PyObject<'p>
/// Consumes `self` without calling `Py_DECREF()`
#[inline]
pub fn into_object<'p>(self, _py: Python<'p>) -> PyObject<'p> {
unsafe { std::mem::transmute(self) }
}
/// Converts `pptr` instance -> PyObject<'p>
/// Consumes `self` without calling `Py_DECREF()`
#[inline]
pub fn into_pobject(self) -> PyPtr<PyObjectMarker> {
unsafe { std::mem::transmute(self) }
}
/// Clone self, Calls Py_INCREF() on the ptr.
#[inline]
pub fn clone_ref(&self, _py: Python) -> pptr {
unsafe { pptr::from_borrowed_ptr(self.0) }
}
/// Casts the `pptr` imstance to a concrete Python object type.
/// Fails with `PyDowncastError` if the object is not of the expected type.
#[inline]
pub fn cast_into<'p, D>(self, py: Python<'p>) -> Result<D, PyDowncastError<'p>>
where D: ::PyDowncastInto<'p>
{
<D as ::PyDowncastInto>::downcast_into(py, self)
}
// /// Unchecked cast into native object.
// /// Undefined behavior if the input object does not have the expected type.
// #[inline]
// pub unsafe fn unchecked_cast_into<'p, S>(self, py: Python<'p>) -> S
// where S: PyNativeObject<'p>
// {
// unsafe { std::mem::transmute(self) }
// }
}
impl ToPythonPointer for pptr {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.0
}
}
impl IntoPythonPointer for pptr {
/// 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 IntoPyObject for pptr {
#[inline]
fn into_object(self, _py: Python) -> pptr {
self
}
}
impl PartialEq for pptr {
#[inline]
fn eq(&self, o: &pptr) -> bool {
self.0 == o.0
}
}
/// Dropping a `pptr` instance decrements the reference count on the object by 1.
impl Drop for pptr {
fn drop(&mut self) {
unsafe {
println!("drop pptr: {:?} {} {:?}",
self.0, ffi::Py_REFCNT(self.0), &self as *const _);
}
let _gil_guard = Python::acquire_gil();
unsafe { ffi::Py_DECREF(self.0); }
}
}
pub struct PyPtr<T> { pub struct PyPtr<T> {
inner: *mut ffi::PyObject, inner: *mut ffi::PyObject,
_t: PhantomData<T>, _t: PhantomData<T>,
} }
impl<T> PyPtr<T> { impl<T> PyPtr<T> {
/// Creates a PyPtr instance for the given FFI pointer. /// Creates a PyPtr instance for the given FFI pointer.
/// This moves ownership over the pointer into the Py. /// This moves ownership over the pointer into the Py.
@ -104,16 +296,13 @@ impl<T> PyPtr<T> {
/// Converts PyPtr<T> -> PyPtr<PyObject> /// Converts PyPtr<T> -> PyPtr<PyObject>
/// Consumes `self` without calling `Py_INCREF()` /// Consumes `self` without calling `Py_INCREF()`
#[inline] #[inline]
pub fn park(self) -> PyPtr<PyObjectMarker> { pub fn park(self) -> pptr {
let p = PyPtr {inner: self.inner, _t: PhantomData}; unsafe { std::mem::transmute(self) }
std::mem::forget(self);
p
} }
/// Converts PyPtr<T> -> &PyObject<'p>. /// Converts PyPtr<T> -> &PyObject<'p>.
#[inline] #[inline]
pub fn as_object<'p>(&self, _py: Python<'p>) -> &PyObject<'p> { pub fn as_object<'p>(&self, _py: Python<'p>) -> &PyObject<'p> {
unsafe {ffi::Py_INCREF(self.inner)};
unsafe { std::mem::transmute(self) } unsafe { std::mem::transmute(self) }
} }
@ -184,7 +373,7 @@ impl<T> IntoPythonPointer for PyPtr<T> {
impl<T> IntoPyObject for PyPtr<T> { impl<T> IntoPyObject for PyPtr<T> {
#[inline] #[inline]
fn into_object<'a>(self, _py: Python) -> PyPtr<PyObjectMarker> { fn into_object<'a>(self, _py: Python) -> pptr {
self.park() self.park()
} }
} }
@ -290,6 +479,12 @@ impl<'p, T> Py<'p, T>
unsafe { ffi::Py_REFCNT(self.inner) as usize } unsafe { ffi::Py_REFCNT(self.inner) as usize }
} }
/// Convert tp `pptr` pointer
#[inline]
pub fn park(self) -> pptr {
unsafe { std::mem::transmute(self) }
}
/// Creates a PyPtr instance. Calls Py_INCREF() on the ptr. /// Creates a PyPtr instance. Calls Py_INCREF() on the ptr.
#[inline] #[inline]
pub fn as_pptr(&self) -> PyPtr<T> { pub fn as_pptr(&self) -> PyPtr<T> {
@ -636,10 +831,8 @@ impl<T> ToPyObject for PyPtr<T> {
impl<'p, T> IntoPyObject for Py<'p, T> { impl<'p, T> IntoPyObject for Py<'p, T> {
#[inline] #[inline]
default fn into_object(self, _py: Python) -> PyPtr<PyObjectMarker> { default fn into_object(self, _py: Python) -> pptr {
let ptr = unsafe { PyPtr::from_owned_ptr(self.inner) }; unsafe { std::mem::transmute(self) }
std::mem::forget(self);
ptr
} }
} }

View file

@ -8,37 +8,37 @@ use python::{Python, PyDowncastInto, ToPythonPointer, IntoPythonPointer};
use typeob::{PyTypeInfo, PyObjectAlloc}; use typeob::{PyTypeInfo, PyObjectAlloc};
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub struct pptr<'p>(Python<'p>, *mut ffi::PyObject); pub struct pyptr<'p>(Python<'p>, *mut ffi::PyObject);
impl<'p> pptr<'p> { impl<'p> pyptr<'p> {
/// Create new python object and move T instance under python management /// Create new python object and move T instance under python management
pub fn new<T>(py: Python<'p>, value: T) -> PyResult<pptr<'p>> where T: PyObjectAlloc<Type=T> pub fn new<T>(py: Python<'p>, value: T) -> PyResult<pyptr<'p>> where T: PyObjectAlloc<Type=T>
{ {
let ptr = unsafe { let ptr = unsafe {
try!(<T as PyObjectAlloc>::alloc(py, value)) try!(<T as PyObjectAlloc>::alloc(py, value))
}; };
Ok(pptr(py, ptr)) Ok(pyptr(py, ptr))
} }
/// Creates a Py instance for the given FFI pointer. /// Creates a Py instance for the given FFI pointer.
/// This moves ownership over the pointer into the Py. /// This moves ownership over the pointer into the Py.
/// Undefined behavior if the pointer is NULL or invalid. /// Undefined behavior if the pointer is NULL or invalid.
#[inline] #[inline]
pub unsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> pptr<'p> { pub unsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> pyptr<'p> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0); debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
pptr(py, ptr) pyptr(py, ptr)
} }
/// Cast from ffi::PyObject ptr to a concrete object. /// Cast from ffi::PyObject ptr to a concrete object.
#[inline] #[inline]
pub unsafe fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject) -> pptr<'p> pub unsafe fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject) -> pyptr<'p>
{ {
if ptr.is_null() { if ptr.is_null() {
::err::panic_after_error(); ::err::panic_after_error();
} else { } else {
pptr::from_owned_ptr(py, ptr) pyptr::from_owned_ptr(py, ptr)
} }
} }
@ -47,25 +47,25 @@ impl<'p> pptr<'p> {
/// Returns `Err(PyErr)` if the pointer is `null`. /// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid. /// Unsafe because the pointer might be invalid.
pub unsafe fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject) pub unsafe fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<pptr<'p>> -> PyResult<pyptr<'p>>
{ {
if ptr.is_null() { if ptr.is_null() {
Err(PyErr::fetch(py)) Err(PyErr::fetch(py))
} else { } else {
Ok(pptr::from_owned_ptr(py, ptr)) Ok(pyptr::from_owned_ptr(py, ptr))
} }
} }
/// Creates a pptr<'p> instance for the given FFI pointer. /// Creates a pyptr<'p> instance for the given FFI pointer.
/// This moves ownership over the pointer into the pptr<'p>. /// This moves ownership over the pointer into the pyptr<'p>.
/// Returns None for null pointers; undefined behavior if the pointer is invalid. /// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline] #[inline]
pub unsafe fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) pub unsafe fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<pptr<'p>> { -> Option<pyptr<'p>> {
if ptr.is_null() { if ptr.is_null() {
None None
} else { } else {
Some(pptr::from_owned_ptr(py, ptr)) Some(pyptr::from_owned_ptr(py, ptr))
} }
} }
@ -73,23 +73,23 @@ impl<'p> pptr<'p> {
/// Calls Py_INCREF() on the ptr. /// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid. /// Undefined behavior if the pointer is NULL or invalid.
#[inline] #[inline]
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> pptr<'p> { pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> pyptr<'p> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0); debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr); ffi::Py_INCREF(ptr);
pptr(py, ptr) pyptr(py, ptr)
} }
/// Creates a Py instance for the given FFI pointer. /// Creates a Py instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr. /// Calls Py_INCREF() on the ptr.
#[inline] #[inline]
pub unsafe fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) pub unsafe fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<pptr<'p>> { -> Option<pyptr<'p>> {
if ptr.is_null() { if ptr.is_null() {
None None
} else { } else {
debug_assert!(ffi::Py_REFCNT(ptr) > 0); debug_assert!(ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr); ffi::Py_INCREF(ptr);
Some(pptr(py, ptr)) Some(pyptr(py, ptr))
} }
} }
@ -106,13 +106,13 @@ impl<'p> pptr<'p> {
/// Cast from ffi::PyObject ptr to a concrete object. /// Cast from ffi::PyObject ptr to a concrete object.
#[inline] #[inline]
pub fn cast_from_owned_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn cast_from_owned_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<pptr<'p>, ::PyDowncastError<'p>> -> Result<pyptr<'p>, ::PyDowncastError<'p>>
where T: PyTypeInfo where T: PyTypeInfo
{ {
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 }; let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
if checked { if checked {
Ok( unsafe { pptr::from_owned_ptr(py, ptr) }) Ok( unsafe { pyptr::from_owned_ptr(py, ptr) })
} else { } else {
Err(::PyDowncastError(py, None)) Err(::PyDowncastError(py, None))
} }
@ -121,13 +121,13 @@ impl<'p> pptr<'p> {
/// Cast from ffi::PyObject ptr to a concrete object. /// Cast from ffi::PyObject ptr to a concrete object.
#[inline] #[inline]
pub fn cast_from_borrowed_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn cast_from_borrowed_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<pptr<'p>, ::PyDowncastError<'p>> -> Result<pyptr<'p>, ::PyDowncastError<'p>>
where T: PyTypeInfo where T: PyTypeInfo
{ {
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 }; let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
if checked { if checked {
Ok( unsafe { pptr::from_borrowed_ptr(py, ptr) }) Ok( unsafe { pyptr::from_borrowed_ptr(py, ptr) })
} else { } else {
Err(::PyDowncastError(py, None)) Err(::PyDowncastError(py, None))
} }
@ -136,30 +136,30 @@ impl<'p> pptr<'p> {
/// Cast from ffi::PyObject ptr to a concrete object. /// Cast from ffi::PyObject ptr to a concrete object.
#[inline] #[inline]
pub unsafe fn cast_from_owned_ptr_or_panic<T>(py: Python<'p>, pub unsafe fn cast_from_owned_ptr_or_panic<T>(py: Python<'p>,
ptr: *mut ffi::PyObject) -> pptr<'p> ptr: *mut ffi::PyObject) -> pyptr<'p>
where T: PyTypeInfo where T: PyTypeInfo
{ {
if ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 { if ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 {
pptr::from_owned_ptr(py, ptr) pyptr::from_owned_ptr(py, ptr)
} else { } else {
::err::panic_after_error(); ::err::panic_after_error();
} }
} }
#[inline] #[inline]
pub fn cast_from_owned_nullptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject) pub fn cast_from_owned_ptr_or_err<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<pptr<'p>> -> PyResult<pyptr<'p>>
where T: PyTypeInfo where T: PyTypeInfo
{ {
if ptr.is_null() { if ptr.is_null() {
Err(PyErr::fetch(py)) Err(PyErr::fetch(py))
} else { } else {
pptr::cast_from_owned_ptr::<T>(py, ptr).map_err(|e| e.into()) pyptr::cast_from_owned_ptr::<T>(py, ptr).map_err(|e| e.into())
} }
} }
} }
impl<'p> ToPythonPointer for pptr<'p> { impl<'p> ToPythonPointer for pyptr<'p> {
/// Gets the underlying FFI pointer, returns a borrowed pointer. /// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline] #[inline]
fn as_ptr(&self) -> *mut ffi::PyObject { fn as_ptr(&self) -> *mut ffi::PyObject {
@ -167,7 +167,7 @@ impl<'p> ToPythonPointer for pptr<'p> {
} }
} }
impl<'p> IntoPythonPointer for pptr<'p> { impl<'p> IntoPythonPointer for pyptr<'p> {
/// Gets the underlying FFI pointer, returns a owned pointer. /// Gets the underlying FFI pointer, returns a owned pointer.
#[inline] #[inline]
#[must_use] #[must_use]
@ -178,19 +178,19 @@ impl<'p> IntoPythonPointer for pptr<'p> {
} }
} }
/// Dropping a `pptr` instance decrements the reference count on the object by 1. /// Dropping a `pyptr` instance decrements the reference count on the object by 1.
impl<'p> Drop for pptr<'p> { impl<'p> Drop for pyptr<'p> {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
println!("drop pptr: {:?} {} {:?}", println!("drop pyptr: {:?} {} {:?}",
self.1, ffi::Py_REFCNT(self.1), &self as *const _); self.1, ffi::Py_REFCNT(self.1), &self as *const _);
} }
unsafe { ffi::Py_DECREF(self.1); } unsafe { ffi::Py_DECREF(self.1); }
} }
} }
impl<'p> std::fmt::Debug for pptr<'p> { impl<'p> std::fmt::Debug for pyptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let repr = unsafe { ::PyString::downcast_from_owned_ptr( let repr = unsafe { ::PyString::downcast_from_owned_ptr(
self.0, ffi::PyObject_Repr(self.1)) }; self.0, ffi::PyObject_Repr(self.1)) };
@ -199,7 +199,7 @@ impl<'p> std::fmt::Debug for pptr<'p> {
} }
} }
impl<'p> std::fmt::Display for pptr<'p> { impl<'p> std::fmt::Display for pyptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let ob = unsafe { ::PyString::downcast_from_owned_ptr( let ob = unsafe { ::PyString::downcast_from_owned_ptr(
self.0, ffi::PyObject_Str(self.1)) }; self.0, ffi::PyObject_Str(self.1)) };

View file

@ -9,10 +9,10 @@ use std::os::raw::c_int;
use ffi; use ffi;
use typeob::{PyTypeInfo, PyTypeObject, PyObjectAlloc}; use typeob::{PyTypeInfo, PyTypeObject, PyObjectAlloc};
use token::{PyObjectMarker, PythonToken}; use token::{PythonToken};
use objects::{PyObject, PyType, PyBool, PyDict, PyModule}; use objects::{PyObject, PyType, PyBool, PyDict, PyModule};
use err::{PyErr, PyResult, PyDowncastError}; use err::{PyErr, PyResult, PyDowncastError};
use pyptr::{Py, PyPtr}; use pointers::{Py, PyPtr, pptr};
use pythonrun::GILGuard; use pythonrun::GILGuard;
@ -42,9 +42,8 @@ pub trait PyDowncastFrom<'p> : Sized {
/// Trait implemented by Python object types that allow a checked downcast. /// Trait implemented by Python object types that allow a checked downcast.
pub trait PyDowncastInto<'p> : Sized { pub trait PyDowncastInto<'p> : Sized {
/// Cast from PyObject to a concrete Python object type. /// Cast Self to a concrete Python object type.
fn downcast_into<I>(Python<'p>, I) fn downcast_into<I>(Python<'p>, I) -> Result<Self, PyDowncastError<'p>>
-> Result<Self, PyDowncastError<'p>>
where I: ToPythonPointer + IntoPythonPointer; where I: ToPythonPointer + IntoPythonPointer;
/// Cast from ffi::PyObject to a concrete Python object type. /// Cast from ffi::PyObject to a concrete Python object type.
@ -216,8 +215,8 @@ impl<'p> Python<'p> {
/// Gets the Python builtin value `None`. /// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase #[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline] #[inline]
pub fn None(self) -> PyPtr<PyObjectMarker> { pub fn None(self) -> pptr {
unsafe { PyPtr::from_borrowed_ptr(ffi::Py_None()) } unsafe { pptr::from_borrowed_ptr(ffi::Py_None()) }
} }
/// Gets the Python builtin value `True`. /// Gets the Python builtin value `True`.
@ -237,8 +236,8 @@ impl<'p> Python<'p> {
/// Gets the Python builtin value `NotImplemented`. /// Gets the Python builtin value `NotImplemented`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase #[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline] #[inline]
pub fn NotImplemented(self) -> PyPtr<PyObjectMarker> { pub fn NotImplemented(self) -> pptr {
unsafe { PyPtr::from_borrowed_ptr(ffi::Py_NotImplemented()) } unsafe { pptr::from_borrowed_ptr(ffi::Py_NotImplemented()) }
} }
/// Execute closure `F` with Python instance. /// Execute closure `F` with Python instance.

View file

@ -4,7 +4,7 @@ use std::fmt;
use std::marker::PhantomData; use std::marker::PhantomData;
use ffi; use ffi;
use pyptr::{Py, PyPtr}; use pointers::{Py, PyPtr};
use err::{PyResult}; use err::{PyResult};
use python::{Python, ToPythonPointer, PyDowncastInto}; use python::{Python, ToPythonPointer, PyDowncastInto};
use objects::PyString; use objects::PyString;

View file

@ -7,7 +7,7 @@ use std::collections::HashMap;
use {ffi, class}; use {ffi, class};
use err::{PyErr, PyResult}; use err::{PyErr, PyResult};
use pyptr::{Py}; use pointers::{Py};
use python::{Python}; use python::{Python};
use objects::PyType; use objects::PyType;
use callback::AbortOnDrop; use callback::AbortOnDrop;

View file

@ -316,7 +316,7 @@ impl StaticMethod {
#[py::class] #[py::class]
struct GCIntegration { struct GCIntegration {
self_ref: RefCell<PyPtr<PyObjectMarker>>, self_ref: RefCell<pptr>,
dropped: TestDropCall, dropped: TestDropCall,
token: PythonToken<GCIntegration>, token: PythonToken<GCIntegration>,
} }
@ -343,7 +343,7 @@ fn gc_integration() {
dropped: TestDropCall { drop_called: drop_called.clone() }, dropped: TestDropCall { drop_called: drop_called.clone() },
token: t}); token: t});
*inst.self_ref.borrow_mut() = inst.clone_ref().into_object().into_pptr(); *inst.self_ref.borrow_mut() = inst.clone_ref().park();
drop(inst); drop(inst);
py.run("import gc; gc.collect()", None, None).unwrap(); py.run("import gc; gc.collect()", None, None).unwrap();
@ -804,7 +804,7 @@ impl PyObjectProtocol for RichComparisons2 {
} }
fn __richcmp__(&self, py: Python, fn __richcmp__(&self, py: Python,
other: &'p PyObject<'p>, op: CompareOp) -> PyResult<PyPtr<PyObjectMarker>> { other: &'p PyObject<'p>, op: CompareOp) -> PyResult<pptr> {
match op { match op {
CompareOp::Eq => Ok(true.to_object(py).park()), CompareOp::Eq => Ok(true.to_object(py).park()),
CompareOp::Ne => Ok(false.to_object(py).park()), CompareOp::Ne => Ok(false.to_object(py).park()),