clippy warnings

This commit is contained in:
Nikolay Kim 2018-01-19 10:02:36 -08:00
parent 324a6b2697
commit b738c1a04b
31 changed files with 136 additions and 84 deletions

View File

@ -89,16 +89,13 @@ fn native_element_type_from_type_char(type_char: u8) -> ElementType {
fn standard_element_type_from_type_char(type_char: u8) -> ElementType {
use self::ElementType::*;
match type_char {
b'c' => UnsignedInteger { bytes: 1 },
b'c' | b'B' => UnsignedInteger { bytes: 1 },
b'b' => SignedInteger { bytes: 1 },
b'B' => UnsignedInteger { bytes: 1 },
b'?' => Bool,
b'h' => SignedInteger { bytes: 2 },
b'H' => UnsignedInteger { bytes: 2 },
b'i' => SignedInteger { bytes: 4 },
b'I' => UnsignedInteger { bytes: 4 },
b'l' => SignedInteger { bytes: 4 },
b'L' => UnsignedInteger { bytes: 4 },
b'i' | b'l' => SignedInteger { bytes: 4 },
b'I' | b'L' => UnsignedInteger { bytes: 4 },
b'q' => SignedInteger { bytes: 8 },
b'Q' => UnsignedInteger { bytes: 8 },
b'e' => Float { bytes: 2 },
@ -495,7 +492,7 @@ impl PyBuffer {
}
}
pub fn release<'p>(self, _py: Python<'p>) {
pub fn release(self, _py: Python) {
unsafe {
let ptr = &*self.0 as *const ffi::Py_buffer as *mut ffi::Py_buffer;
ffi::PyBuffer_Release(ptr)

View File

@ -139,6 +139,7 @@ impl <T> CallbackConverter<T> for HashConverter
}
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub unsafe fn cb_convert<C, T>(_c: C, py: Python, value: PyResult<T>) -> C::R
where C: CallbackConverter<T>
{

View File

@ -2,10 +2,10 @@
//! Python Async/Await Interface.
//!
//! Python c-api information is available:
//! https://docs.python.org/3/c-api/typeobj.html#async-object-structures
//! Check [python c-api information](
//! https://docs.python.org/3/c-api/typeobj.html#async-object-structures)
//!
//! Python documentation is available: https://www.python.org/dev/peps/pep-0492/
//! [PEP-0492](https://www.python.org/dev/peps/pep-0492/)
//!
use ffi;

View File

@ -2,9 +2,8 @@
//! Basic Python Object customization
//!
//! Python c-api information is available:
//! https://docs.python.org/3/reference/datamodel.html#basic-customization
//!
//! Check [python c-api information](https://docs.python.org/3/reference/datamodel.html#basic-customization)
//! for more information.
use std;
use std::os::raw::c_int;
@ -369,7 +368,7 @@ impl<T> PyObjectRichcmpProtocolImpl for T
Ok(op) => match arg.extract() {
Ok(arg) =>
slf.__richcmp__(arg, op).into(),
Err(e) => Err(e.into()),
Err(e) => Err(e),
},
Err(e) => Err(e)
};

View File

@ -2,9 +2,8 @@
//! Represent Python Buffer protocol implementation
//!
//! more information on buffer protocol can be found
//! https://docs.python.org/3/c-api/buffer.html
//! For more information check [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
//! c-api
use std::os::raw::c_int;
use ffi;
@ -15,8 +14,8 @@ use callback::UnitCallbackConverter;
/// Buffer protocol interface
///
/// more information on buffer protocol can be found
/// https://docs.python.org/3/c-api/buffer.html
/// For more information check [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
/// c-api
#[allow(unused_variables)]
pub trait PyBufferProtocol<'p> : PyTypeInfo
{
@ -53,7 +52,6 @@ impl<'p, T> PyBufferProtocolImpl for T where T: PyBufferProtocol<'p>
Some(ffi::PyBufferProcs{
bf_getbuffer: Self::cb_bf_getbuffer(),
bf_releasebuffer: None,
.. ffi::PyBufferProcs_INIT
})
}
}

View File

@ -2,8 +2,8 @@
//! Python Description Interface
//!
//! more information
//! https://docs.python.org/3/reference/datamodel.html#implementing-descriptors
//! [Python information](
//! https://docs.python.org/3/reference/datamodel.html#implementing-descriptors)
use std::os::raw::c_int;

View File

@ -231,7 +231,7 @@ impl<T> PySequenceSetItemProtocolImpl for T
Ok(value) => {
slf.__setitem__(key as isize, value).into()
},
Err(e) => Err(e.into()),
Err(e) => Err(e),
};
match result {
Ok(_) => 0,
@ -321,7 +321,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
Ok(value) => {
slf.__setitem__(key as isize, value).into()
},
Err(e) => Err(e.into()),
Err(e) => Err(e),
};
match result {
Ok(_) => 0,

View File

@ -133,14 +133,14 @@ impl IntoPyObject for () {
impl<'a, T> IntoPyObject for &'a T where T: ToPyPointer
{
#[inline]
fn into_object<'p>(self, py: Python) -> PyObject {
fn into_object(self, py: Python) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(py, self.as_ptr()) }
}
}
impl<'a, T> IntoPyObject for &'a mut T where T: ToPyPointer {
#[inline]
fn into_object<'p>(self, py: Python) -> PyObject {
fn into_object(self, py: Python) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(py, self.as_ptr()) }
}
}

View File

@ -365,7 +365,7 @@ impl PyErr {
/// This method takes `mut self` because the error might need
/// to be normalized in order to create the exception instance.
fn instance(mut self, py: Python) -> PyObject {
&self.normalize(py);
self.normalize(py);
match self.pvalue {
PyErrValue::Value(ref instance) => instance.clone_ref(py),
_ => py.None(),

View File

@ -13,23 +13,23 @@ pub struct PyFutureFeatures {
}
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_NESTED_SCOPES : &'static str = "nested_scopes";
pub const FUTURE_NESTED_SCOPES : &str = "nested_scopes";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_GENERATORS : &'static str = "generators";
pub const FUTURE_GENERATORS : &str = "generators";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_DIVISION : &'static str = "division";
pub const FUTURE_DIVISION : &str = "division";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_ABSOLUTE_IMPORT : &'static str = "absolute_import";
pub const FUTURE_ABSOLUTE_IMPORT : &str = "absolute_import";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_WITH_STATEMENT : &'static str = "with_statement";
pub const FUTURE_WITH_STATEMENT : &str = "with_statement";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_PRINT_FUNCTION : &'static str = "print_function";
pub const FUTURE_PRINT_FUNCTION : &str = "print_function";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_UNICODE_LITERALS : &'static str = "unicode_literals";
pub const FUTURE_UNICODE_LITERALS : &str = "unicode_literals";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_BARRY_AS_BDFL : &'static str = "barry_as_FLUFL";
pub const FUTURE_BARRY_AS_BDFL : &str = "barry_as_FLUFL";
#[cfg(not(Py_LIMITED_API))]
pub const FUTURE_GENERATOR_STOP : &'static str = "generator_stop";
pub const FUTURE_GENERATOR_STOP : &str = "generator_stop";
#[cfg(not(Py_LIMITED_API))]
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {

View File

@ -1,7 +1,7 @@
use std::os::raw::{c_char, c_int};
use ffi3::object::PyObject;
pub const PY_STDIOTEXTMODE : &'static str = "b";
pub const PY_STDIOTEXTMODE : &str = "b";
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFile_FromFd(arg1: c_int, arg2: *const c_char,

View File

@ -24,6 +24,7 @@ impl PyToken {
}
#[inline(always)]
#[cfg_attr(feature = "cargo-clippy", allow(inline_always))]
pub fn py(&self) -> Python {
unsafe { Python::assume_gil_acquired() }
}
@ -45,6 +46,7 @@ pub trait AsPyRef<T>: Sized {
fn as_ref(&self, py: Python) -> &T;
/// Return mutable reference to object.
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))]
fn as_mut(&self, py: Python) -> &mut T;
/// Acquire python gil and call closure with object reference.

View File

@ -123,7 +123,8 @@
//! ```
//!
//! (Note: on macOS you will have to rename `libhello.dynlib` to `libhello.so`.
//! To build on macOS, use "-C link-arg=-undefined -C link-arg=dynamic_lookup" is required to build the library.
//! To build on macOS, use `-C link-arg=-undefined -C link-arg=dynamic_lookup`
//! is required to build the library.
//! `setuptools-rust` includes this by default.
//! See [examples/word-count](https://github.com/PyO3/pyo3/tree/master/examples/word-count).)
//!

View File

@ -16,6 +16,7 @@ use typeob::PyTypeInfo;
/// Python object model helper methods
#[cfg_attr(feature = "cargo-clippy", allow(len_without_is_empty))]
pub trait ObjectProtocol {
/// Determines whether this object has the given attribute.
@ -151,6 +152,7 @@ pub trait ObjectProtocol {
fn get_base(&self) -> &<Self as PyTypeInfo>::BaseType where Self: PyTypeInfo;
/// Gets the Python base object for this object.
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))]
fn get_mut_base(&self) -> &mut <Self as PyTypeInfo>::BaseType where Self: PyTypeInfo;
/// Casts the PyObject to a concrete Python object type.
@ -406,7 +408,7 @@ impl<T> ObjectProtocol for T where T: PyObjectWithToken + ToPyPointer {
})
}
fn iter<'p>(&'p self) -> PyResult<PyIterator<'p>> {
fn iter(&self) -> PyResult<PyIterator> {
Ok(PyIterator::from_object(self.py(), self)?)
}

View File

@ -30,7 +30,7 @@ impl PyByteArray {
/// Creates a new Python bytearray object
/// from other PyObject, that implements the buffer protocol.
pub fn from<I>(py: Python, src: I) -> PyResult<&PyByteArray>
pub fn from<'p, I>(py: Python<'p>, src: &'p I) -> PyResult<&'p PyByteArray>
where I: ToPyPointer
{
unsafe {
@ -48,7 +48,13 @@ impl PyByteArray {
}
}
/// Check if bytearray is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Gets the Python bytearray data as byte slice.
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))]
pub fn data(&self) -> &mut [u8] {
unsafe {
let buffer = ffi::PyByteArray_AsString(self.0.as_ptr()) as *mut u8;
@ -89,7 +95,7 @@ mod test {
assert_eq!(src, bytearray.data());
let ba: PyObject = bytearray.into();
let bytearray = PyByteArray::from(py, ba).unwrap();
let bytearray = PyByteArray::from(py, &ba).unwrap();
assert_eq!(src.len(), bytearray.len());
assert_eq!(src, bytearray.data());

View File

@ -47,6 +47,11 @@ impl PyDict {
unsafe { ffi::PyDict_Size(self.as_ptr()) as usize }
}
/// Check if dict is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Determine if the dictionary contains the specified key.
/// This is equivalent to the Python expression `key in self`.
pub fn contains<K>(&self, key: K) -> PyResult<bool> where K: ToBorrowedObject {

View File

@ -29,6 +29,7 @@ macro_rules! exc_type(
}
}
impl $name {
#[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))]
pub fn new<V: ToPyObject + 'static>(args: V) -> PyErr {
PyErr::new::<$name, V>(args)
}
@ -132,6 +133,7 @@ exc_type!(WindowsError, PyExc_WindowsError);
impl UnicodeDecodeError {
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn new_err<'p>(py: Python<'p>, encoding: &CStr, input: &[u8],
range: ops::Range<usize>, reason: &CStr) -> PyResult<&'p PyObjectRef> {
unsafe {

View File

@ -46,6 +46,7 @@ macro_rules! import_exception {
}
impl $name {
#[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))]
pub fn new<T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyErr
where Self: $crate::typeob::PyTypeObject + Sized
{

View File

@ -50,19 +50,24 @@ impl IntoPyObject for f64 {
pyobject_extract!(obj to f64 => {
let v = unsafe { ffi::PyFloat_AsDouble(obj.as_ptr()) };
if v == -1.0 && PyErr::occurred(obj.py()) {
Err(PyErr::fetch(obj.py()))
} else {
Ok(v)
#[cfg_attr(feature = "cargo-clippy", allow(float_cmp))]
{
if v == -1.0 && PyErr::occurred(obj.py()) {
Err(PyErr::fetch(obj.py()))
} else {
Ok(v)
}
}
});
impl ToPyObject for f32 {
#[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
fn to_object(&self, py: Python) -> PyObject {
PyFloat::new(py, *self as f64).into()
}
}
impl IntoPyObject for f32 {
#[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
fn into_object(self, py: Python) -> PyObject {
PyFloat::new(py, self as f64).into()
}

View File

@ -46,6 +46,11 @@ impl PyList {
}
}
/// Check if list is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Gets the item at the specified index.
///
/// Panics if the index is out of range.

View File

@ -36,6 +36,7 @@ macro_rules! pyobject_downcast(
impl<'a> $crate::FromPyObject<'a> for &'a $name
{
/// Extracts `Self` from the source `PyObject`.
#[cfg_attr(feature = "cargo-clippy", allow(useless_transmute))]
fn extract(ob: &'a $crate::PyObjectRef) -> $crate::PyResult<Self>
{
unsafe {
@ -65,6 +66,7 @@ macro_rules! pyobject_nativetype(
impl $crate::PyNativeType for $name {}
impl $crate::std::convert::AsRef<$crate::PyObjectRef> for $name {
#[cfg_attr(feature = "cargo-clippy", allow(useless_transmute))]
fn as_ref(&self) -> &$crate::PyObjectRef {
unsafe{$crate::std::mem::transmute(self)}
}
@ -106,6 +108,7 @@ macro_rules! pyobject_nativetype(
&mut $crate::ffi::$typeobject
}
#[cfg_attr(feature = "cargo-clippy", allow(not_unsafe_ptr_arg_deref))]
fn is_instance(ptr: *mut $crate::ffi::PyObject) -> bool {
#[allow(unused_unsafe)]
unsafe { $crate::ffi::$checkfunction(ptr) > 0 }

View File

@ -30,6 +30,7 @@ pyobject_nativetype!(PyLong, PyLong_Type, PyLong_Check);
macro_rules! int_fits_c_long(
($rust_type:ty) => (
impl ToPyObject for $rust_type {
#[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObject::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(*self as c_long))
@ -37,6 +38,7 @@ macro_rules! int_fits_c_long(
}
}
impl IntoPyObject for $rust_type {
#[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
fn into_object(self, py: Python) -> PyObject {
unsafe {
PyObject::from_owned_ptr_or_panic(py, ffi::PyLong_FromLong(self as c_long))
@ -81,6 +83,8 @@ macro_rules! int_fits_larger_int(
);
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn err_if_invalid_value<T: PartialEq>
(py: Python, invalid_value: T, actual_value: T) -> PyResult<T>
{

View File

@ -20,6 +20,7 @@ pyobject_nativetype!(PySequence);
pyobject_downcast!(PySequence, PySequence_Check);
#[cfg_attr(feature = "cargo-clippy", allow(len_without_is_empty))]
impl PySequence {
/// Returns the number of objects in sequence. This is equivalent to Python `len()`.
#[inline]

View File

@ -45,6 +45,11 @@ impl PySet {
unsafe { ffi::PySet_Size(self.as_ptr()) as usize }
}
/// Check if set is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Determine if the set contains the specified key.
/// This is equivalent to the Python expression `key in self`.
pub fn contains<K>(&self, key: K) -> PyResult<bool> where K: ToPyObject {
@ -127,6 +132,11 @@ impl PyFrozenSet {
unsafe { ffi::PySet_Size(self.as_ptr()) as usize }
}
/// Check if set is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Determine if the set contains the specified key.
/// This is equivalent to the Python expression `key in self`.
pub fn contains<K>(&self, key: K) -> PyResult<bool> where K: ToBorrowedObject {

View File

@ -124,7 +124,7 @@ impl PyBytes {
mod test {
use python::Python;
use instance::AsPyRef;
use conversion::{ToPyObject, RefFromPyObject};
use conversion::{FromPyObject, ToPyObject};
#[test]
fn test_non_bmp() {
@ -141,12 +141,8 @@ mod test {
let py = gil.python();
let s = "Hello Python";
let py_string = s.to_object(py);
let mut called = false;
RefFromPyObject::with_extracted(py_string.as_ref(py),
|s2: &str| {
assert_eq!(s, s2);
called = true;
}).unwrap();
assert!(called);
let s2: &str = FromPyObject::extract(py_string.as_ref(py)).unwrap();
assert_eq!(s, s2);
}
}

View File

@ -193,7 +193,7 @@ impl std::convert::From<Py<PyUnicode>> for Py<PyString> {
mod test {
use python::Python;
use instance::AsPyRef;
use conversion::{ToPyObject, RefFromPyObject};
use conversion::{ToPyObject, FromPyObject};
#[test]
fn test_non_bmp() {
@ -210,13 +210,8 @@ mod test {
let py = gil.python();
let s = "Hello Python";
let py_string = s.to_object(py);
let mut called = false;
RefFromPyObject::with_extracted(py_string.as_ref(py),
|s2: &str| {
assert_eq!(s, s2);
called = true;
}).unwrap();
assert!(called);
let s2: &str = FromPyObject::extract(py_string.as_ref(py)).unwrap();
assert_eq!(s, s2);
}
}

View File

@ -48,6 +48,11 @@ impl PyTuple {
}
}
/// Check if tuple is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Take a slice of the tuple pointed to by p from low to high and return it as a new tuple.
pub fn slice(&self, low: isize, high: isize) -> Py<PyTuple> {
unsafe {

View File

@ -276,6 +276,7 @@ impl<'p> Python<'p> {
}
/// Register `ffi::PyObject` pointer in release pool
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_borrowed_ptr_to_obj(self, ptr: *mut ffi::PyObject) -> &'p PyObjectRef
{
if ptr.is_null() {
@ -287,6 +288,7 @@ impl<'p> Python<'p> {
/// Register `ffi::PyObject` pointer in release pool,
/// and do unchecked downcast to specific type.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_owned_ptr<T>(self, ptr: *mut ffi::PyObject) -> &'p T
where T: PyTypeInfo
{
@ -314,6 +316,7 @@ impl<'p> Python<'p> {
/// Register owned `ffi::PyObject` pointer in release pool.
/// Returns `Err(PyErr)` if the pointer is `null`.
/// do unchecked downcast to specific type.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_owned_ptr_or_err<T>(self, ptr: *mut ffi::PyObject) -> PyResult<&'p T>
where T: PyTypeInfo
{
@ -328,6 +331,7 @@ impl<'p> Python<'p> {
/// Register owned `ffi::PyObject` pointer in release pool.
/// Returns `None` if the pointer is `null`.
/// do unchecked downcast to specific type.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_owned_ptr_or_opt<T>(self, ptr: *mut ffi::PyObject) -> Option<&'p T>
where T: PyTypeInfo
{
@ -342,6 +346,7 @@ impl<'p> Python<'p> {
/// Register borrowed `ffi::PyObject` pointer in release pool.
/// Panics if the pointer is `null`.
/// do unchecked downcast to specific type.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_borrowed_ptr<T>(self, ptr: *mut ffi::PyObject) -> &'p T
where T: PyTypeInfo
{
@ -366,6 +371,7 @@ impl<'p> Python<'p> {
/// Register borrowed `ffi::PyObject` pointer in release pool.
/// Returns `Err(PyErr)` if the pointer is `null`.
/// do unchecked downcast to specific type.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_borrowed_ptr_or_err<T>(self, ptr: *mut ffi::PyObject) -> PyResult<&'p T>
where T: PyTypeInfo
{
@ -380,6 +386,7 @@ impl<'p> Python<'p> {
/// Register borrowed `ffi::PyObject` pointer in release pool.
/// Returns `None` if the pointer is `null`.
/// do unchecked downcast to specific `T`.
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub unsafe fn from_borrowed_ptr_or_opt<T>(self, ptr: *mut ffi::PyObject) -> Option<&'p T>
where T: PyTypeInfo
{
@ -412,6 +419,7 @@ impl<'p> Python<'p> {
/// Release `ffi::PyObject` pointer.
/// Undefined behavior if the pointer is invalid.
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(not_unsafe_ptr_arg_deref))]
pub fn xdecref(self, ptr: *mut ffi::PyObject) {
if !ptr.is_null() {
unsafe {ffi::Py_DECREF(ptr)};

View File

@ -179,15 +179,22 @@ pub struct GILPool {
no_send: marker::PhantomData<rc::Rc<()>>,
}
impl GILPool {
impl Default for GILPool {
#[inline]
pub fn new() -> GILPool {
fn default() -> GILPool {
let p: &'static mut ReleasePool = unsafe { &mut *POOL };
GILPool {owned: p.owned.len(),
borrowed: p.borrowed.len(),
pointers: true,
no_send: marker::PhantomData}
}
}
impl GILPool {
#[inline]
pub fn new() -> GILPool {
GILPool::default()
}
#[inline]
pub fn new_no_pointers() -> GILPool {
let p: &'static mut ReleasePool = unsafe { &mut *POOL };

View File

@ -42,11 +42,13 @@ pub trait PyTypeInfo {
unsafe fn type_object() -> &'static mut ffi::PyTypeObject;
/// Check if `*mut ffi::PyObject` is instance of this type
#[cfg_attr(feature = "cargo-clippy", allow(not_unsafe_ptr_arg_deref))]
fn is_instance(ptr: *mut ffi::PyObject) -> bool {
unsafe {ffi::PyObject_TypeCheck(ptr, Self::type_object()) != 0}
}
/// Check if `*mut ffi::PyObject` is exact instance of this type
#[cfg_attr(feature = "cargo-clippy", allow(not_unsafe_ptr_arg_deref))]
fn is_exact_instance(ptr: *mut ffi::PyObject) -> bool {
unsafe {
(*ptr).ob_type == Self::type_object()
@ -56,7 +58,7 @@ pub trait PyTypeInfo {
/// type object supports python GC
pub const PY_TYPE_FLAG_GC: usize = 1<<0;
pub const PY_TYPE_FLAG_GC: usize = 1;
/// Type object supports python weak references
pub const PY_TYPE_FLAG_WEAKREF: usize = 1<<1;
@ -182,6 +184,7 @@ impl PyRawObject {
}
/// Return reference to object.
#[cfg_attr(feature = "cargo-clippy", allow(should_implement_trait))]
pub fn as_ref<T: PyTypeInfo>(&self) -> &T {
// TODO: check is object initialized
unsafe {
@ -199,6 +202,7 @@ impl IntoPyPointer for PyRawObject {
}
impl PyObjectWithToken for PyRawObject {
#[cfg_attr(feature = "cargo-clippy", allow(inline_always))]
#[inline(always)]
fn py(&self) -> Python {
unsafe { Python::assume_gil_acquired() }
@ -435,11 +439,8 @@ pub fn initialize_type<'p, T>(py: Python<'p>, module_name: Option<&str>) -> PyRe
mem::forget(methods);
}
match (new, init) {
(None, Some(_)) => {
panic!("{}.__new__ method is required if __init__ method defined", T::NAME);
}
_ => ()
if let (None, Some(_)) = (new, init) {
panic!("{}.__new__ method is required if __init__ method defined", T::NAME);
}
// __new__ method
@ -459,8 +460,9 @@ pub fn initialize_type<'p, T>(py: Python<'p>, module_name: Option<&str>) -> PyRe
// set type flags
py_class_flags::<T>(type_object);
if type_object.tp_base != unsafe{std::mem::transmute(&ffi::PyBaseObject_Type)} {
type_object.tp_flags = type_object.tp_flags | ffi::Py_TPFLAGS_HEAPTYPE
if type_object.tp_base !=
unsafe{&ffi::PyBaseObject_Type as *const ffi::PyTypeObject as *mut ffi::PyTypeObject} {
type_object.tp_flags |= ffi::Py_TPFLAGS_HEAPTYPE
}
// register type object
@ -526,6 +528,7 @@ fn py_class_flags<T: PyTypeInfo>(type_object: &mut ffi::PyTypeObject) {
}
}
#[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
fn py_class_method_defs<T>() -> PyResult<(Option<ffi::newfunc>,
Option<ffi::initproc>,
Option<ffi::PyCFunctionWithKeywords>,
@ -559,12 +562,8 @@ fn py_class_method_defs<T>() -> PyResult<(Option<ffi::newfunc>,
panic!("Method type is not supoorted by tp_init slot")
}
}
PyMethodDefType::Method(ref def) => {
defs.push(def.as_method_def());
}
PyMethodDefType::Class(ref def) => {
defs.push(def.as_method_def());
}
PyMethodDefType::Method(ref def) |
PyMethodDefType::Class(ref def) |
PyMethodDefType::Static(ref def) => {
defs.push(def.as_method_def());
}

View File

@ -218,8 +218,8 @@ fn data_is_dropped() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = py.init(|t| DataIsDropped{
member1: TestDropCall { drop_called: drop_called1.clone() },
member2: TestDropCall { drop_called: drop_called2.clone() },
member1: TestDropCall { drop_called: Arc::clone(&drop_called1) },
member2: TestDropCall { drop_called: Arc::clone(&drop_called2) },
token: t
}).unwrap();
assert!(!drop_called1.load(Ordering::Relaxed));
@ -460,8 +460,8 @@ fn gc_integration() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = Py::new_ref(py, |t| GCIntegration{
self_ref: RefCell::new(py.None().into()),
dropped: TestDropCall { drop_called: drop_called.clone() },
self_ref: RefCell::new(py.None()),
dropped: TestDropCall { drop_called: Arc::clone(&drop_called) },
token: t}).unwrap();
*inst.self_ref.borrow_mut() = inst.into();
@ -1402,10 +1402,10 @@ fn inheritance_with_new_methods_with_drop() {
let inst = typeobj.call(NoArgs, NoArgs).unwrap();
let obj = SubClassWithDrop::try_from_mut(inst).unwrap();
obj.data = Some(drop_called1.clone());
obj.data = Some(Arc::clone(&drop_called1));
let base = obj.get_mut_base();
base.data = Some(drop_called2.clone());
base.data = Some(Arc::clone(&drop_called2));
}
assert!(drop_called1.load(Ordering::Relaxed));