add mirror ptr types for native py classes

This commit is contained in:
Nikolay Kim 2017-05-31 15:52:13 -07:00
parent 0b47d44562
commit 2f3ea202b3
23 changed files with 368 additions and 187 deletions

View File

@ -570,8 +570,8 @@ impl_element!(f64, Float);
mod test {
use std;
use python::{Python};
use conversion::ToPyObject;
use objects::{PyList, PyTuple};//, PySequence, PyIterator};
//use conversion::ToPyObject;
//use objects::{PyList, PyTuple};//, PySequence, PyIterator};
use objectprotocol::ObjectProtocol;
use super::PyBuffer;

View File

@ -1,9 +1,7 @@
use ffi;
use err::PyResult;
use pointers::PyObjectPtr;
use python::{Python, ToPythonPointer, PyDowncastFrom};
use python::{Python, ToPythonPointer, PyDowncastFrom, Park};
use objects::{PyObject, PyTuple};
use native::PyNativeObject;
use typeob::PyTypeInfo;
@ -31,7 +29,7 @@ pub trait IntoPyObject {
/// Converts self into a Python object. (Consumes self)
#[inline]
fn into_object(self, py: Python) -> PyObjectPtr
fn into_object(self, py: Python) -> ::objects::PyObjectPtr
where Self: Sized;
}
@ -102,7 +100,7 @@ impl <'p, T: ?Sized> RefFromPyObject<'p> for T
impl<T> IntoPyObject for T where T: ToPyObject
{
#[inline]
default fn into_object(self, py: Python) -> PyObjectPtr
default fn into_object(self, py: Python) -> ::PyObjectPtr
{
self.to_object(py).park()
}
@ -133,17 +131,17 @@ impl <T> ToPyObject for Option<T> where T: ToPyObject {
fn to_object<'p>(&self, py: Python<'p>) -> PyObject<'p> {
match *self {
Some(ref val) => val.to_object(py),
None => py.None().into_object(py),
None => py.None(),
}
}
}
impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
fn into_object(self, py: Python) -> PyObjectPtr {
fn into_object(self, py: Python) -> ::PyObjectPtr {
match self {
Some(val) => val.into_object(py),
None => py.None()
None => py.None().park()
}
}
}
@ -151,7 +149,7 @@ impl<T> IntoPyObject for Option<T> where T: IntoPyObject {
/// `()` is converted to Python `None`.
impl ToPyObject for () {
fn to_object<'p>(&self, py: Python<'p>) -> PyObject<'p> {
py.None().into_object(py)
py.None()
}
}

View File

@ -4,9 +4,8 @@ use std::os::raw::c_char;
use libc;
use ffi;
use pointers::PyObjectPtr;
use python::{ToPythonPointer, IntoPythonPointer, Python};
use objects::{PyObject, PyType, exc};
use python::{ToPythonPointer, IntoPythonPointer, Python, Park, Unpark, PyDowncastInto};
use objects::{PyObject, PyObjectPtr, PyType, PyTypePtr, exc};
use native::PyNativeObject;
use typeob::{PyTypeObject};
use conversion::{ToPyObject, ToPyTuple, IntoPyObject};
@ -82,7 +81,7 @@ macro_rules! py_exception {
#[derive(Debug)]
pub struct PyErr {
/// The type of the exception. This should be either a `PyClass` or a `PyType`.
pub ptype: PyObjectPtr,
pub ptype: PyTypePtr,
/// The value of the exception.
///
/// This can be either an instance of `ptype`,
@ -176,14 +175,14 @@ impl PyErr {
ptype: if ptype.is_null() {
py.get_type::<exc::SystemError>().park()
} else {
PyObjectPtr::from_owned_ptr(ptype)
PyTypePtr::from_owned_ptr(ptype)
},
pvalue: PyObjectPtr::from_owned_ptr_or_opt(pvalue),
ptraceback: PyObjectPtr::from_owned_ptr_or_opt(ptraceback)
}
}
fn new_helper(_py: Python, ty: PyObjectPtr, value: PyObjectPtr) -> PyErr {
fn new_helper(_py: Python, ty: PyTypePtr, value: PyObjectPtr) -> PyErr {
assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } != 0);
PyErr {
ptype: ty,
@ -204,14 +203,14 @@ impl PyErr {
fn from_instance_helper<'p>(py: Python, obj: PyObjectPtr) -> PyErr {
if unsafe { ffi::PyExceptionInstance_Check(obj.as_ptr()) } != 0 {
PyErr {
ptype: unsafe { PyObjectPtr::from_borrowed_ptr(
ptype: unsafe { PyTypePtr::from_borrowed_ptr(
ffi::PyExceptionInstance_Class(obj.as_ptr())) },
pvalue: Some(obj),
ptraceback: None
}
} else if unsafe { ffi::PyExceptionClass_Check(obj.as_ptr()) } != 0 {
PyErr {
ptype: obj,
ptype: PyTypePtr::downcast_into(py, obj).unwrap(),
pvalue: None,
ptraceback: None
}
@ -246,7 +245,7 @@ impl PyErr {
let pval = args.to_py_tuple(py);
PyErr {
ptype: exc.park(),
pvalue: Some(pval.park()),
pvalue: Some(pval.into_object(py)),
ptraceback: None
}
}
@ -309,7 +308,7 @@ impl PyErr {
self.normalize(py);
match self.pvalue {
Some(ref instance) => instance.as_object(py).clone_object(),
None => py.None().as_object(py).clone_object(),
None => py.None().as_object().clone_object(),
}
}

View File

@ -65,7 +65,7 @@ pub mod ffi;
pub use ffi::{Py_ssize_t, Py_hash_t};
pub mod pointers;
pub use pointers::{Py, PyPtr, PyObjectPtr};
pub use pointers::{Py, PyPtr, PPyPtr};
mod ppptr;
pub use ppptr::{pyptr};
@ -76,7 +76,9 @@ pub use token::{PythonToken, PythonObjectWithToken, PythonObjectWithGilToken};
pub use err::{PyErr, PyResult, PyDowncastError};
pub use objects::*;
pub use objectprotocol::ObjectProtocol;
pub use python::{Python, ToPythonPointer, IntoPythonPointer, PyDowncastFrom, PyDowncastInto};
pub use python::{Python, ToPythonPointer, IntoPythonPointer,
Park, Unpark,
PyDowncastFrom, PyDowncastInto};
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
pub use conversion::{FromPyObject, RefFromPyObject, ToPyObject, IntoPyObject, ToPyTuple};
pub use class::{CompareOp};
@ -152,7 +154,7 @@ pub use std::os::raw::*;
///
/// fn run(py: Python) -> PyResult<PyObject> {
/// println!("Rust says: Hello Python!");
/// Ok(py.None().into_object(py))
/// Ok(py.None())
/// }
/// # fn main() {}
/// ```

View File

@ -1,14 +1,11 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use pointers::PyObjectPtr;
use objects::PyObject;
use objects::{PyObject};
pub trait PyBaseObject : Sized {}
pub trait PyNativeObject<'p> : PyBaseObject {
fn park(self) -> PyObjectPtr;
fn as_object(self) -> PyObject<'p>;
fn clone_object(&self) -> Self;

View File

@ -8,7 +8,7 @@ use std::cmp::Ordering;
use ffi;
use libc;
use pyptr;
use pointers::{PyObjectPtr, Py, PyPtr};
use pointers::{Py, PyPtr, PPyPtr};
use python::{Python, PyDowncastInto, ToPythonPointer};
use objects::{PyObject, PyDict, PyString, PyIterator};
use token::PythonObjectWithGilToken;
@ -427,7 +427,7 @@ impl<'p, T> fmt::Display for PyPtr<T> where T: ObjectProtocol<'p> + PyTypeInfo {
}
impl fmt::Debug for PyObjectPtr {
impl fmt::Debug for PPyPtr {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();
@ -439,7 +439,7 @@ impl fmt::Debug for PyObjectPtr {
}
}
impl fmt::Display for PyObjectPtr {
impl fmt::Display for PPyPtr {
default fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
let gil = Python::acquire_gil();
let py = gil.python();

View File

@ -1,5 +1,6 @@
use pyptr;
use ffi;
use pointers::PPyPtr;
use python::{ToPythonPointer, Python};
use objects::PyObject;
use native::PyNativeObject;
@ -7,8 +8,10 @@ use conversion::ToPyObject;
/// Represents a Python `bool`.
pub struct PyBool<'p>(pyptr<'p>);
pub struct PyBoolPtr(PPyPtr);
pyobject_nativetype!(PyBool, PyBool_Check, PyBool_Type, PyBoolPtr);
pyobject_nativetype!(PyBool, PyBool_Check, PyBool_Type);
impl<'p> PyBool<'p> {
/// Depending on `val`, returns `py.True()` or `py.False()`.

View File

@ -8,13 +8,15 @@ use python::{Python, ToPythonPointer};
use objects::PyObject;
use err::{PyResult, PyErr};
use ppptr::pyptr;
use pointers::PPyPtr;
use token::PythonObjectWithGilToken;
/// Represents a Python bytearray.
pub struct PyByteArray<'p>(pyptr<'p>);
pub struct PyByteArrayPtr(PPyPtr);
pyobject_nativetype!(PyByteArray, PyByteArray_Check, PyByteArray_Type);
pyobject_nativetype!(PyByteArray, PyByteArray_Check, PyByteArray_Type, PyByteArrayPtr);
impl<'p> PyByteArray<'p> {
@ -101,7 +103,7 @@ mod test {
assert_eq!(20, bytearray.len());
let none = py.None();
if let Err(mut err) = PyByteArray::from(none.as_object(py)) {
if let Err(mut err) = PyByteArray::from(&none) {
assert!(exc::TypeError::type_object(py).is_instance(&err.instance(py)))
} else {
panic!("error");

View File

@ -6,6 +6,7 @@ use std::{mem, collections, hash, cmp};
use ffi;
use pyptr;
use pointers::PPyPtr;
use python::{Python, ToPythonPointer, PyDowncastInto};
use conversion::{ToPyObject};
use objects::{PyObject, PyList};
@ -15,8 +16,9 @@ use native::PyNativeObject;
/// Represents a Python `dict`.
pub struct PyDict<'p>(pyptr<'p>);
pub struct PyDictPtr(PPyPtr);
pyobject_nativetype!(PyDict, PyDict_Check, PyDict_Type);
pyobject_nativetype!(PyDict, PyDict_Check, PyDict_Type, PyDictPtr);
impl<'p> PyDict<'p> {

View File

@ -9,12 +9,10 @@ use std::{self, mem, ops};
use std::ffi::CStr;
use ffi;
use pointers::PyObjectPtr;
use python::{Python, ToPythonPointer};
use python::{Python, ToPythonPointer, Park};
use err::PyResult;
use native::PyNativeObject;
use super::tuple::PyTuple;
use super::typeobject::PyType;
use super::{PyTuple, PyType, PyTypePtr};
macro_rules! exc_type(
($name:ident, $exc_name:ident) => (
@ -86,10 +84,10 @@ exc_type!(UnicodeTranslateError, PyExc_UnicodeTranslateError);
impl UnicodeDecodeError {
pub fn new(py: Python, encoding: &CStr, input: &[u8], range: ops::Range<usize>, reason: &CStr)
-> PyResult<PyObjectPtr> {
-> PyResult<PyTypePtr> {
unsafe {
let input: &[c_char] = mem::transmute(input);
PyObjectPtr::from_owned_ptr_or_err(
PyTypePtr::from_owned_ptr_or_err(
py, ffi::PyUnicodeDecodeError_Create(
encoding.as_ptr(),
input.as_ptr(),
@ -101,7 +99,7 @@ impl UnicodeDecodeError {
}
pub fn new_utf8<'p>(py: Python, input: &[u8], err: std::str::Utf8Error)
-> PyResult<PyObjectPtr>
-> PyResult<PyTypePtr>
{
let pos = err.valid_up_to();
UnicodeDecodeError::new(py, cstr!("utf-8"), input, pos .. pos+1, cstr!("invalid utf-8"))

View File

@ -5,15 +5,17 @@
use ::pyptr;
use err::{self, PyResult};
use ffi::{self, Py_ssize_t};
use python::{Python, ToPythonPointer, IntoPythonPointer};
use pointers::PPyPtr;
use python::{Python, ToPythonPointer, IntoPythonPointer, Park};
use objects::PyObject;
use token::PythonObjectWithGilToken;
use conversion::{ToPyObject, IntoPyObject};
/// Represents a Python `list`.
pub struct PyList<'p>(pyptr<'p>);
pub struct PyListPtr(PPyPtr);
pyobject_nativetype!(PyList, PyList_Check, PyList_Type);
pyobject_nativetype!(PyList, PyList_Check, PyList_Type, PyListPtr);
impl<'p> PyList<'p> {
/// Construct a new list with the given elements.
@ -131,7 +133,7 @@ impl <T> IntoPyObject for Vec<T> where T: IntoPyObject {
let obj = e.into_object(py).into_ptr();
ffi::PyList_SetItem(ptr, i as Py_ssize_t, obj);
}
::PyObjectPtr::from_owned_ptr_or_panic(ptr)
::PyObject::from_owned_ptr_or_panic(py, ptr).park()
}
}
}
@ -139,6 +141,7 @@ impl <T> IntoPyObject for Vec<T> where T: IntoPyObject {
#[cfg(test)]
mod test {
use python::{Python, PyDowncastInto};
use native::PyNativeObject;
use conversion::{ToPyObject, IntoPyObject};
use objects::PyList;
@ -210,7 +213,7 @@ mod test {
let py = gil.python();
let v = vec![2, 3, 5, 7];
let list = PyList::downcast_into(py, v.to_object(py)).unwrap();
let v2 = list.into_object(py).into_object(py).extract::<Vec<i32>>().unwrap();
let v2 = list.as_object().extract::<Vec<i32>>().unwrap();
assert_eq!(v, v2);
}
}

View File

@ -1,19 +1,19 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
pub use self::object::PyObject;
pub use self::typeobject::PyType;
pub use self::module::PyModule;
pub use self::string::{PyBytes, PyString, PyStringData};
pub use self::object::{PyObject, PyObjectPtr};
pub use self::typeobject::{PyType, PyTypePtr};
pub use self::module::{PyModule, PyModulePtr};
pub use self::string::{PyBytes, PyBytesPtr, PyString, PyStringPtr, PyStringData};
pub use self::iterator::PyIterator;
pub use self::boolobject::PyBool;
pub use self::bytearray::PyByteArray;
pub use self::tuple::{PyTuple, NoArgs};
pub use self::dict::PyDict;
pub use self::list::PyList;
pub use self::num::{PyLong, PyFloat};
pub use self::boolobject::{PyBool, PyBoolPtr};
pub use self::bytearray::{PyByteArray, PyByteArrayPtr};
pub use self::tuple::{PyTuple, PyTuplePtr, NoArgs};
pub use self::dict::{PyDict, PyDictPtr};
pub use self::list::{PyList, PyListPtr};
pub use self::num::{PyLong, PyLongPtr, PyFloat, PyFloatPtr};
pub use self::sequence::PySequence;
pub use self::slice::PySlice;
pub use self::set::{PySet, PyFrozenSet};
pub use self::slice::{PySlice, PySlicePtr};
pub use self::set::{PySet, PySetPtr, PyFrozenSet, PyFrozenSetPtr};
#[macro_export]
@ -45,15 +45,130 @@ macro_rules! pyobject_nativetype(
pyobject_nativetype!($name, $checkfunction);
};
($name: ident, $checkfunction: ident, $typeobject: ident, $ptr: ident) => {
impl<'p> $crate::python::Park for $name<'p> {
type Target = $ptr;
fn park(self) -> $ptr {
unsafe {$crate::std::mem::transmute(self)}
}
}
impl<'p> $crate::python::Unpark<'p> for $ptr {
type Target = $name<'p>;
fn unpark(self, _py: $crate::Python<'p>) -> $name<'p> {
unsafe {$crate::std::mem::transmute(self)}
}
}
impl $crate::std::ops::Deref for $ptr {
type Target = PPyPtr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl $crate::IntoPyObject for $ptr {
#[inline]
fn into_object(self, _py: $crate::Python) -> $crate::PyObjectPtr
{
unsafe { $crate::std::mem::transmute(self) }
}
}
impl $crate::python::IntoPythonPointer for $ptr {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
fn into_ptr(self) -> *mut $crate::ffi::PyObject {
unsafe {$crate::std::mem::transmute(self)}
}
}
impl $crate::python::ToPythonPointer for $ptr {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
fn as_ptr(&self) -> *mut $crate::ffi::PyObject {
self.0.as_ptr()
}
}
impl<'p> $crate::python::PyDowncastInto<'p> for $ptr
{
fn downcast_into<I>(py: $crate::Python<'p>, ob: I)
-> Result<Self, $crate::PyDowncastError<'p>>
where I: $crate::ToPythonPointer + $crate::IntoPythonPointer
{
unsafe{
let ptr = ob.into_ptr();
if ffi::$checkfunction(ptr) != 0 {
Ok($ptr($crate::PPyPtr::from_owned_ptr(ptr)))
} else {
$crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None))
}
}
}
fn downcast_from_owned_ptr(py: $crate::Python<'p>, ptr: *mut $crate::ffi::PyObject)
-> Result<$ptr, $crate::PyDowncastError<'p>>
{
unsafe{
if ffi::$checkfunction(ptr) != 0 {
Ok($ptr($crate::PPyPtr::from_owned_ptr(ptr)))
} else {
$crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None))
}
}
}
}
impl $crate::std::fmt::Debug for $ptr {
fn fmt(&self, f : &mut $crate::std::fmt::Formatter)
-> Result<(), $crate::std::fmt::Error>
{
use objectprotocol::ObjectProtocol;
let gil = $crate::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(|_| $crate::std::fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
impl $crate::std::fmt::Display for $ptr {
fn fmt(&self, f : &mut $crate::std::fmt::Formatter)
-> Result<(), $crate::std::fmt::Error>
{
use objectprotocol::ObjectProtocol;
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(|_| $crate::std::fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
pyobject_nativetype!($name, $checkfunction, $typeobject);
};
($name: ident, $checkfunction: ident) => (
impl<'p> $crate::native::PyBaseObject for $name<'p> {}
impl<'p> $crate::native::PyNativeObject<'p> for $name<'p> {
fn park(self) -> $crate::PyObjectPtr {
unsafe { $crate::std::mem::transmute(self) }
}
//fn park(self) -> $crate::PyObjectPtr {
// unsafe { $crate::std::mem::transmute(self) }
//}
fn as_object(self) -> $crate::PyObject<'p> {
unsafe {
$crate::ffi::Py_INCREF(self.as_ptr());

View File

@ -9,6 +9,7 @@ use std::ffi::{CStr, CString};
use ::pyptr;
use conversion::{ToPyObject, ToPyTuple};
use pointers::PPyPtr;
use python::{ToPythonPointer, Python};
use token::PythonObjectWithGilToken;
use objects::{PyObject, PyDict, PyType, exc};
@ -18,8 +19,9 @@ use err::{PyResult, PyErr};
/// Represents a Python module object.
pub struct PyModule<'p>(pyptr<'p>);
pub struct PyModulePtr(PPyPtr);
pyobject_nativetype!(PyModule, PyModule_Check, PyModule_Type);
pyobject_nativetype!(PyModule, PyModule_Check, PyModule_Type, PyModulePtr);
impl<'p> PyModule<'p> {

View File

@ -12,6 +12,7 @@ use pyptr;
use objects::exc;
use objects::PyObject;
use token::PythonObjectWithGilToken;
use pointers::PPyPtr;
use python::{ToPythonPointer, Python};
use err::{PyResult, PyErr};
use native::PyNativeObject;
@ -24,7 +25,8 @@ use conversion::{ToPyObject, FromPyObject};
/// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types.
pub struct PyLong<'p>(pyptr<'p>);
pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type);
pub struct PyLongPtr(PPyPtr);
pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type, PyLongPtr);
/// Represents a Python `float` object.
///
@ -33,7 +35,8 @@ pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type);
/// and [extract](struct.PyObject.html#method.extract)
/// with `f32`/`f64`.
pub struct PyFloat<'p>(pyptr<'p>);
pyobject_nativetype!(PyFloat, PyFloat_Check, PyFloat_Type);
pub struct PyFloatPtr(PPyPtr);
pyobject_nativetype!(PyFloat, PyFloat_Check, PyFloat_Type, PyFloatPtr);
impl<'p> PyFloat<'p> {

View File

@ -4,13 +4,16 @@ use std;
use ::pyptr;
use ffi;
use err::{PyResult, PyDowncastError};
use pointers::PPyPtr;
use err::{PyErr, PyResult, PyDowncastError};
use python::{Python, ToPythonPointer};
pub struct PyObject<'p>(pyptr<'p>);
pyobject_nativetype!(PyObject, PyObject_Check, PyBaseObject_Type);
pub struct PyObjectPtr(PPyPtr);
pyobject_nativetype!(PyObject, PyObject_Check, PyBaseObject_Type, PyObjectPtr);
impl<'p> PyObject<'p> {
@ -107,3 +110,83 @@ impl<'p> PartialEq for PyObject<'p> {
self.as_ptr() == other.as_ptr()
}
}
impl PyObjectPtr {
/// Creates a `PyObjectPtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyObjectPtr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> PyObjectPtr {
PyObjectPtr(PPyPtr::from_owned_ptr(ptr))
}
/// Creates a `PyObjectPtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyObjectPtr`.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub fn from_owned_ptr_or_opt(ptr: *mut ffi::PyObject) -> Option<PyObjectPtr> {
if ptr.is_null() {
None
} else {
Some(PyObjectPtr(unsafe{PPyPtr::from_owned_ptr(ptr)}))
}
}
/// Construct `PyObjectPtr` 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 fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject) -> PyResult<PyObjectPtr>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(PyObjectPtr(unsafe{PPyPtr::from_owned_ptr(ptr)}))
}
}
/// Construct `PyObjectPtr` 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) -> PyObjectPtr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
PyObjectPtr(PPyPtr::from_owned_ptr(ptr))
}
}
/// Creates a `PyObjectPtr` 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) -> PyObjectPtr {
PyObjectPtr(PPyPtr::from_borrowed_ptr(ptr))
}
/// Creates a `PyObjectPtr` 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 fn from_borrowed_ptr_or_opt(ptr: *mut ffi::PyObject) -> Option<PyObjectPtr> {
if ptr.is_null() {
None
} else {
Some(PyObjectPtr(unsafe{PPyPtr::from_borrowed_ptr(ptr)}))
}
}
/// Construct `PyObjectPtr` 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) -> PyObjectPtr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
PyObjectPtr(PPyPtr::from_borrowed_ptr(ptr))
}
}
}

View File

@ -5,6 +5,7 @@ use std::{hash, collections};
use ffi;
use pyptr;
use python::{Python, ToPythonPointer};
use pointers::PPyPtr;
use conversion::ToPyObject;
use objects::PyObject;
use err::{self, PyResult, PyErr};
@ -14,11 +15,14 @@ use token::{PythonObjectWithGilToken};
/// Represents a Python `set`
pub struct PySet<'p>(pyptr<'p>);
pub struct PySetPtr(PPyPtr);
/// Represents a Python `frozenset`
pub struct PyFrozenSet<'p>(pyptr<'p>);
pub struct PyFrozenSetPtr(PPyPtr);
pyobject_nativetype!(PySet, PySet_Check, PySet_Type);
pyobject_nativetype!(PyFrozenSet, PyFrozenSet_Check, PyFrozenSet_Type);
pyobject_nativetype!(PySet, PySet_Check, PySet_Type, PySetPtr);
pyobject_nativetype!(PyFrozenSet, PyFrozenSet_Check, PyFrozenSet_Type, PyFrozenSetPtr);
impl<'p> PySet<'p> {
/// Creates a new set.

View File

@ -3,6 +3,7 @@
use std::os::raw::c_long;
use ::pyptr;
use pointers::PPyPtr;
use python::{ToPythonPointer, Python};
use err::{PyErr, PyResult};
use ffi::{self, Py_ssize_t};
@ -11,6 +12,14 @@ use objects::PyObject;
use conversion::ToPyObject;
use token::PythonObjectWithGilToken;
/// Represents a Python `slice`. Only `c_long` indeces supprted
/// at the moment by PySlice object.
pub struct PySlice<'p>(pyptr<'p>);
pub struct PySlicePtr(PPyPtr);
pyobject_nativetype!(PySlice, PySlice_Check, PySlice_Type, PySlicePtr);
/// Represents a Python `slice` indices
pub struct PySliceIndices {
pub start: isize,
@ -31,12 +40,6 @@ impl PySliceIndices {
}
/// Represents a Python `slice`. Only `c_long` indeces supprted
/// at the moment by PySlice object.
pub struct PySlice<'p>(pyptr<'p>);
pyobject_nativetype!(PySlice, PySlice_Check, PySlice_Type);
impl<'p> PySlice<'p> {
/// Construct a new slice with the given elements.

View File

@ -10,6 +10,7 @@ use std::os::raw::c_char;
use ffi;
use pyptr;
use pointers::PPyPtr;
use python::{ToPythonPointer, Python};
use super::{exc, PyObject};
use token::PythonObjectWithGilToken;
@ -19,13 +20,13 @@ use conversion::{ToPyObject, RefFromPyObject};
/// Represents a Python string.
pub struct PyString<'p>(pyptr<'p>);
pyobject_nativetype!(PyString, PyUnicode_Check, PyUnicode_Type);
pub struct PyStringPtr(PPyPtr);
pyobject_nativetype!(PyString, PyUnicode_Check, PyUnicode_Type, PyStringPtr);
/// Represents a Python byte string.
pub struct PyBytes<'p>(pyptr<'p>);
pyobject_nativetype!(PyBytes, PyBytes_Check, PyBytes_Type);
pub struct PyBytesPtr(PPyPtr);
pyobject_nativetype!(PyBytes, PyBytes_Check, PyBytes_Type, PyBytesPtr);
/// Enum of possible Python string representations.

View File

@ -7,6 +7,7 @@ use std::slice;
use pyptr;
use ffi::{self, Py_ssize_t};
use err::{PyErr, PyResult};
use pointers::PPyPtr;
use python::{Python, ToPythonPointer, IntoPythonPointer};
use conversion::{FromPyObject, ToPyObject, ToPyTuple, IntoPyObject};
use objects::PyObject;
@ -16,8 +17,8 @@ use super::exc;
/// Represents a Python tuple object.
pub struct PyTuple<'p>(pyptr<'p>);
pyobject_nativetype!(PyTuple, PyTuple_Check, PyTuple_Type);
pub struct PyTuplePtr(PPyPtr);
pyobject_nativetype!(PyTuple, PyTuple_Check, PyTuple_Type, PyTuplePtr);
impl<'p> PyTuple<'p> {

View File

@ -8,15 +8,16 @@ use std::borrow::Cow;
use ::pyptr;
use ffi;
use token::PythonObjectWithGilToken;
use pointers::PPyPtr;
use python::{Python, ToPythonPointer};
use conversion::ToPyTuple;
use objects::{PyObject, PyDict};
use err::PyResult;
use err::{PyErr, PyResult};
/// Represents a reference to a Python type object.
pub struct PyType<'p>(pyptr<'p>);
pyobject_nativetype!(PyType, PyType_Check, PyType_Type);
pub struct PyTypePtr(PPyPtr);
pyobject_nativetype!(PyType, PyType_Check, PyType_Type, PyTypePtr);
impl<'p> PyType<'p> {
@ -74,3 +75,35 @@ impl<'p> PartialEq for PyType<'p> {
}
}
impl<'p> Eq for PyType<'p> { }
impl PyTypePtr {
/// Creates a `PyTypePtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyTypePtr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> PyTypePtr {
PyTypePtr(PPyPtr::from_owned_ptr(ptr))
}
/// Retrieves the owned PyTypePtr instance for the given FFI pointer.
/// Returns `Err(PyErr)` if the pointer is `null`; undefined behavior if the
/// pointer is invalid
#[inline]
pub unsafe fn from_owned_ptr_or_err(py: Python, ptr: *mut ffi::PyObject)
-> PyResult<PyTypePtr> {
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(PyTypePtr(PPyPtr::from_owned_ptr(ptr)))
}
}
/// Creates a `PyTypePtr` 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) -> PyTypePtr {
PyTypePtr(PPyPtr::from_owned_ptr(ptr))
}
}

View File

@ -8,100 +8,38 @@ use std::convert::{AsRef, AsMut};
use ffi;
use err::{PyErr, PyResult, PyDowncastError};
use conversion::{ToPyObject, IntoPyObject};
use objects::PyObject;
use objects::{PyObject, PyObjectPtr};
use python::{Python, ToPythonPointer, IntoPythonPointer};
use token::PythonObjectWithGilToken;
use typeob::{PyTypeInfo, PyObjectAlloc};
#[allow(non_camel_case_types)]
pub struct PyObjectPtr(*mut ffi::PyObject);
pub struct PPyPtr(*mut ffi::PyObject);
// `PyObjectPtr` is thread-safe, because all operations on it require a Python<'p> token.
unsafe impl Send for PyObjectPtr {}
unsafe impl Sync for PyObjectPtr {}
// `PPyPtr` is thread-safe, because any python related operations require a Python<'p> token.
unsafe impl Send for PPyPtr {}
unsafe impl Sync for PPyPtr {}
impl PyObjectPtr {
impl PPyPtr {
/// Creates a `PyObjectPtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyObjectPtr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> PyObjectPtr {
pub unsafe fn from_owned_ptr(ptr: *mut ffi::PyObject) -> PPyPtr {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
PyObjectPtr(ptr)
}
/// Creates a `PyObjectPtr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `PyObjectPtr`.
/// 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<PyObjectPtr> {
if ptr.is_null() {
None
} else {
Some(PyObjectPtr::from_owned_ptr(ptr))
}
}
/// Construct `PyObjectPtr` 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<PyObjectPtr>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(PyObjectPtr::from_owned_ptr(ptr))
}
}
/// Construct `PyObjectPtr` 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) -> PyObjectPtr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
PyObjectPtr::from_owned_ptr(ptr)
}
PPyPtr(ptr)
}
/// Creates a `PyObjectPtr` 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) -> PyObjectPtr {
pub unsafe fn from_borrowed_ptr(ptr: *mut ffi::PyObject) -> PPyPtr {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr);
PyObjectPtr::from_owned_ptr(ptr)
}
/// Creates a `PyObjectPtr` 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<PyObjectPtr> {
if ptr.is_null() {
None
} else {
Some(PyObjectPtr::from_borrowed_ptr(ptr))
}
}
/// Construct `PyObjectPtr` 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) -> PyObjectPtr
{
if ptr.is_null() {
::err::panic_after_error();
} else {
PyObjectPtr::from_borrowed_ptr(ptr)
}
PPyPtr::from_owned_ptr(ptr)
}
/// Gets the reference count of the PyObject pointer.
@ -125,8 +63,8 @@ impl PyObjectPtr {
/// Clone self, Calls Py_INCREF() on the ptr.
#[inline]
pub fn clone_ref(&self, _py: Python) -> PyObjectPtr {
unsafe { PyObjectPtr::from_borrowed_ptr(self.0) }
pub fn clone_ref(&self, _py: Python) -> PPyPtr {
unsafe { PPyPtr::from_borrowed_ptr(self.0) }
}
/// Casts the `PyObjectPtr` imstance to a concrete Python object type.
@ -137,18 +75,9 @@ impl PyObjectPtr {
{
<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 PyObjectPtr {
impl ToPythonPointer for PPyPtr {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
@ -156,7 +85,7 @@ impl ToPythonPointer for PyObjectPtr {
}
}
impl IntoPythonPointer for PyObjectPtr {
impl IntoPythonPointer for PPyPtr {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
@ -167,23 +96,16 @@ impl IntoPythonPointer for PyObjectPtr {
}
}
impl IntoPyObject for PyObjectPtr {
impl PartialEq for PPyPtr {
#[inline]
fn into_object(self, _py: Python) -> PyObjectPtr {
self
}
}
impl PartialEq for PyObjectPtr {
#[inline]
fn eq(&self, o: &PyObjectPtr) -> bool {
fn eq(&self, o: &PPyPtr) -> bool {
self.0 == o.0
}
}
/// Dropping a `PyObjectPtr` instance decrements the reference count on the object by 1.
impl Drop for PyObjectPtr {
/// Dropping a `PPyPtr` instance decrements the reference count on the object by 1.
impl Drop for PPyPtr {
fn drop(&mut self) {
unsafe {
@ -298,7 +220,7 @@ impl<T> ToPyObject for PyPtr<T> {
impl<T> IntoPyObject for PyPtr<T> {
#[inline]
fn into_object<'a>(self, _py: Python) -> PyObjectPtr {
fn into_object<'a>(self, _py: Python) -> ::PyObjectPtr {
self.park()
}
}
@ -498,7 +420,7 @@ impl <'a, T> ToPyObject for Py<'a, T> {
impl<'p, T> IntoPyObject for Py<'p, T> {
#[inline]
default fn into_object(self, _py: Python) -> PyObjectPtr {
default fn into_object(self, _py: Python) -> ::PyObjectPtr {
unsafe { std::mem::transmute(self) }
}
}

View File

@ -10,9 +10,9 @@ use std::os::raw::c_int;
use ffi;
use typeob::{PyTypeInfo, PyTypeObject, PyObjectAlloc};
use token::{PythonToken};
use objects::{PyObject, PyType, PyBool, PyDict, PyModule};
use objects::{PyObject, PyObjectPtr, PyType, PyBool, PyDict, PyModule};
use err::{PyErr, PyResult, PyDowncastError};
use pointers::{Py, PyObjectPtr};
use pointers::{Py};
use pythonrun::GILGuard;
@ -51,6 +51,16 @@ pub trait PyDowncastInto<'p> : Sized {
-> Result<Self, PyDowncastError<'p>>;
}
pub trait Park : Sized {
type Target;
fn park(self) -> Self::Target;
}
pub trait Unpark<'p> : Sized {
type Target;
fn unpark(self, py: Python<'p>) -> Self::Target;
}
/// This trait allows retrieving the underlying FFI pointer from Python objects.
pub trait ToPythonPointer {
@ -200,8 +210,8 @@ impl<'p> Python<'p> {
/// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
pub fn None(self) -> PyObjectPtr {
unsafe { PyObjectPtr::from_borrowed_ptr(ffi::Py_None()) }
pub fn None(self) -> PyObject<'p> {
unsafe { PyObject::from_borrowed_ptr(self, ffi::Py_None()) }
}
/// Gets the Python builtin value `True`.

View File

@ -328,7 +328,7 @@ impl PyGCProtocol for GCIntegration {
}
fn __clear__(&mut self, py: Python) {
*self.self_ref.borrow_mut() = py.None();
*self.self_ref.borrow_mut() = py.None().park();
}
}
@ -339,7 +339,7 @@ fn gc_integration() {
let drop_called = Arc::new(AtomicBool::new(false));
let mut inst = py.with_token(|t| GCIntegration{
self_ref: RefCell::new(py.None()),
self_ref: RefCell::new(py.None().park()),
dropped: TestDropCall { drop_called: drop_called.clone() },
token: t});