consistent naming for pointers

This commit is contained in:
Nikolay Kim 2017-06-01 10:35:02 -07:00
parent bcaaeb8522
commit 9176dc4df1
21 changed files with 281 additions and 380 deletions

69
src/fmt.rs Normal file
View File

@ -0,0 +1,69 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use std;
use std::fmt;
use ffi;
use typeob::PyTypeInfo;
use pointers::{Py, Ptr, PyPtr};
use python::{Python, PyDowncastInto, ToPythonPointer};
use objectprotocol::ObjectProtocol;
impl<'p> std::fmt::Debug for Ptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let repr = unsafe { ::PyString::downcast_from_owned_ptr(
self.token(), ffi::PyObject_Repr(self.as_ptr())) };
let repr = repr.map_err(|_| std::fmt::Error)?;
f.write_str(&repr.to_string_lossy())
}
}
impl<'p> std::fmt::Display for Ptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let ob = unsafe { ::PyString::downcast_from_owned_ptr(
self.token(), ffi::PyObject_Str(self.as_ptr())) };
let ob = ob.map_err(|_| std::fmt::Error)?;
f.write_str(&ob.to_string_lossy())
}
}
impl<'p, T> fmt::Debug for Py<'p, T> where T: ObjectProtocol<'p> + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when repr() fails
let repr_obj = try!(self.repr().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
impl<'p, T> fmt::Display for Py<'p, T> where T: ObjectProtocol<'p> + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when str() fails
let str_obj = try!(self.str().map_err(|_| fmt::Error));
f.write_str(&str_obj.to_string_lossy())
}
}
impl fmt::Debug for PyPtr {
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 PyPtr {
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())
}
}

View File

@ -67,9 +67,6 @@ pub use ffi::{Py_ssize_t, Py_hash_t};
pub mod pointers;
pub use pointers::{Py, PyPtr};
mod ppptr;
pub use ppptr::{pyptr};
mod token;
pub use token::{PythonToken, PythonObjectWithToken, PythonObjectWithGilToken};
@ -116,6 +113,7 @@ macro_rules! py_replace_expr {
pub mod python;
mod native;
mod fmt;
mod err;
mod conversion;
mod objects;

View File

@ -11,23 +11,3 @@ pub trait PyNativeObject<'p> : PyBaseObject {
fn clone_object(&self) -> Self;
}
/*impl<'a, T: Sized> FromPyObject<'a> for T
where T: PyNativeObject + PythonObjectWithCheckedDowncast
{
/// Extracts `Self` from the source `Py<PyObject>`.
fn extract<S>(py: &'a Py<'a, S>) -> PyResult<Self> where S: PyTypeInfo
{
<T as PythonObjectWithCheckedDowncast>
::downcast_from(py.clone_ref()).map_err(|e| e.into())
}
}*/
/*impl<T> ::IntoPyObject for T where T: PyNativeObject
{
#[inline]
default fn into_object(self, py: Python) -> ::PyPtr<PyObject>
{
unsafe { ::std::mem::transmute(self) }
}
}*/

View File

@ -2,19 +2,16 @@
//
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use std::fmt;
use libc;
use std::cmp::Ordering;
use ffi;
use libc;
use pyptr;
use pointers::{Py, PyPtr};
use err::{PyErr, PyResult, self};
use pointers::Ptr;
use python::{Python, PyDowncastInto, ToPythonPointer};
use objects::{PyObject, PyDict, PyString, PyIterator};
use token::PythonObjectWithGilToken;
use conversion::{ToPyObject, ToPyTuple};
use typeob::PyTypeInfo;
use err::{PyErr, PyResult, self};
pub trait ObjectProtocol<'p> {
@ -374,7 +371,7 @@ impl<'p, T> ObjectProtocol<'p> for T where T: PythonObjectWithGilToken<'p> + ToP
#[inline]
fn iter(&self) -> PyResult<PyIterator<'p>> {
unsafe {
let ptr = pyptr::from_owned_ptr_or_err(
let ptr = Ptr::from_owned_ptr_or_err(
self.gil(), ffi::PyObject_GetIter(self.as_ptr()))?;
PyIterator::from_object(self.gil(), ptr).map_err(|e| e.into())
}
@ -385,47 +382,6 @@ impl<'p, T> ObjectProtocol<'p> for T where T: PythonObjectWithGilToken<'p> + ToP
}
}
impl<'p, T> fmt::Debug for Py<'p, T> where T: ObjectProtocol<'p> + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when repr() fails
let repr_obj = try!(self.repr().map_err(|_| fmt::Error));
f.write_str(&repr_obj.to_string_lossy())
}
}
impl<'p, T> fmt::Display for Py<'p, T> where T: ObjectProtocol<'p> + PyTypeInfo {
fn fmt(&self, f : &mut fmt::Formatter) -> Result<(), fmt::Error> {
// TODO: we shouldn't use fmt::Error when str() fails
let str_obj = try!(self.str().map_err(|_| fmt::Error));
f.write_str(&str_obj.to_string_lossy())
}
}
impl fmt::Debug for PyPtr {
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 PyPtr {
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)]
mod test {
use python::{Python};

View File

@ -1,13 +1,12 @@
use pyptr;
use ffi;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{ToPythonPointer, Python};
use objects::PyObject;
use native::PyNativeObject;
use conversion::ToPyObject;
/// Represents a Python `bool`.
pub struct PyBool<'p>(pyptr<'p>);
pub struct PyBool<'p>(Ptr<'p>);
pub struct PyBoolPtr(PyPtr);
pyobject_nativetype!(PyBool, PyBool_Check, PyBool_Type, PyBoolPtr);
@ -18,7 +17,7 @@ impl<'p> PyBool<'p> {
#[inline]
pub fn new(py: Python<'p>, val: bool) -> PyBool<'p> {
unsafe { PyBool(
pyptr::from_borrowed_ptr(py, if val { ffi::Py_True() } else { ffi::Py_False() })
Ptr::from_borrowed_ptr(py, if val { ffi::Py_True() } else { ffi::Py_False() })
)}
}

View File

@ -7,13 +7,12 @@ use ffi;
use python::{Python, ToPythonPointer};
use objects::PyObject;
use err::{PyResult, PyErr};
use ppptr::pyptr;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use token::PythonObjectWithGilToken;
/// Represents a Python bytearray.
pub struct PyByteArray<'p>(pyptr<'p>);
pub struct PyByteArray<'p>(Ptr<'p>);
pub struct PyByteArrayPtr(PyPtr);
pyobject_nativetype!(PyByteArray, PyByteArray_Check, PyByteArray_Type, PyByteArrayPtr);
@ -28,17 +27,15 @@ impl<'p> PyByteArray<'p> {
let ptr = src.as_ptr() as *const c_char;
let len = src.len() as ffi::Py_ssize_t;
let ptr = unsafe {ffi::PyByteArray_FromStringAndSize(ptr, len)};
unsafe { PyByteArray(pyptr::cast_from_owned_ptr_or_panic::<PyByteArray>(py, ptr)) }
PyByteArray(Ptr::from_owned_ptr_or_panic(py, ptr))
}
/// Creates a new Python bytearray object
/// from other PyObject, that implements the buffer protocol.
pub fn from(src: &'p PyObject<'p>) -> PyResult<PyByteArray<'p>> {
println!("FROM: {:?} {}", src.as_ptr(), src.get_refcnt());
let res = unsafe {ffi::PyByteArray_FromObject(src.as_ptr())};
if res != ptr::null_mut() {
Ok(unsafe{ PyByteArray(
pyptr::cast_from_owned_ptr_or_panic::<PyByteArray>(src.gil(), res))})
Ok(PyByteArray(Ptr::from_owned_ptr_or_panic(src.gil(), res)))
} else {
Err(PyErr::fetch(src.gil()))
}

View File

@ -5,8 +5,7 @@
use std::{mem, collections, hash, cmp};
use ffi;
use pyptr;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{Python, ToPythonPointer, PyDowncastInto};
use conversion::{ToPyObject};
use objects::{PyObject, PyList};
@ -15,7 +14,7 @@ use err::{self, PyResult, PyErr};
use native::PyNativeObject;
/// Represents a Python `dict`.
pub struct PyDict<'p>(pyptr<'p>);
pub struct PyDict<'p>(Ptr<'p>);
pub struct PyDictPtr(PyPtr);
pyobject_nativetype!(PyDict, PyDict_Check, PyDict_Type, PyDictPtr);
@ -26,13 +25,13 @@ impl<'p> PyDict<'p> {
///
/// May panic when running out of memory.
pub fn new(py: Python<'p>) -> PyDict<'p> {
unsafe { PyDict(pyptr::from_owned_ptr_or_panic(py, ffi::PyDict_New())) }
unsafe { PyDict(Ptr::from_owned_ptr_or_panic(py, ffi::PyDict_New())) }
}
/// Construct a new dict with the given raw pointer
/// Undefined behavior if the pointer is NULL or invalid.
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyDict<'p> {
PyDict(pyptr::from_borrowed_ptr(py, ptr))
PyDict(Ptr::from_borrowed_ptr(py, ptr))
}
/// Return a new dictionary that contains the same key-value pairs as self.
@ -40,7 +39,7 @@ impl<'p> PyDict<'p> {
pub fn copy(&'p self) -> PyResult<PyDict<'p>> {
unsafe {
Ok(PyDict(
pyptr::from_owned_ptr_or_err(self.gil(), ffi::PyDict_Copy(self.0.as_ptr()))?
Ptr::from_owned_ptr_or_err(self.gil(), ffi::PyDict_Copy(self.0.as_ptr()))?
))
}
}

View File

@ -3,7 +3,7 @@
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ffi;
use ppptr::pyptr;
use pointers::Ptr;
use python::{Python, ToPythonPointer, IntoPythonPointer};
use objects::PyObject;
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
/// so that PyIterator can implement the rust `Iterator` trait.
pub struct PyIterator<'p>(pyptr<'p>);
pub struct PyIterator<'p>(Ptr<'p>);
impl <'p> PyIterator<'p> {
@ -24,7 +24,7 @@ impl <'p> PyIterator<'p> {
unsafe {
let ptr = obj.into_ptr();
if ffi::PyIter_Check(ptr) != 0 {
Ok(PyIterator(pyptr::from_borrowed_ptr(py, ptr)))
Ok(PyIterator(Ptr::from_borrowed_ptr(py, ptr)))
} else {
ffi::Py_DECREF(ptr);
Err(PyDowncastError(py, None))

View File

@ -2,17 +2,16 @@
//
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use ::pyptr;
use err::{self, PyResult};
use ffi::{self, Py_ssize_t};
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
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 PyList<'p>(Ptr<'p>);
pub struct PyListPtr(PyPtr);
pyobject_nativetype!(PyList, PyList_Check, PyList_Type, PyListPtr);
@ -25,7 +24,7 @@ impl<'p> PyList<'p> {
for (i, e) in elements.iter().enumerate() {
ffi::PyList_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr());
}
PyList(pyptr::from_owned_ptr_or_panic(py, ptr))
PyList(Ptr::from_owned_ptr_or_panic(py, ptr))
}
}

View File

@ -179,7 +179,7 @@ macro_rules! pyobject_nativetype(
fn clone_object(&self) -> $name<'p> {
use $crate::{ToPythonPointer, PythonObjectWithGilToken};
unsafe {
$name(pyptr::from_borrowed_ptr(self.gil(), self.as_ptr()))
$name(Ptr::from_borrowed_ptr(self.gil(), self.as_ptr()))
}
}
}
@ -223,7 +223,7 @@ macro_rules! pyobject_nativetype(
unsafe{
let ptr = ob.into_ptr();
if ffi::$checkfunction(ptr) != 0 {
Ok($name(pyptr::from_owned_ptr(py, ptr)))
Ok($name(Ptr::from_owned_ptr(py, ptr)))
} else {
$crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None))
@ -236,7 +236,7 @@ macro_rules! pyobject_nativetype(
{
unsafe{
if ffi::$checkfunction(ptr) != 0 {
Ok($name(pyptr::from_owned_ptr(py, ptr)))
Ok($name(Ptr::from_owned_ptr(py, ptr)))
} else {
$crate::ffi::Py_DECREF(ptr);
Err($crate::PyDowncastError(py, None))
@ -272,7 +272,7 @@ macro_rules! pyobject_nativetype(
unsafe {
if ffi::$checkfunction(py.as_ptr()) != 0 {
Ok( $name($crate::pyptr::from_borrowed_ptr(py.gil(), py.as_ptr())) )
Ok( $name($crate::pointers::Ptr::from_borrowed_ptr(py.gil(), py.as_ptr())) )
} else {
Err(::PyDowncastError(py.gil(), None).into())
}

View File

@ -7,9 +7,8 @@ use ffi;
use std::os::raw::c_char;
use std::ffi::{CStr, CString};
use ::pyptr;
use conversion::{ToPyObject, ToPyTuple};
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{ToPythonPointer, Python};
use token::PythonObjectWithGilToken;
use objects::{PyObject, PyDict, PyType, exc};
@ -18,7 +17,7 @@ use err::{PyResult, PyErr};
/// Represents a Python module object.
pub struct PyModule<'p>(pyptr<'p>);
pub struct PyModule<'p>(Ptr<'p>);
pub struct PyModulePtr(PyPtr);
pyobject_nativetype!(PyModule, PyModule_Check, PyModule_Type, PyModulePtr);
@ -28,21 +27,15 @@ impl<'p> PyModule<'p> {
/// Create a new module object with the `__name__` attribute set to name.
pub fn new(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> {
let name = CString::new(name).unwrap();
unsafe {
let ptr = pyptr::cast_from_owned_ptr_or_err::<PyModule>(
py, ffi::PyModule_New(name.as_ptr()))?;
Ok(PyModule(ptr))
}
Ok(PyModule(Ptr::from_owned_ptr_or_err(
py, unsafe{ffi::PyModule_New(name.as_ptr())} )?))
}
/// Import the Python module with the specified name.
pub fn import(py: Python<'p>, name: &str) -> PyResult<PyModule<'p>> {
let name = CString::new(name).unwrap();
unsafe {
let ptr = pyptr::cast_from_owned_ptr_or_err::<PyModule>(
py, ffi::PyImport_ImportModule(name.as_ptr()))?;
Ok(PyModule(ptr))
}
Ok(PyModule(Ptr::from_owned_ptr_or_err(
py, unsafe{ffi::PyImport_ImportModule(name.as_ptr())} )?))
}
/// Return the dictionary object that implements module's namespace;

View File

@ -8,11 +8,10 @@ use self::num_traits::cast::cast;
use std::os::raw::{c_long, c_double};
use ffi;
use pyptr;
use objects::exc;
use objects::PyObject;
use token::PythonObjectWithGilToken;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{ToPythonPointer, Python};
use err::{PyResult, PyErr};
use native::PyNativeObject;
@ -24,7 +23,7 @@ use conversion::{ToPyObject, FromPyObject};
/// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with the primitive Rust integer types.
pub struct PyLong<'p>(pyptr<'p>);
pub struct PyLong<'p>(Ptr<'p>);
pub struct PyLongPtr(PyPtr);
pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type, PyLongPtr);
@ -34,7 +33,7 @@ pyobject_nativetype!(PyLong, PyLong_Check, PyLong_Type, PyLongPtr);
/// by using [ToPyObject](trait.ToPyObject.html)
/// and [extract](struct.PyObject.html#method.extract)
/// with `f32`/`f64`.
pub struct PyFloat<'p>(pyptr<'p>);
pub struct PyFloat<'p>(Ptr<'p>);
pub struct PyFloatPtr(PyPtr);
pyobject_nativetype!(PyFloat, PyFloat_Check, PyFloat_Type, PyFloatPtr);
@ -43,7 +42,7 @@ impl<'p> PyFloat<'p> {
/// Creates a new Python `float` object.
pub fn new(py: Python<'p>, val: c_double) -> PyFloat<'p> {
unsafe {
PyFloat(pyptr::from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val)))
PyFloat(Ptr::from_owned_ptr_or_panic(py, ffi::PyFloat_FromDouble(val)))
}
}

View File

@ -2,14 +2,13 @@
use std;
use ::pyptr;
use ffi;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use err::{PyErr, PyResult, PyDowncastError};
use python::{Python, ToPythonPointer};
pub struct PyObject<'p>(pyptr<'p>);
pub struct PyObject<'p>(Ptr<'p>);
pub struct PyObjectPtr(PyPtr);
@ -20,47 +19,43 @@ impl<'p> PyObject<'p> {
#[inline]
pub fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> {
unsafe { PyObject(pyptr::from_owned_ptr(py, ptr)) }
unsafe { PyObject(Ptr::from_owned_ptr(py, ptr)) }
}
#[inline]
pub fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<PyObject<'p>> {
unsafe { Ok(PyObject(pyptr::from_owned_ptr_or_err(py, ptr)?)) }
Ok(PyObject(Ptr::from_owned_ptr_or_err(py, ptr)?))
}
#[inline]
pub fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyObject<'p> {
unsafe { PyObject(pyptr::from_owned_ptr_or_panic(py, ptr)) }
PyObject(Ptr::from_owned_ptr_or_panic(py, ptr))
}
#[inline]
pub fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<PyObject<'p>> {
unsafe {
if let Some(ptr) = pyptr::from_owned_ptr_or_opt(py, ptr) {
Some(PyObject(ptr))
} else {
None
}
if let Some(ptr) = Ptr::from_owned_ptr_or_opt(py, ptr) {
Some(PyObject(ptr))
} else {
None
}
}
#[inline]
pub fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyObject<'p> {
unsafe { PyObject(pyptr::from_borrowed_ptr(py, ptr)) }
unsafe { PyObject(Ptr::from_borrowed_ptr(py, ptr)) }
}
#[inline]
pub fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<PyObject<'p>> {
unsafe {
if let Some(ptr) = pyptr::from_borrowed_ptr_or_opt(py, ptr) {
Some(PyObject(ptr))
} else {
None
}
if let Some(ptr) = Ptr::from_borrowed_ptr_or_opt(py, ptr) {
Some(PyObject(ptr))
} else {
None
}
}

View File

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

View File

@ -3,9 +3,8 @@
use std::{hash, collections};
use ffi;
use pyptr;
use python::{Python, ToPythonPointer};
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use conversion::ToPyObject;
use objects::PyObject;
use err::{self, PyResult, PyErr};
@ -14,11 +13,11 @@ use token::{PythonObjectWithGilToken};
/// Represents a Python `set`
pub struct PySet<'p>(pyptr<'p>);
pub struct PySet<'p>(Ptr<'p>);
pub struct PySetPtr(PyPtr);
/// Represents a Python `frozenset`
pub struct PyFrozenSet<'p>(pyptr<'p>);
pub struct PyFrozenSet<'p>(Ptr<'p>);
pub struct PyFrozenSetPtr(PyPtr);
pyobject_nativetype!(PySet, PySet_Check, PySet_Type, PySetPtr);
@ -32,7 +31,7 @@ impl<'p> PySet<'p> {
let list = elements.to_object(py);
unsafe {
let ptr = ffi::PySet_New(list.as_ptr());
PySet(pyptr::from_owned_ptr_or_panic(py, ptr))
PySet(Ptr::from_owned_ptr_or_panic(py, ptr))
}
}
@ -117,7 +116,7 @@ impl<'p> PyFrozenSet<'p> {
let list = elements.to_object(py);
unsafe {
let ptr = ffi::PyFrozenSet_New(list.as_ptr());
PyFrozenSet(pyptr::from_owned_ptr_or_panic(py, ptr))
PyFrozenSet(Ptr::from_owned_ptr_or_panic(py, ptr))
}
}

View File

@ -2,8 +2,7 @@
use std::os::raw::c_long;
use ::pyptr;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{ToPythonPointer, Python};
use err::{PyErr, PyResult};
use ffi::{self, Py_ssize_t};
@ -14,7 +13,7 @@ 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 PySlice<'p>(Ptr<'p>);
pub struct PySlicePtr(PyPtr);
pyobject_nativetype!(PySlice, PySlice_Check, PySlice_Type, PySlicePtr);
@ -48,7 +47,7 @@ impl<'p> PySlice<'p> {
let ptr = ffi::PySlice_New(ffi::PyLong_FromLong(start as i64),
ffi::PyLong_FromLong(stop as i64),
ffi::PyLong_FromLong(step as i64));
PySlice(pyptr::from_owned_ptr_or_panic(py, ptr))
PySlice(Ptr::from_owned_ptr_or_panic(py, ptr))
}
}

View File

@ -9,8 +9,7 @@ use std::borrow::Cow;
use std::os::raw::c_char;
use ffi;
use pyptr;
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{ToPythonPointer, Python};
use super::{exc, PyObject};
use token::PythonObjectWithGilToken;
@ -19,12 +18,12 @@ use native::PyNativeObject;
use conversion::{ToPyObject, RefFromPyObject};
/// Represents a Python string.
pub struct PyString<'p>(pyptr<'p>);
pub struct PyString<'p>(Ptr<'p>);
pub struct PyStringPtr(PyPtr);
pyobject_nativetype!(PyString, PyUnicode_Check, PyUnicode_Type, PyStringPtr);
/// Represents a Python byte string.
pub struct PyBytes<'p>(pyptr<'p>);
pub struct PyBytes<'p>(Ptr<'p>);
pub struct PyBytesPtr(PyPtr);
pyobject_nativetype!(PyBytes, PyBytes_Check, PyBytes_Type, PyBytesPtr);
@ -145,7 +144,7 @@ impl<'p> PyString<'p> {
let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t;
unsafe {
PyString(pyptr::from_owned_ptr_or_panic(
PyString(Ptr::from_owned_ptr_or_panic(
py, ffi::PyUnicode_FromStringAndSize(ptr, len)))
}
}
@ -154,7 +153,7 @@ impl<'p> PyString<'p> {
-> PyResult<PyString<'p>> {
unsafe {
Ok(PyString(
pyptr::from_owned_ptr_or_err(
Ptr::from_owned_ptr_or_err(
src.gil(), ffi::PyUnicode_FromEncodedObject(
src.as_ptr(),
encoding.as_ptr() as *const i8,
@ -203,7 +202,7 @@ impl<'p> PyBytes<'p> {
let ptr = s.as_ptr() as *const c_char;
let len = s.len() as ffi::Py_ssize_t;
unsafe {
PyBytes(pyptr::from_owned_ptr_or_panic(
PyBytes(Ptr::from_owned_ptr_or_panic(
py, ffi::PyBytes_FromStringAndSize(ptr, len)))
}
}

View File

@ -4,10 +4,9 @@
use std::slice;
use pyptr;
use ffi::{self, Py_ssize_t};
use err::{PyErr, PyResult};
use pointers::PyPtr;
use pointers::{Ptr, PyPtr};
use python::{Python, ToPythonPointer, IntoPythonPointer};
use conversion::{FromPyObject, ToPyObject, ToPyTuple, IntoPyObject};
use objects::PyObject;
@ -16,7 +15,7 @@ use token::PythonObjectWithGilToken;
use super::exc;
/// Represents a Python tuple object.
pub struct PyTuple<'p>(pyptr<'p>);
pub struct PyTuple<'p>(Ptr<'p>);
pub struct PyTuplePtr(PyPtr);
pyobject_nativetype!(PyTuple, PyTuple_Check, PyTuple_Type, PyTuplePtr);
@ -31,19 +30,19 @@ impl<'p> PyTuple<'p> {
for (i, e) in elements.iter().enumerate() {
ffi::PyTuple_SetItem(ptr, i as Py_ssize_t, e.to_object(py).into_ptr());
}
PyTuple(pyptr::from_owned_ptr_or_panic(py, ptr))
PyTuple(Ptr::from_owned_ptr_or_panic(py, ptr))
}
}
/// Construct a new tuple with the given raw pointer
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyTuple<'p> {
PyTuple(pyptr::from_borrowed_ptr(py, ptr))
PyTuple(Ptr::from_borrowed_ptr(py, ptr))
}
/// Retrieves the empty tuple.
pub fn empty(py: Python<'p>) -> PyTuple<'p> {
unsafe {
PyTuple(pyptr::from_owned_ptr_or_panic(py, ffi::PyTuple_New(0)))
PyTuple(Ptr::from_owned_ptr_or_panic(py, ffi::PyTuple_New(0)))
}
}
@ -91,7 +90,7 @@ impl<'p> PyTuple<'p> {
impl<'a> ToPyTuple for PyTuple<'a> {
fn to_py_tuple<'p>(&self, py: Python<'p>) -> PyTuple<'p> {
unsafe { PyTuple(pyptr::from_borrowed_ptr(py, self.0.as_ptr())) }
unsafe { PyTuple(Ptr::from_borrowed_ptr(py, self.0.as_ptr())) }
}
}

View File

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

View File

@ -6,7 +6,7 @@ use std::ops::{Deref, DerefMut};
use std::convert::{AsRef, AsMut};
use ffi;
use err::{PyResult, PyDowncastError};
use err::{PyErr, PyResult, PyDowncastError};
use conversion::{ToPyObject, IntoPyObject};
use objects::{PyObject, PyObjectPtr};
use python::{Python, ToPythonPointer, IntoPythonPointer};
@ -124,6 +124,137 @@ impl Drop for PyPtr {
}
}
#[allow(non_camel_case_types)]
pub struct Ptr<'p>(*mut ffi::PyObject, Python<'p>);
impl<'p> Ptr<'p> {
/// Create new python object and move T instance under python management
pub fn new<T>(py: Python<'p>, value: T) -> PyResult<Ptr<'p>> where T: PyObjectAlloc<Type=T>
{
let ptr = unsafe {
try!(<T as PyObjectAlloc>::alloc(py, value))
};
Ok(Ptr(ptr, py))
}
/// Creates a `Ptr` instance for the given FFI pointer.
/// This moves ownership over the pointer into the `Ptr`.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_owned_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> Ptr<'p> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
Ptr(ptr, py)
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject) -> Ptr<'p>
{
if ptr.is_null() {
::err::panic_after_error();
} else {
unsafe{
Ptr::from_owned_ptr(py, ptr)
}
}
}
/// Construct `Ptr<'p>` from the result of a Python FFI call that
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject) -> PyResult<Ptr<'p>>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(unsafe{
Ptr::from_owned_ptr(py, ptr)
})
}
}
/// Creates a Ptr<'p> instance for the given FFI pointer.
/// This moves ownership over the pointer into the Ptr<'p>.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) -> Option<Ptr<'p>> {
if ptr.is_null() {
None
} else {
Some(unsafe{
Ptr::from_owned_ptr(py, ptr)
})
}
}
/// Creates a `Ptr<'p>` instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_borrowed_ptr(py: Python<'p>, ptr: *mut ffi::PyObject) -> Ptr<'p> {
debug_assert!(!ptr.is_null() && ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr);
Ptr(ptr, py)
}
/// Creates a `Ptr<'p>` instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
#[inline]
pub fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject) -> Option<Ptr<'p>> {
if ptr.is_null() {
None
} else {
Some(unsafe{ Ptr::from_borrowed_ptr(py, ptr) })
}
}
/// Gets the reference count of this Py object.
#[inline]
pub fn get_refcnt(&self) -> usize {
unsafe { ffi::Py_REFCNT(self.0) as usize }
}
pub fn token<'a>(&'a self) -> Python<'p> {
self.1
}
}
impl<'p> ToPythonPointer for Ptr<'p> {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.0
}
}
impl<'p> IntoPythonPointer for Ptr<'p> {
/// 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
}
}
/// Dropping a `Ptr` instance decrements the reference count on the object by 1.
impl<'p> Drop for Ptr<'p> {
fn drop(&mut self) {
unsafe {
println!("drop Ptr: {:?} {} {:?}",
self.0, ffi::Py_REFCNT(self.0), &self as *const _);
}
unsafe { ffi::Py_DECREF(self.0); }
}
}
pub struct Py<'p, T> {
pub inner: *mut ffi::PyObject,

View File

@ -1,209 +0,0 @@
// Copyright (c) 2017-present PyO3 Project and Contributors
use std;
use ffi;
use err::{PyErr, PyResult};
use python::{Python, PyDowncastInto, ToPythonPointer, IntoPythonPointer};
use typeob::{PyTypeInfo, PyObjectAlloc};
#[allow(non_camel_case_types)]
pub struct pyptr<'p>(Python<'p>, *mut ffi::PyObject);
impl<'p> pyptr<'p> {
/// Create new python object and move T instance under python management
pub fn new<T>(py: Python<'p>, value: T) -> PyResult<pyptr<'p>> where T: PyObjectAlloc<Type=T>
{
let ptr = unsafe {
try!(<T as PyObjectAlloc>::alloc(py, value))
};
Ok(pyptr(py, ptr))
}
/// Creates a Py instance for the given FFI pointer.
/// This moves ownership over the pointer into the Py.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
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);
pyptr(py, ptr)
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub unsafe fn from_owned_ptr_or_panic(py: Python<'p>, ptr: *mut ffi::PyObject) -> pyptr<'p>
{
if ptr.is_null() {
::err::panic_after_error();
} else {
pyptr::from_owned_ptr(py, ptr)
}
}
/// Construct pppt<'p> from the result of a Python FFI call that
/// returns a new reference (owned pointer).
/// Returns `Err(PyErr)` if the pointer is `null`.
/// Unsafe because the pointer might be invalid.
pub unsafe fn from_owned_ptr_or_err(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<pyptr<'p>>
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(pyptr::from_owned_ptr(py, ptr))
}
}
/// Creates a pyptr<'p> instance for the given FFI pointer.
/// This moves ownership over the pointer into the pyptr<'p>.
/// Returns None for null pointers; undefined behavior if the pointer is invalid.
#[inline]
pub unsafe fn from_owned_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<pyptr<'p>> {
if ptr.is_null() {
None
} else {
Some(pyptr::from_owned_ptr(py, ptr))
}
}
/// Creates a Py instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
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);
ffi::Py_INCREF(ptr);
pyptr(py, ptr)
}
/// Creates a Py instance for the given FFI pointer.
/// Calls Py_INCREF() on the ptr.
#[inline]
pub unsafe fn from_borrowed_ptr_or_opt(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Option<pyptr<'p>> {
if ptr.is_null() {
None
} else {
debug_assert!(ffi::Py_REFCNT(ptr) > 0);
ffi::Py_INCREF(ptr);
Some(pyptr(py, ptr))
}
}
/// Gets the reference count of this Py object.
#[inline]
pub fn get_refcnt(&self) -> usize {
unsafe { ffi::Py_REFCNT(self.1) as usize }
}
pub fn token<'a>(&'a self) -> Python<'p> {
self.0
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn cast_from_owned_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<pyptr<'p>, ::PyDowncastError<'p>>
where T: PyTypeInfo
{
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
if checked {
Ok( unsafe { pyptr::from_owned_ptr(py, ptr) })
} else {
Err(::PyDowncastError(py, None))
}
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub fn cast_from_borrowed_ptr<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> Result<pyptr<'p>, ::PyDowncastError<'p>>
where T: PyTypeInfo
{
let checked = unsafe { ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 };
if checked {
Ok( unsafe { pyptr::from_borrowed_ptr(py, ptr) })
} else {
Err(::PyDowncastError(py, None))
}
}
/// Cast from ffi::PyObject ptr to a concrete object.
#[inline]
pub unsafe fn cast_from_owned_ptr_or_panic<T>(py: Python<'p>,
ptr: *mut ffi::PyObject) -> pyptr<'p>
where T: PyTypeInfo
{
if ffi::PyObject_TypeCheck(ptr, T::type_object()) != 0 {
pyptr::from_owned_ptr(py, ptr)
} else {
::err::panic_after_error();
}
}
#[inline]
pub fn cast_from_owned_ptr_or_err<T>(py: Python<'p>, ptr: *mut ffi::PyObject)
-> PyResult<pyptr<'p>>
where T: PyTypeInfo
{
if ptr.is_null() {
Err(PyErr::fetch(py))
} else {
pyptr::cast_from_owned_ptr::<T>(py, ptr).map_err(|e| e.into())
}
}
}
impl<'p> ToPythonPointer for pyptr<'p> {
/// Gets the underlying FFI pointer, returns a borrowed pointer.
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.1
}
}
impl<'p> IntoPythonPointer for pyptr<'p> {
/// Gets the underlying FFI pointer, returns a owned pointer.
#[inline]
#[must_use]
fn into_ptr(self) -> *mut ffi::PyObject {
let ptr = self.1;
std::mem::forget(self);
ptr
}
}
/// Dropping a `pyptr` instance decrements the reference count on the object by 1.
impl<'p> Drop for pyptr<'p> {
fn drop(&mut self) {
unsafe {
println!("drop pyptr: {:?} {} {:?}",
self.1, ffi::Py_REFCNT(self.1), &self as *const _);
}
unsafe { ffi::Py_DECREF(self.1); }
}
}
impl<'p> std::fmt::Debug for pyptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let repr = unsafe { ::PyString::downcast_from_owned_ptr(
self.0, ffi::PyObject_Repr(self.1)) };
let repr = repr.map_err(|_| std::fmt::Error)?;
f.write_str(&repr.to_string_lossy())
}
}
impl<'p> std::fmt::Display for pyptr<'p> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let ob = unsafe { ::PyString::downcast_from_owned_ptr(
self.0, ffi::PyObject_Str(self.1)) };
let ob = ob.map_err(|_| std::fmt::Error)?;
f.write_str(&ob.to_string_lossy())
}
}