Fix another bunch of clippy lints
This commit is contained in:
parent
9dd6bb0d2c
commit
771d59b913
|
@ -6,9 +6,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
|
|||
|
||||
## Unreleased
|
||||
|
||||
### Changed
|
||||
|
||||
* All exceptions are consturcted with `py_err` instead of `new`, as they return `PyErr` and not `Self`.
|
||||
* `as_mut` and friends take and `&mut self` instead of `&self`
|
||||
|
||||
### Fixed
|
||||
|
||||
* Added an explenation that the GIL can temporarily be released even while holding a GILGuard.
|
||||
* Lots of clippy errors
|
||||
|
||||
### Removed
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ You can use the `py_exception!` macro to define a new exception type:
|
|||
```rust
|
||||
#[macro_use] extern crate pyo3;
|
||||
|
||||
py_exception!(module, MyError);
|
||||
py_exception!(module, MyError, pyo3::exc::Exception);
|
||||
```
|
||||
|
||||
* `module` is the name of the containing module.
|
||||
|
@ -20,7 +20,7 @@ For example:
|
|||
|
||||
use pyo3::{Python, PyDict};
|
||||
|
||||
py_exception!(mymodule, CustomError);
|
||||
py_exception!(mymodule, CustomError, pyo3::exc::Exception);
|
||||
|
||||
fn main() {
|
||||
let gil = Python::acquire_gil();
|
||||
|
@ -69,7 +69,7 @@ have rust type as well.
|
|||
# fn check_for_error() -> bool {false}
|
||||
fn my_func(arg: PyObject) -> PyResult<()> {
|
||||
if check_for_error() {
|
||||
Err(exc::ValueError::new("argument is wrong"))
|
||||
Err(exc::ValueError::py_err("argument is wrong"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
|
@ -106,7 +106,7 @@ To check the type of an exception, you can simply do:
|
|||
# fn main() {
|
||||
# let gil = Python::acquire_gil();
|
||||
# let py = gil.python();
|
||||
# let err = exc::TypeError::new(NoArgs);
|
||||
# let err = exc::TypeError::py_err(NoArgs);
|
||||
err.is_instance::<exc::TypeError>(py);
|
||||
# }
|
||||
```
|
||||
|
|
|
@ -40,7 +40,7 @@ pub fn parse_args<'p>(
|
|||
let nargs = args.len();
|
||||
let nkeywords = kwargs.map_or(0, |d| d.len());
|
||||
if !accept_args && (nargs + nkeywords > params.len()) {
|
||||
return Err(exc::TypeError::new(format!(
|
||||
return Err(exc::TypeError::py_err(format!(
|
||||
"{}{} takes at most {} argument{} ({} given)",
|
||||
fname.unwrap_or("function"),
|
||||
if fname.is_some() { "()" } else { "" },
|
||||
|
@ -57,7 +57,7 @@ pub fn parse_args<'p>(
|
|||
*out = Some(kwarg);
|
||||
used_keywords += 1;
|
||||
if i < nargs {
|
||||
return Err(exc::TypeError::new(format!(
|
||||
return Err(exc::TypeError::py_err(format!(
|
||||
"Argument given by name ('{}') and position ({})",
|
||||
p.name,
|
||||
i + 1
|
||||
|
@ -67,7 +67,7 @@ pub fn parse_args<'p>(
|
|||
None => {
|
||||
if p.kw_only {
|
||||
if !p.is_optional {
|
||||
return Err(exc::TypeError::new(format!(
|
||||
return Err(exc::TypeError::py_err(format!(
|
||||
"Required argument ('{}') is keyword only argument",
|
||||
p.name
|
||||
)));
|
||||
|
@ -78,7 +78,7 @@ pub fn parse_args<'p>(
|
|||
} else {
|
||||
*out = None;
|
||||
if !p.is_optional {
|
||||
return Err(exc::TypeError::new(format!(
|
||||
return Err(exc::TypeError::py_err(format!(
|
||||
"Required argument ('{}') (pos {}) not found",
|
||||
p.name,
|
||||
i + 1
|
||||
|
@ -94,7 +94,7 @@ pub fn parse_args<'p>(
|
|||
let item = <PyTuple as PyTryFrom>::try_from(item)?;
|
||||
let key = <PyString as PyTryFrom>::try_from(item.get_item(0))?.to_string()?;
|
||||
if !params.iter().any(|p| p.name == key) {
|
||||
return Err(exc::TypeError::new(format!(
|
||||
return Err(exc::TypeError::py_err(format!(
|
||||
"'{}' is an invalid keyword argument for this function",
|
||||
key
|
||||
)));
|
||||
|
|
|
@ -460,7 +460,7 @@ impl PyBuffer {
|
|||
fort: u8,
|
||||
) -> PyResult<()> {
|
||||
if mem::size_of_val(target) != self.len_bytes() {
|
||||
return Err(exc::BufferError::new(
|
||||
return Err(exc::BufferError::py_err(
|
||||
"Slice length does not match buffer length.",
|
||||
));
|
||||
}
|
||||
|
@ -563,7 +563,7 @@ impl PyBuffer {
|
|||
return buffer_readonly_error();
|
||||
}
|
||||
if mem::size_of_val(source) != self.len_bytes() {
|
||||
return Err(exc::BufferError::new(
|
||||
return Err(exc::BufferError::py_err(
|
||||
"Slice length does not match buffer length.",
|
||||
));
|
||||
}
|
||||
|
@ -593,13 +593,15 @@ impl PyBuffer {
|
|||
}
|
||||
|
||||
fn incompatible_format_error() -> PyResult<()> {
|
||||
Err(exc::BufferError::new(
|
||||
Err(exc::BufferError::py_err(
|
||||
"Slice type is incompatible with buffer format.",
|
||||
))
|
||||
}
|
||||
|
||||
fn buffer_readonly_error() -> PyResult<()> {
|
||||
Err(exc::BufferError::new("Cannot write to read-only buffer."))
|
||||
Err(exc::BufferError::py_err(
|
||||
"Cannot write to read-only buffer.",
|
||||
))
|
||||
}
|
||||
|
||||
impl Drop for PyBuffer {
|
||||
|
|
|
@ -14,7 +14,7 @@ use python::{IntoPyPointer, Python};
|
|||
pub trait CallbackConverter<S> {
|
||||
type R;
|
||||
|
||||
fn convert(S, Python) -> Self::R;
|
||||
fn convert(s: S, p: Python) -> Self::R;
|
||||
fn error_value() -> Self::R;
|
||||
}
|
||||
|
||||
|
@ -61,7 +61,7 @@ impl CallbackConverter<usize> for LenResultConverter {
|
|||
if val <= (isize::MAX as usize) {
|
||||
val as isize
|
||||
} else {
|
||||
OverflowError::new(()).restore(py);
|
||||
OverflowError::py_err(()).restore(py);
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
@ -138,7 +138,6 @@ where
|
|||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
pub unsafe fn cb_convert<C, T>(_c: C, py: Python, value: PyResult<T>) -> C::R
|
||||
where
|
||||
C: CallbackConverter<T>,
|
||||
|
|
|
@ -252,7 +252,7 @@ where
|
|||
{
|
||||
fn try_from(value: &PyObjectRef) -> Result<&T, PyDowncastError> {
|
||||
unsafe {
|
||||
if T::is_instance(value.as_ptr()) {
|
||||
if T::is_instance(value) {
|
||||
let ptr = if T::OFFSET == 0 {
|
||||
value as *const _ as *mut u8 as *mut T
|
||||
} else {
|
||||
|
@ -267,7 +267,7 @@ where
|
|||
|
||||
fn try_from_exact(value: &PyObjectRef) -> Result<&T, PyDowncastError> {
|
||||
unsafe {
|
||||
if T::is_exact_instance(value.as_ptr()) {
|
||||
if T::is_exact_instance(value) {
|
||||
let ptr = if T::OFFSET == 0 {
|
||||
value as *const _ as *mut u8 as *mut T
|
||||
} else {
|
||||
|
@ -282,7 +282,7 @@ where
|
|||
|
||||
fn try_from_mut(value: &PyObjectRef) -> Result<&mut T, PyDowncastError> {
|
||||
unsafe {
|
||||
if T::is_instance(value.as_ptr()) {
|
||||
if T::is_instance(value) {
|
||||
let ptr = if T::OFFSET == 0 {
|
||||
value as *const _ as *mut u8 as *mut T
|
||||
} else {
|
||||
|
@ -297,7 +297,7 @@ where
|
|||
|
||||
fn try_from_mut_exact(value: &PyObjectRef) -> Result<&mut T, PyDowncastError> {
|
||||
unsafe {
|
||||
if T::is_exact_instance(value.as_ptr()) {
|
||||
if T::is_exact_instance(value) {
|
||||
let ptr = if T::OFFSET == 0 {
|
||||
value as *const _ as *mut u8 as *mut T
|
||||
} else {
|
||||
|
|
14
src/err.rs
14
src/err.rs
|
@ -17,10 +17,11 @@ use typeob::PyTypeObject;
|
|||
/// Defines a new exception type.
|
||||
///
|
||||
/// # Syntax
|
||||
/// `py_exception!(module, MyError)`
|
||||
/// `py_exception!(module, MyError, pyo3::exc::Exception)`
|
||||
///
|
||||
/// * `module` is the name of the containing module.
|
||||
/// * `MyError` is the name of the new exception type.
|
||||
/// * `pyo3::exc::Exception` is the name of the base type
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
|
@ -29,7 +30,7 @@ use typeob::PyTypeObject;
|
|||
///
|
||||
/// use pyo3::{Python, PyDict};
|
||||
///
|
||||
/// py_exception!(mymodule, CustomError);
|
||||
/// py_exception!(mymodule, CustomError, pyo3::exc::Exception);
|
||||
///
|
||||
/// fn main() {
|
||||
/// let gil = Python::acquire_gil();
|
||||
|
@ -48,7 +49,7 @@ macro_rules! py_exception {
|
|||
($module: ident, $name: ident, $base: ty) => {
|
||||
pub struct $name;
|
||||
|
||||
impl ::std::convert::From<$name> for $crate::PyErr {
|
||||
impl std::convert::From<$name> for $crate::PyErr {
|
||||
fn from(_err: $name) -> $crate::PyErr {
|
||||
$crate::PyErr::new::<$name, _>(())
|
||||
}
|
||||
|
@ -61,7 +62,7 @@ macro_rules! py_exception {
|
|||
}
|
||||
|
||||
impl $name {
|
||||
pub fn new<T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyErr {
|
||||
pub fn py_err<T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyErr {
|
||||
$crate::PyErr::new::<$name, T>(args)
|
||||
}
|
||||
pub fn into<R, T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyResult<R> {
|
||||
|
@ -90,7 +91,7 @@ macro_rules! py_exception {
|
|||
}
|
||||
|
||||
impl $crate::typeob::PyTypeObject for $name {
|
||||
#[inline(always)]
|
||||
#[inline]
|
||||
fn init_type() {
|
||||
let _ = $name::type_object();
|
||||
}
|
||||
|
@ -105,9 +106,6 @@ macro_rules! py_exception {
|
|||
}
|
||||
}
|
||||
};
|
||||
($module: ident, $name: ident) => {
|
||||
py_exception!($module, $name, $crate::exc::Exception);
|
||||
};
|
||||
}
|
||||
|
||||
/// Represents a `PyErr` value
|
||||
|
|
|
@ -564,9 +564,9 @@ mod typeobject {
|
|||
pub unsafe fn PyHeapType_GET_MEMBERS(
|
||||
etype: *mut PyHeapTypeObject,
|
||||
) -> *mut ffi3::structmember::PyMemberDef {
|
||||
(etype as *mut c_char).offset(
|
||||
(*ffi3::object::Py_TYPE(etype as *mut ffi3::object::PyObject)).tp_basicsize as isize,
|
||||
) as *mut ffi3::structmember::PyMemberDef
|
||||
let py_type = ffi3::object::Py_TYPE(etype as *mut ffi3::object::PyObject);
|
||||
let ptr = (etype as *mut c_char).offset((*py_type).tp_basicsize);
|
||||
ptr as *mut ffi3::structmember::PyMemberDef
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -7,6 +7,7 @@ use std::rc::Rc;
|
|||
use conversion::{FromPyObject, IntoPyObject, ToPyObject};
|
||||
use err::{PyErr, PyResult};
|
||||
use ffi;
|
||||
use instance;
|
||||
use object::PyObject;
|
||||
use objectprotocol::ObjectProtocol;
|
||||
use objects::PyObjectRef;
|
||||
|
@ -42,8 +43,7 @@ pub trait AsPyRef<T>: Sized {
|
|||
fn as_ref(&self, py: Python) -> &T;
|
||||
|
||||
/// Return mutable reference to object.
|
||||
|
||||
fn as_mut(&self, py: Python) -> &mut T;
|
||||
fn as_mut(&mut self, py: Python) -> &mut T;
|
||||
|
||||
/// Acquire python gil and call closure with object reference.
|
||||
fn with<F, R>(&self, f: F) -> R
|
||||
|
@ -57,7 +57,7 @@ pub trait AsPyRef<T>: Sized {
|
|||
}
|
||||
|
||||
/// Acquire python gil and call closure with mutable object reference.
|
||||
fn with_mut<F, R>(&self, f: F) -> R
|
||||
fn with_mut<F, R>(&mut self, f: F) -> R
|
||||
where
|
||||
F: FnOnce(Python, &mut T) -> R,
|
||||
{
|
||||
|
@ -80,7 +80,7 @@ pub trait AsPyRef<T>: Sized {
|
|||
result
|
||||
}
|
||||
|
||||
fn into_mut_py<F, R>(self, f: F) -> R
|
||||
fn into_mut_py<F, R>(mut self, f: F) -> R
|
||||
where
|
||||
Self: IntoPyPointer,
|
||||
F: FnOnce(Python, &mut T) -> R,
|
||||
|
@ -222,7 +222,7 @@ where
|
|||
}
|
||||
}
|
||||
#[inline]
|
||||
default fn as_mut(&self, _py: Python) -> &mut T {
|
||||
default fn as_mut(&mut self, _py: Python) -> &mut T {
|
||||
unsafe {
|
||||
let ptr = (self.as_ptr() as *mut u8).offset(T::OFFSET) as *mut T;
|
||||
ptr.as_mut().unwrap()
|
||||
|
@ -236,10 +236,10 @@ where
|
|||
{
|
||||
#[inline]
|
||||
fn as_ref(&self, _py: Python) -> &T {
|
||||
unsafe { std::mem::transmute(self) }
|
||||
unsafe { &*(self as *const instance::Py<T> as *const T) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_mut(&self, _py: Python) -> &mut T {
|
||||
fn as_mut(&mut self, _py: Python) -> &mut T {
|
||||
unsafe { &mut *(self as *const _ as *mut T) }
|
||||
}
|
||||
}
|
||||
|
|
|
@ -279,7 +279,7 @@ impl AsPyRef<PyObjectRef> for PyObject {
|
|||
unsafe { &*(self as *const _ as *mut PyObjectRef) }
|
||||
}
|
||||
#[inline]
|
||||
fn as_mut(&self, _py: Python) -> &mut PyObjectRef {
|
||||
fn as_mut(&mut self, _py: Python) -> &mut PyObjectRef {
|
||||
unsafe { &mut *(self as *const _ as *mut PyObjectRef) }
|
||||
}
|
||||
}
|
||||
|
|
|
@ -172,7 +172,7 @@ pub trait ObjectProtocol {
|
|||
|
||||
/// Gets the Python base object for this object.
|
||||
|
||||
fn get_mut_base(&self) -> &mut <Self as PyTypeInfo>::BaseType
|
||||
fn get_mut_base(&mut self) -> &mut <Self as PyTypeInfo>::BaseType
|
||||
where
|
||||
Self: PyTypeInfo;
|
||||
|
||||
|
@ -271,7 +271,7 @@ where
|
|||
} else if result < 0 {
|
||||
return Err(PyErr::fetch(py));
|
||||
}
|
||||
Err(::exc::TypeError::new(
|
||||
Err(::exc::TypeError::py_err(
|
||||
"ObjectProtocol::compare(): All comparisons returned false",
|
||||
))
|
||||
}
|
||||
|
@ -493,7 +493,7 @@ where
|
|||
unsafe { self.py().from_borrowed_ptr(self.as_ptr()) }
|
||||
}
|
||||
|
||||
fn get_mut_base(&self) -> &mut <Self as PyTypeInfo>::BaseType
|
||||
fn get_mut_base(&mut self) -> &mut <Self as PyTypeInfo>::BaseType
|
||||
where
|
||||
Self: PyTypeInfo,
|
||||
{
|
||||
|
|
|
@ -47,8 +47,7 @@ impl PyByteArray {
|
|||
}
|
||||
|
||||
/// Gets the Python bytearray data as byte slice.
|
||||
|
||||
pub fn data(&self) -> &mut [u8] {
|
||||
pub fn data(&self) -> &[u8] {
|
||||
unsafe {
|
||||
let buffer = ffi::PyByteArray_AsString(self.0.as_ptr()) as *mut u8;
|
||||
let length = ffi::PyByteArray_Size(self.0.as_ptr()) as usize;
|
||||
|
|
|
@ -2,19 +2,18 @@
|
|||
|
||||
//! This module contains the standard python exception types.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::c_char;
|
||||
use std::{self, mem, ops};
|
||||
|
||||
use conversion::ToPyObject;
|
||||
use err::{PyErr, PyResult};
|
||||
use ffi;
|
||||
use instance::Py;
|
||||
use objects::{PyObjectRef, PyTuple, PyType};
|
||||
use python::{Python, ToPyPointer};
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::c_char;
|
||||
use std::{self, ops};
|
||||
use typeob::PyTypeObject;
|
||||
|
||||
macro_rules! exc_type(
|
||||
macro_rules! exc_type (
|
||||
($name:ident, $exc_name:ident) => (
|
||||
pub struct $name;
|
||||
|
||||
|
@ -29,8 +28,7 @@ macro_rules! exc_type(
|
|||
}
|
||||
}
|
||||
impl $name {
|
||||
|
||||
pub fn new<V: ToPyObject + 'static>(args: V) -> PyErr {
|
||||
pub fn py_err<V: ToPyObject + 'static>(args: V) -> PyErr {
|
||||
PyErr::new::<$name, V>(args)
|
||||
}
|
||||
pub fn into<R, V: ToPyObject + 'static>(args: V) -> PyResult<R> {
|
||||
|
@ -38,7 +36,7 @@ macro_rules! exc_type(
|
|||
}
|
||||
}
|
||||
impl PyTypeObject for $name {
|
||||
#[inline(always)]
|
||||
#[inline]
|
||||
fn init_type() {}
|
||||
|
||||
#[inline]
|
||||
|
@ -139,7 +137,7 @@ impl UnicodeDecodeError {
|
|||
reason: &CStr,
|
||||
) -> PyResult<&'p PyObjectRef> {
|
||||
unsafe {
|
||||
let input: &[c_char] = mem::transmute(input);
|
||||
let input: &[c_char] = &*(input as *const [u8] as *const [i8]);
|
||||
py.from_owned_ptr_or_err(ffi::PyUnicodeDecodeError_Create(
|
||||
encoding.as_ptr(),
|
||||
input.as_ptr(),
|
||||
|
|
|
@ -55,8 +55,7 @@ macro_rules! import_exception {
|
|||
}
|
||||
|
||||
impl $name {
|
||||
|
||||
pub fn new<T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyErr
|
||||
pub fn py_err<T: $crate::ToPyObject + 'static>(args: T) -> $crate::PyErr
|
||||
where Self: $crate::typeob::PyTypeObject + Sized
|
||||
{
|
||||
$crate::PyErr::new::<Self, T>(args)
|
||||
|
|
|
@ -50,28 +50,28 @@ impl IntoPyObject for f64 {
|
|||
}
|
||||
|
||||
impl<'source> FromPyObject<'source> for f64 {
|
||||
// PyFloat_AsDouble returns -1.0 upon failure
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp))]
|
||||
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
|
||||
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)
|
||||
}
|
||||
if v == -1.0 && PyErr::occurred(obj.py()) {
|
||||
Err(PyErr::fetch(obj.py()))
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToPyObject for f32 {
|
||||
fn to_object(&self, py: Python) -> PyObject {
|
||||
PyFloat::new(py, *self as f64).into()
|
||||
PyFloat::new(py, f64::from(*self)).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoPyObject for f32 {
|
||||
fn into_object(self, py: Python) -> PyObject {
|
||||
PyFloat::new(py, self as f64).into()
|
||||
PyFloat::new(py, f64::from(self)).into()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
// Copyright (c) 2017-present PyO3 Project and Contributors
|
||||
|
||||
#[macro_use]
|
||||
mod exc_impl;
|
||||
|
||||
pub use self::boolobject::PyBool;
|
||||
pub use self::bytearray::PyByteArray;
|
||||
pub use self::dict::PyDict;
|
||||
|
@ -10,31 +7,32 @@ pub use self::floatob::PyFloat;
|
|||
pub use self::iterator::PyIterator;
|
||||
pub use self::list::PyList;
|
||||
pub use self::module::PyModule;
|
||||
pub use self::sequence::PySequence;
|
||||
pub use self::set::{PyFrozenSet, PySet};
|
||||
pub use self::slice::{PySlice, PySliceIndices};
|
||||
pub use self::stringdata::PyStringData;
|
||||
pub use self::tuple::PyTuple;
|
||||
pub use self::typeobject::PyType;
|
||||
|
||||
#[cfg(Py_3)]
|
||||
pub use self::string::{PyBytes, PyString, PyUnicode};
|
||||
|
||||
#[cfg(not(Py_3))]
|
||||
pub use self::string2::{PyBytes, PyString, PyUnicode};
|
||||
|
||||
pub use self::num2::{PyInt, PyLong};
|
||||
#[cfg(Py_3)]
|
||||
pub use self::num3::PyLong;
|
||||
#[cfg(Py_3)]
|
||||
pub use self::num3::PyLong as PyInt;
|
||||
|
||||
pub use self::sequence::PySequence;
|
||||
pub use self::set::{PyFrozenSet, PySet};
|
||||
pub use self::slice::{PySlice, PySliceIndices};
|
||||
#[cfg(Py_3)]
|
||||
pub use self::string::{PyBytes, PyString, PyUnicode};
|
||||
#[cfg(not(Py_3))]
|
||||
pub use self::num2::{PyInt, PyLong};
|
||||
pub use self::string2::{PyBytes, PyString, PyUnicode};
|
||||
pub use self::stringdata::PyStringData;
|
||||
pub use self::tuple::PyTuple;
|
||||
pub use self::typeobject::PyType;
|
||||
use ffi;
|
||||
use python::ToPyPointer;
|
||||
|
||||
#[macro_use]
|
||||
mod exc_impl;
|
||||
|
||||
/// Implements a typesafe conversions throught [FromPyObject], given a typecheck function as second
|
||||
/// parameter
|
||||
#[macro_export]
|
||||
macro_rules! pyobject_downcast(
|
||||
macro_rules! pyobject_downcast (
|
||||
($name: ty, $checkfunction: path $(,$type_param: ident)*) => (
|
||||
impl<'a, $($type_param,)*> $crate::FromPyObject<'a> for &'a $name
|
||||
{
|
||||
|
@ -54,7 +52,7 @@ macro_rules! pyobject_downcast(
|
|||
);
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! pyobject_native_type_named(
|
||||
macro_rules! pyobject_native_type_named (
|
||||
($name: ty $(,$type_param: ident)*) => {
|
||||
impl<$($type_param,)*> $crate::PyNativeType for $name {}
|
||||
|
||||
|
@ -89,7 +87,7 @@ macro_rules! pyobject_native_type_named(
|
|||
);
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! pyobject_native_type(
|
||||
macro_rules! pyobject_native_type (
|
||||
($name: ty, $typeobject: expr, $checkfunction: path $(,$type_param: ident)*) => {
|
||||
pyobject_native_type_named!($name $(,$type_param)*);
|
||||
pyobject_native_type_convert!($name, $typeobject, $checkfunction $(,$type_param)*);
|
||||
|
@ -118,10 +116,9 @@ macro_rules! pyobject_native_type_convert(
|
|||
&mut $typeobject
|
||||
}
|
||||
|
||||
|
||||
fn is_instance(ptr: *mut $crate::ffi::PyObject) -> bool {
|
||||
fn is_instance(ptr: &$crate::objects::PyObjectRef) -> bool {
|
||||
#[allow(unused_unsafe)]
|
||||
unsafe { $checkfunction(ptr) > 0 }
|
||||
unsafe { $checkfunction(ptr.as_ptr()) > 0 }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -175,8 +172,6 @@ macro_rules! pyobject_native_type_convert(
|
|||
};
|
||||
);
|
||||
|
||||
use ffi;
|
||||
use python::ToPyPointer;
|
||||
/// Represents general python instance.
|
||||
#[repr(transparent)]
|
||||
pub struct PyObjectRef(::PyObject);
|
||||
|
|
|
@ -162,9 +162,9 @@ impl PyModule {
|
|||
PyType::new::<T>()
|
||||
} else {
|
||||
// automatically initialize the class
|
||||
initialize_type::<T>(self.py(), Some(self.name()?)).expect(
|
||||
format!("An error occurred while initializing class {}", T::NAME).as_ref(),
|
||||
);
|
||||
initialize_type::<T>(self.py(), Some(self.name()?)).unwrap_or_else(|_| {
|
||||
panic!("An error occurred while initializing class {}", T::NAME)
|
||||
});
|
||||
PyType::new::<T>()
|
||||
}
|
||||
};
|
||||
|
|
|
@ -13,6 +13,7 @@ use instance::PyObjectWithToken;
|
|||
use object::PyObject;
|
||||
use objects::{exc, PyObjectRef};
|
||||
use python::{Python, ToPyPointer};
|
||||
use std::i64;
|
||||
use std::os::raw::{c_long, c_uchar};
|
||||
|
||||
/// Represents a Python `int` object.
|
||||
|
@ -29,7 +30,7 @@ pyobject_native_type!(PyLong, ffi::PyLong_Type, ffi::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,7 +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))
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
// Copyright (c) 2017-present PyO3 Project and Contributors
|
||||
|
||||
use std;
|
||||
|
||||
use buffer;
|
||||
use conversion::{FromPyObject, PyTryFrom, ToBorrowedObject};
|
||||
use err::{self, PyDowncastError, PyErr, PyResult};
|
||||
|
@ -39,7 +37,7 @@ impl PySequence {
|
|||
self.as_ptr(),
|
||||
other.as_ptr(),
|
||||
))?;
|
||||
Ok(std::mem::transmute(ptr))
|
||||
Ok(&*(ptr as *const PyObjectRef as *const PySequence))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -55,7 +53,7 @@ impl PySequence {
|
|||
self.as_ptr(),
|
||||
count as Py_ssize_t,
|
||||
))?;
|
||||
Ok(std::mem::transmute(ptr))
|
||||
Ok(&*(ptr as *const PyObjectRef as *const PySequence))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::{char, mem, str};
|
||||
use std::{char, str};
|
||||
|
||||
use err::{PyErr, PyResult};
|
||||
use objects::exc;
|
||||
|
@ -63,7 +63,7 @@ impl<'a> PyStringData<'a> {
|
|||
}
|
||||
PyStringData::Utf16(data) => {
|
||||
fn utf16_bytes(input: &[u16]) -> &[u8] {
|
||||
unsafe { mem::transmute(input) }
|
||||
unsafe { &*(input as *const [u16] as *const [u8]) }
|
||||
}
|
||||
match String::from_utf16(data) {
|
||||
Ok(s) => Ok(Cow::Owned(s)),
|
||||
|
@ -78,7 +78,7 @@ impl<'a> PyStringData<'a> {
|
|||
}
|
||||
PyStringData::Utf32(data) => {
|
||||
fn utf32_bytes(input: &[u32]) -> &[u8] {
|
||||
unsafe { mem::transmute(input) }
|
||||
unsafe { &*(input as *const [u32] as *const [u8]) }
|
||||
}
|
||||
match data.iter().map(|&u| char::from_u32(u)).collect() {
|
||||
Some(s) => Ok(Cow::Owned(s)),
|
||||
|
|
|
@ -82,7 +82,8 @@ impl PyTuple {
|
|||
// (We don't even need a Python token, thanks to immutability)
|
||||
unsafe {
|
||||
let ptr = self.as_ptr() as *mut ffi::PyTupleObject;
|
||||
std::mem::transmute(slice::from_raw_parts((*ptr).ob_item.as_ptr(), self.len()))
|
||||
let slice = slice::from_raw_parts((*ptr).ob_item.as_ptr(), self.len());
|
||||
&*(slice as *const [*mut ffi::PyObject] as *const [PyObject])
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -155,7 +156,7 @@ fn wrong_tuple_length(t: &PyTuple, expected_length: usize) -> PyErr {
|
|||
expected_length,
|
||||
t.len()
|
||||
);
|
||||
exc::ValueError::new(msg)
|
||||
exc::ValueError::py_err(msg)
|
||||
}
|
||||
|
||||
macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
// Copyright (c) 2017-present PyO3 Project and Contributors
|
||||
use spin;
|
||||
use std::{any, marker, mem, rc, sync};
|
||||
use std::{any, marker, rc, sync};
|
||||
|
||||
use ffi;
|
||||
use objects::PyObjectRef;
|
||||
|
@ -242,13 +242,13 @@ pub unsafe fn register_pointer(obj: *mut ffi::PyObject) {
|
|||
pub unsafe fn register_owned(_py: Python, obj: *mut ffi::PyObject) -> &PyObjectRef {
|
||||
let pool: &'static mut ReleasePool = &mut *POOL;
|
||||
pool.owned.push(obj);
|
||||
mem::transmute(&pool.owned[pool.owned.len() - 1])
|
||||
&*(&pool.owned[pool.owned.len() - 1] as *const *mut ffi::PyObject as *const PyObjectRef)
|
||||
}
|
||||
|
||||
pub unsafe fn register_borrowed(_py: Python, obj: *mut ffi::PyObject) -> &PyObjectRef {
|
||||
let pool: &'static mut ReleasePool = &mut *POOL;
|
||||
pool.borrowed.push(obj);
|
||||
mem::transmute(&pool.borrowed[pool.borrowed.len() - 1])
|
||||
&*(&pool.borrowed[pool.borrowed.len() - 1] as *const *mut ffi::PyObject as *const PyObjectRef)
|
||||
}
|
||||
|
||||
impl GILGuard {
|
||||
|
|
|
@ -2,16 +2,17 @@
|
|||
|
||||
//! Python type object information
|
||||
|
||||
use class::methods::PyMethodDefType;
|
||||
use err::{PyErr, PyResult};
|
||||
use instance::{Py, PyObjectWithToken, PyToken};
|
||||
use objects::PyObjectRef;
|
||||
use objects::PyType;
|
||||
use python::ToPyPointer;
|
||||
use python::{IntoPyPointer, Python};
|
||||
use std;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::CString;
|
||||
use std::mem;
|
||||
|
||||
use class::methods::PyMethodDefType;
|
||||
use err::{PyErr, PyResult};
|
||||
use instance::{Py, PyObjectWithToken, PyToken};
|
||||
use objects::PyType;
|
||||
use python::{IntoPyPointer, Python};
|
||||
use std::os::raw::c_void;
|
||||
use {class, ffi, pythonrun};
|
||||
|
||||
|
@ -42,15 +43,13 @@ pub trait PyTypeInfo {
|
|||
unsafe fn type_object() -> &'static mut ffi::PyTypeObject;
|
||||
|
||||
/// Check if `*mut ffi::PyObject` is instance of this type
|
||||
|
||||
fn is_instance(ptr: *mut ffi::PyObject) -> bool {
|
||||
unsafe { ffi::PyObject_TypeCheck(ptr, Self::type_object()) != 0 }
|
||||
fn is_instance(object: &PyObjectRef) -> bool {
|
||||
unsafe { ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object()) != 0 }
|
||||
}
|
||||
|
||||
/// Check if `*mut ffi::PyObject` is exact instance of this type
|
||||
|
||||
fn is_exact_instance(ptr: *mut ffi::PyObject) -> bool {
|
||||
unsafe { (*ptr).ob_type == Self::type_object() }
|
||||
fn is_exact_instance(object: &PyObjectRef) -> bool {
|
||||
unsafe { (*object.as_ptr()).ob_type == Self::type_object() }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -81,12 +80,12 @@ impl<'a, T: PyTypeInfo + ?Sized> PyTypeInfo for &'a T {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
default fn is_instance(ptr: *mut ffi::PyObject) -> bool {
|
||||
default fn is_instance(ptr: &PyObjectRef) -> bool {
|
||||
<T as PyTypeInfo>::is_instance(ptr)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
default fn is_exact_instance(ptr: *mut ffi::PyObject) -> bool {
|
||||
default fn is_exact_instance(ptr: &PyObjectRef) -> bool {
|
||||
<T as PyTypeInfo>::is_exact_instance(ptr)
|
||||
}
|
||||
}
|
||||
|
@ -185,10 +184,10 @@ impl PyRawObject {
|
|||
pub fn type_object(&self) -> &PyType {
|
||||
unsafe { PyType::from_type_ptr(self.py(), self.curr_ptr) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Return reference to object.
|
||||
|
||||
pub fn as_ref<T: PyTypeInfo>(&self) -> &T {
|
||||
impl<T: PyTypeInfo> AsRef<T> for PyRawObject {
|
||||
fn as_ref(&self) -> &T {
|
||||
// TODO: check is object initialized
|
||||
unsafe {
|
||||
let ptr = (self.ptr as *mut u8).offset(T::OFFSET) as *mut T;
|
||||
|
@ -342,10 +341,9 @@ where
|
|||
let gil = Python::acquire_gil();
|
||||
let py = gil.python();
|
||||
|
||||
initialize_type::<T>(py, None).expect(&format!(
|
||||
"An error occurred while initializing class {}",
|
||||
T::NAME
|
||||
));
|
||||
initialize_type::<T>(py, None).unwrap_or_else(|_| {
|
||||
panic!("An error occurred while initializing class {}", T::NAME)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,6 +5,7 @@ extern crate pyo3;
|
|||
use std::os::raw::{c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
use pyo3::exc::BufferError;
|
||||
use pyo3::ffi;
|
||||
use pyo3::prelude::*;
|
||||
|
||||
|
@ -18,7 +19,7 @@ struct TestClass {
|
|||
impl PyBufferProtocol for TestClass {
|
||||
fn bf_getbuffer(&self, view: *mut ffi::Py_buffer, flags: c_int) -> PyResult<()> {
|
||||
if view.is_null() {
|
||||
return Err(PyErr::new::<exc::BufferError, _>("View is null"));
|
||||
return Err(BufferError::py_err("View is null"));
|
||||
}
|
||||
|
||||
unsafe {
|
||||
|
@ -26,7 +27,7 @@ impl PyBufferProtocol for TestClass {
|
|||
}
|
||||
|
||||
if (flags & ffi::PyBUF_WRITABLE) == ffi::PyBUF_WRITABLE {
|
||||
return Err(PyErr::new::<exc::BufferError, _>("Object is not writable"));
|
||||
return Err(BufferError::py_err("Object is not writable"));
|
||||
}
|
||||
|
||||
let bytes = &self.vec;
|
||||
|
|
Loading…
Reference in New Issue