diff --git a/Cargo.toml b/Cargo.toml index f67a157f32c..db3afea11cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,7 +85,9 @@ parking_lot = { version = "0.12.3", features = ["arc_lock"] } pyo3-build-config = { path = "pyo3-build-config", version = "=0.28.2", features = ["resolve-config"] } [features] -default = ["macros"] +default = ["std", "macros"] + +std = [] # Enables support for `async fn` for `#[pyfunction]` and `#[pymethods]`. experimental-async = ["macros", "pyo3-macros/experimental-async"] diff --git a/newsfragments/5856.changed.md b/newsfragments/5856.changed.md new file mode 100644 index 00000000000..07025df4438 --- /dev/null +++ b/newsfragments/5856.changed.md @@ -0,0 +1 @@ +Add feature `std` which is enabled by default. Implemetations of `pyo3` traits on `std` types are gated behind this feature. diff --git a/pyo3-ffi/src/abstract_.rs b/pyo3-ffi/src/abstract_.rs index 8f2b4831231..e11e0e88032 100644 --- a/pyo3-ffi/src/abstract_.rs +++ b/pyo3-ffi/src/abstract_.rs @@ -1,8 +1,8 @@ use crate::object::*; use crate::pyport::Py_ssize_t; +use core::ffi::{c_char, c_int}; #[cfg(any(Py_3_12, all(Py_3_8, not(Py_LIMITED_API))))] use libc::size_t; -use std::ffi::{c_char, c_int}; #[inline] #[cfg(all( @@ -10,7 +10,7 @@ use std::ffi::{c_char, c_int}; not(all(PyPy, not(Py_3_11))) // PyPy exposed as a function until PyPy 3.10, macro in 3.11+ ))] pub unsafe fn PyObject_DelAttrString(o: *mut PyObject, attr_name: *const c_char) -> c_int { - PyObject_SetAttrString(o, attr_name, std::ptr::null_mut()) + PyObject_SetAttrString(o, attr_name, core::ptr::null_mut()) } #[inline] @@ -19,7 +19,7 @@ pub unsafe fn PyObject_DelAttrString(o: *mut PyObject, attr_name: *const c_char) not(all(PyPy, not(Py_3_11))) // PyPy exposed as a function until PyPy 3.10, macro in 3.11+ ))] pub unsafe fn PyObject_DelAttr(o: *mut PyObject, attr_name: *mut PyObject) -> c_int { - PyObject_SetAttr(o, attr_name, std::ptr::null_mut()) + PyObject_SetAttr(o, attr_name, core::ptr::null_mut()) } extern "C" { @@ -81,7 +81,7 @@ extern "C" { } #[cfg(any(Py_3_12, all(Py_3_8, not(Py_LIMITED_API))))] pub const PY_VECTORCALL_ARGUMENTS_OFFSET: size_t = - 1 << (8 * std::mem::size_of::() as size_t - 1); + 1 << (8 * core::mem::size_of::() as size_t - 1); extern "C" { #[cfg_attr(PyPy, link_name = "PyPyObject_Vectorcall")] diff --git a/pyo3-ffi/src/boolobject.rs b/pyo3-ffi/src/boolobject.rs index 4d2ce70a600..9cffac70c4f 100644 --- a/pyo3-ffi/src/boolobject.rs +++ b/pyo3-ffi/src/boolobject.rs @@ -1,8 +1,8 @@ #[cfg(not(GraalPy))] use crate::longobject::PyLongObject; use crate::object::*; -use std::ffi::{c_int, c_long}; -use std::ptr::addr_of_mut; +use core::ffi::{c_int, c_long}; +use core::ptr::addr_of_mut; #[inline] pub unsafe fn PyBool_Check(op: *mut PyObject) -> c_int { diff --git a/pyo3-ffi/src/bytearrayobject.rs b/pyo3-ffi/src/bytearrayobject.rs index 3b874e51bca..9c3601ea191 100644 --- a/pyo3-ffi/src/bytearrayobject.rs +++ b/pyo3-ffi/src/bytearrayobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int}; +use core::ptr::addr_of_mut; #[cfg(not(any(PyPy, GraalPy, Py_LIMITED_API)))] #[repr(C)] diff --git a/pyo3-ffi/src/bytesobject.rs b/pyo3-ffi/src/bytesobject.rs index 08351d18daa..3ed43d7f47d 100644 --- a/pyo3-ffi/src/bytesobject.rs +++ b/pyo3-ffi/src/bytesobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int}; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/ceval.rs b/pyo3-ffi/src/ceval.rs index 3a2f6935395..56f9e1fe2ac 100644 --- a/pyo3-ffi/src/ceval.rs +++ b/pyo3-ffi/src/ceval.rs @@ -1,6 +1,6 @@ use crate::object::PyObject; use crate::pytypedefs::PyThreadState; -use std::ffi::{c_char, c_int, c_void}; +use core::ffi::{c_char, c_int, c_void}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyEval_EvalCode")] @@ -39,7 +39,7 @@ extern "C" { #[inline] pub unsafe fn PyEval_CallObject(func: *mut PyObject, arg: *mut PyObject) -> *mut PyObject { #[allow(deprecated)] - PyEval_CallObjectWithKeywords(func, arg, std::ptr::null_mut()) + PyEval_CallObjectWithKeywords(func, arg, core::ptr::null_mut()) } extern "C" { diff --git a/pyo3-ffi/src/codecs.rs b/pyo3-ffi/src/codecs.rs index 9e4c52c9348..a5a34115c21 100644 --- a/pyo3-ffi/src/codecs.rs +++ b/pyo3-ffi/src/codecs.rs @@ -1,5 +1,5 @@ use crate::object::PyObject; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; extern "C" { pub fn PyCodec_Register(search_function: *mut PyObject) -> c_int; diff --git a/pyo3-ffi/src/compat/py_3_10.rs b/pyo3-ffi/src/compat/py_3_10.rs index 2d4daa194c6..5c931de4d85 100644 --- a/pyo3-ffi/src/compat/py_3_10.rs +++ b/pyo3-ffi/src/compat/py_3_10.rs @@ -24,9 +24,9 @@ compat_function!( #[inline] pub unsafe fn PyModule_AddObjectRef( module: *mut crate::PyObject, - name: *const std::ffi::c_char, + name: *const core::ffi::c_char, value: *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { if value.is_null() && crate::PyErr_Occurred().is_null() { crate::PyErr_SetString( crate::PyExc_SystemError, diff --git a/pyo3-ffi/src/compat/py_3_13.rs b/pyo3-ffi/src/compat/py_3_13.rs index 08bdf5cba18..699714b4f98 100644 --- a/pyo3-ffi/src/compat/py_3_13.rs +++ b/pyo3-ffi/src/compat/py_3_13.rs @@ -6,7 +6,7 @@ compat_function!( dp: *mut crate::PyObject, key: *mut crate::PyObject, result: *mut *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { use crate::{compat::Py_NewRef, PyDict_GetItemWithError, PyErr_Occurred}; let item = PyDict_GetItemWithError(dp, key); @@ -14,7 +14,7 @@ compat_function!( *result = Py_NewRef(item); return 1; // found } - *result = std::ptr::null_mut(); + *result = core::ptr::null_mut(); if PyErr_Occurred().is_null() { return 0; // not found } @@ -43,7 +43,7 @@ compat_function!( #[inline] pub unsafe fn PyImport_AddModuleRef( - name: *const std::ffi::c_char, + name: *const core::ffi::c_char, ) -> *mut crate::PyObject { use crate::{compat::Py_XNewRef, PyImport_AddModule}; @@ -58,25 +58,25 @@ compat_function!( pub unsafe fn PyWeakref_GetRef( reference: *mut crate::PyObject, pobj: *mut *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { use crate::{ compat::Py_NewRef, PyErr_SetString, PyExc_TypeError, PyWeakref_Check, PyWeakref_GetObject, Py_None, }; if !reference.is_null() && PyWeakref_Check(reference) == 0 { - *pobj = std::ptr::null_mut(); + *pobj = core::ptr::null_mut(); PyErr_SetString(PyExc_TypeError, c"expected a weakref".as_ptr()); return -1; } let obj = PyWeakref_GetObject(reference); if obj.is_null() { // SystemError if reference is NULL - *pobj = std::ptr::null_mut(); + *pobj = core::ptr::null_mut(); return -1; } if obj == Py_None() { - *pobj = std::ptr::null_mut(); + *pobj = core::ptr::null_mut(); return 0; } *pobj = Py_NewRef(obj); @@ -91,7 +91,7 @@ compat_function!( pub unsafe fn PyList_Extend( list: *mut crate::PyObject, iterable: *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { crate::PyList_SetSlice(list, crate::PY_SSIZE_T_MAX, crate::PY_SSIZE_T_MAX, iterable) } ); @@ -100,8 +100,8 @@ compat_function!( originally_defined_for(Py_3_13); #[inline] - pub unsafe fn PyList_Clear(list: *mut crate::PyObject) -> std::ffi::c_int { - crate::PyList_SetSlice(list, 0, crate::PY_SSIZE_T_MAX, std::ptr::null_mut()) + pub unsafe fn PyList_Clear(list: *mut crate::PyObject) -> core::ffi::c_int { + crate::PyList_SetSlice(list, 0, crate::PY_SSIZE_T_MAX, core::ptr::null_mut()) } ); @@ -111,9 +111,9 @@ compat_function!( #[inline] pub unsafe fn PyModule_Add( module: *mut crate::PyObject, - name: *const std::ffi::c_char, + name: *const core::ffi::c_char, value: *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { let result = crate::compat::PyModule_AddObjectRef(module, name, value); crate::Py_XDECREF(value); result diff --git a/pyo3-ffi/src/compat/py_3_14.rs b/pyo3-ffi/src/compat/py_3_14.rs index 28cef7975c9..879ec93e77e 100644 --- a/pyo3-ffi/src/compat/py_3_14.rs +++ b/pyo3-ffi/src/compat/py_3_14.rs @@ -3,7 +3,7 @@ compat_function!( #[inline] pub unsafe fn Py_HashBuffer( - ptr: *const std::ffi::c_void, + ptr: *const core::ffi::c_void, len: crate::Py_ssize_t, ) -> crate::Py_hash_t { #[cfg(not(any(Py_LIMITED_API, PyPy)))] @@ -13,7 +13,7 @@ compat_function!( #[cfg(any(Py_LIMITED_API, PyPy))] { - let bytes = crate::PyBytes_FromStringAndSize(ptr as *const std::ffi::c_char, len); + let bytes = crate::PyBytes_FromStringAndSize(ptr as *const core::ffi::c_char, len); if bytes.is_null() { -1 } else { @@ -32,7 +32,7 @@ compat_function!( pub unsafe fn PyIter_NextItem( iter: *mut crate::PyObject, item: *mut *mut crate::PyObject, - ) -> std::ffi::c_int { + ) -> core::ffi::c_int { *item = crate::PyIter_Next(iter); if !(*item).is_null() { 1 diff --git a/pyo3-ffi/src/compat/py_3_15.rs b/pyo3-ffi/src/compat/py_3_15.rs index 052fd9fd481..c3efc30e054 100644 --- a/pyo3-ffi/src/compat/py_3_15.rs +++ b/pyo3-ffi/src/compat/py_3_15.rs @@ -12,22 +12,22 @@ compat_function!( if size < 0 { crate::PyErr_SetString(crate::PyExc_ValueError, c"size must be >= 0".as_ptr() as *const _); - return std::ptr::null_mut(); + return core::ptr::null_mut(); } - let writer: *mut PyBytesWriter = crate::PyMem_Malloc(std::mem::size_of::()).cast(); + let writer: *mut PyBytesWriter = crate::PyMem_Malloc(core::mem::size_of::()).cast(); if writer.is_null() { crate::PyErr_NoMemory(); - return std::ptr::null_mut(); + return core::ptr::null_mut(); } - (*writer).obj = std::ptr::null_mut(); + (*writer).obj = core::ptr::null_mut(); (*writer).size = 0; if size >=1 { if _PyBytesWriter_Resize_impl(writer, size, 0) < 0 { PyBytesWriter_Discard(writer); - return std::ptr::null_mut(); + return core::ptr::null_mut(); } (*writer).size = size; @@ -75,9 +75,9 @@ compat_function!( } else { if size != crate::PyBytes_Size((*writer).obj) && crate::_PyBytes_Resize(&mut (*writer).obj, size) < 0 { PyBytesWriter_Discard(writer); - return std::ptr::null_mut(); + return core::ptr::null_mut(); } - std::mem::replace(&mut (*writer).obj, std::ptr::null_mut()) + core::mem::replace(&mut (*writer).obj, core::ptr::null_mut()) }; PyBytesWriter_Discard(writer); @@ -90,7 +90,7 @@ compat_function!( originally_defined_for(all(Py_3_15, not(Py_LIMITED_API))); #[inline] - pub unsafe fn PyBytesWriter_GetData(writer: *mut PyBytesWriter) -> *mut std::ffi::c_void { + pub unsafe fn PyBytesWriter_GetData(writer: *mut PyBytesWriter) -> *mut core::ffi::c_void { if (*writer).obj.is_null() { (*writer).small_buffer.as_ptr() as *mut _ } else { @@ -114,7 +114,7 @@ compat_function!( originally_defined_for(all(Py_3_15, not(Py_LIMITED_API))); #[inline] - pub unsafe fn PyBytesWriter_Resize(writer: *mut PyBytesWriter, size: crate::Py_ssize_t) -> std::ffi::c_int { + pub unsafe fn PyBytesWriter_Resize(writer: *mut PyBytesWriter, size: crate::Py_ssize_t) -> core::ffi::c_int { if size < 0 { crate::PyErr_SetString(crate::PyExc_ValueError, c"size must be >= 0".as_ptr()); return -1; @@ -130,7 +130,7 @@ compat_function!( #[repr(C)] #[cfg(not(any(Py_3_15, Py_LIMITED_API)))] pub struct PyBytesWriter { - small_buffer: [std::ffi::c_char; 256], + small_buffer: [core::ffi::c_char; 256], obj: *mut crate::PyObject, size: crate::Py_ssize_t, } @@ -140,13 +140,13 @@ pub struct PyBytesWriter { unsafe fn _PyBytesWriter_Resize_impl( writer: *mut PyBytesWriter, mut size: crate::Py_ssize_t, - resize: std::ffi::c_int, -) -> std::ffi::c_int { + resize: core::ffi::c_int, +) -> core::ffi::c_int { let overallocate = resize; assert!(size >= 0); let allocated = if (*writer).obj.is_null() { - std::mem::size_of_val(&(*writer).small_buffer) as _ + core::mem::size_of_val(&(*writer).small_buffer) as _ } else { crate::PyBytes_Size((*writer).obj) }; @@ -173,18 +173,18 @@ unsafe fn _PyBytesWriter_Resize_impl( } assert!(!(*writer).obj.is_null()) } else { - (*writer).obj = crate::PyBytes_FromStringAndSize(std::ptr::null_mut(), size); + (*writer).obj = crate::PyBytes_FromStringAndSize(core::ptr::null_mut(), size); if (*writer).obj.is_null() { return -1; } if resize > 0 { - assert!((size as usize) > std::mem::size_of_val(&(*writer).small_buffer)); + assert!((size as usize) > core::mem::size_of_val(&(*writer).small_buffer)); - std::ptr::copy_nonoverlapping( + core::ptr::copy_nonoverlapping( (*writer).small_buffer.as_ptr(), crate::PyBytes_AS_STRING((*writer).obj) as *mut _, - std::mem::size_of_val(&(*writer).small_buffer), + core::mem::size_of_val(&(*writer).small_buffer), ); } } diff --git a/pyo3-ffi/src/compat/py_3_9.rs b/pyo3-ffi/src/compat/py_3_9.rs index 6b3521cc167..fed7e21aaa5 100644 --- a/pyo3-ffi/src/compat/py_3_9.rs +++ b/pyo3-ffi/src/compat/py_3_9.rs @@ -6,7 +6,7 @@ compat_function!( #[inline] pub unsafe fn PyObject_CallNoArgs(obj: *mut crate::PyObject) -> *mut crate::PyObject { - crate::PyObject_CallObject(obj, std::ptr::null_mut()) + crate::PyObject_CallObject(obj, core::ptr::null_mut()) } ); @@ -15,6 +15,6 @@ compat_function!( #[inline] pub unsafe fn PyObject_CallMethodNoArgs(obj: *mut crate::PyObject, name: *mut crate::PyObject) -> *mut crate::PyObject { - crate::PyObject_CallMethodObjArgs(obj, name, std::ptr::null_mut::()) + crate::PyObject_CallMethodObjArgs(obj, name, core::ptr::null_mut::()) } ); diff --git a/pyo3-ffi/src/compile.rs b/pyo3-ffi/src/compile.rs index 50128a815d0..9c7ce0f3ce6 100644 --- a/pyo3-ffi/src/compile.rs +++ b/pyo3-ffi/src/compile.rs @@ -1,4 +1,4 @@ -use std::ffi::c_int; +use core::ffi::c_int; pub const Py_single_input: c_int = 256; pub const Py_file_input: c_int = 257; diff --git a/pyo3-ffi/src/complexobject.rs b/pyo3-ffi/src/complexobject.rs index a8920765424..c737dc2f817 100644 --- a/pyo3-ffi/src/complexobject.rs +++ b/pyo3-ffi/src/complexobject.rs @@ -1,6 +1,6 @@ use crate::object::*; -use std::ffi::{c_double, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_double, c_int}; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/context.rs b/pyo3-ffi/src/context.rs index 8f2f1576bb1..698b6f7c3c0 100644 --- a/pyo3-ffi/src/context.rs +++ b/pyo3-ffi/src/context.rs @@ -1,6 +1,6 @@ use crate::object::{PyObject, PyTypeObject, Py_TYPE}; -use std::ffi::{c_char, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int}; +use core::ptr::addr_of_mut; extern "C" { pub static mut PyContext_Type: PyTypeObject; diff --git a/pyo3-ffi/src/cpython/abstract_.rs b/pyo3-ffi/src/cpython/abstract_.rs index 53ef71e0710..923f855c83e 100644 --- a/pyo3-ffi/src/cpython/abstract_.rs +++ b/pyo3-ffi/src/cpython/abstract_.rs @@ -1,7 +1,7 @@ use crate::{PyObject, Py_ssize_t}; #[cfg(any(all(Py_3_8, not(PyPy)), not(Py_3_11)))] -use std::ffi::c_char; -use std::ffi::c_int; +use core::ffi::c_char; +use core::ffi::c_int; #[cfg(not(Py_3_11))] use crate::Py_buffer; @@ -43,7 +43,7 @@ extern "C" { #[cfg(Py_3_8)] // NB exported as public in abstract.rs from 3.12 const PY_VECTORCALL_ARGUMENTS_OFFSET: size_t = - 1 << (8 * std::mem::size_of::() as size_t - 1); + 1 << (8 * core::mem::size_of::() as size_t - 1); #[cfg(Py_3_8)] #[inline(always)] @@ -86,7 +86,7 @@ pub unsafe fn _PyObject_VectorcallTstate( } Some(func) => { let res = func(callable, args, nargsf, kwnames); - _Py_CheckFunctionResult(tstate, callable, res, std::ptr::null_mut()) + _Py_CheckFunctionResult(tstate, callable, res, core::ptr::null_mut()) } } } @@ -135,7 +135,7 @@ pub unsafe fn _PyObject_FastCallTstate( args: *const *mut PyObject, nargs: Py_ssize_t, ) -> *mut PyObject { - _PyObject_VectorcallTstate(tstate, func, args, nargs as size_t, std::ptr::null_mut()) + _PyObject_VectorcallTstate(tstate, func, args, nargs as size_t, core::ptr::null_mut()) } #[cfg(all(Py_3_8, not(any(PyPy, GraalPy))))] @@ -154,9 +154,9 @@ pub unsafe fn _PyObject_CallNoArg(func: *mut PyObject) -> *mut PyObject { _PyObject_VectorcallTstate( PyThreadState_GET(), func, - std::ptr::null_mut(), + core::ptr::null_mut(), 0, - std::ptr::null_mut(), + core::ptr::null_mut(), ) } @@ -170,11 +170,11 @@ extern "C" { #[inline(always)] pub unsafe fn PyObject_CallOneArg(func: *mut PyObject, arg: *mut PyObject) -> *mut PyObject { assert!(!arg.is_null()); - let args_array = [std::ptr::null_mut(), arg]; + let args_array = [core::ptr::null_mut(), arg]; let args = args_array.as_ptr().offset(1); // For PY_VECTORCALL_ARGUMENTS_OFFSET let tstate = PyThreadState_GET(); let nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET; - _PyObject_VectorcallTstate(tstate, func, args, nargsf, std::ptr::null_mut()) + _PyObject_VectorcallTstate(tstate, func, args, nargsf, core::ptr::null_mut()) } #[cfg(all(Py_3_9, not(PyPy)))] @@ -187,7 +187,7 @@ pub unsafe fn PyObject_CallMethodNoArgs( name, &self_, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) } @@ -204,7 +204,7 @@ pub unsafe fn PyObject_CallMethodOneArg( name, args.as_ptr(), 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) } @@ -238,12 +238,12 @@ extern "C" { pub fn PyBuffer_GetPointer( view: *mut Py_buffer, indices: *mut Py_ssize_t, - ) -> *mut std::ffi::c_void; + ) -> *mut core::ffi::c_void; #[cfg_attr(PyPy, link_name = "PyPyBuffer_SizeFromFormat")] pub fn PyBuffer_SizeFromFormat(format: *const c_char) -> Py_ssize_t; #[cfg_attr(PyPy, link_name = "PyPyBuffer_ToContiguous")] pub fn PyBuffer_ToContiguous( - buf: *mut std::ffi::c_void, + buf: *mut core::ffi::c_void, view: *mut Py_buffer, len: Py_ssize_t, order: c_char, @@ -251,7 +251,7 @@ extern "C" { #[cfg_attr(PyPy, link_name = "PyPyBuffer_FromContiguous")] pub fn PyBuffer_FromContiguous( view: *mut Py_buffer, - buf: *mut std::ffi::c_void, + buf: *mut core::ffi::c_void, len: Py_ssize_t, order: c_char, ) -> c_int; @@ -269,7 +269,7 @@ extern "C" { pub fn PyBuffer_FillInfo( view: *mut Py_buffer, o: *mut PyObject, - buf: *mut std::ffi::c_void, + buf: *mut core::ffi::c_void, len: Py_ssize_t, readonly: c_int, flags: c_int, diff --git a/pyo3-ffi/src/cpython/bytesobject.rs b/pyo3-ffi/src/cpython/bytesobject.rs index e9510c2d77a..fa8ff742e78 100644 --- a/pyo3-ffi/src/cpython/bytesobject.rs +++ b/pyo3-ffi/src/cpython/bytesobject.rs @@ -1,10 +1,10 @@ use crate::object::*; use crate::Py_ssize_t; #[cfg(not(Py_LIMITED_API))] -use std::ffi::c_char; -use std::ffi::c_int; +use core::ffi::c_char; +use core::ffi::c_int; #[cfg(Py_3_15)] -use std::ffi::c_void; +use core::ffi::c_void; #[cfg(not(any(PyPy, GraalPy, Py_LIMITED_API)))] #[repr(C)] diff --git a/pyo3-ffi/src/cpython/ceval.rs b/pyo3-ffi/src/cpython/ceval.rs index cbec47195ec..e27c98ac527 100644 --- a/pyo3-ffi/src/cpython/ceval.rs +++ b/pyo3-ffi/src/cpython/ceval.rs @@ -1,6 +1,6 @@ use crate::cpython::pystate::Py_tracefunc; use crate::object::{freefunc, PyObject}; -use std::ffi::c_int; +use core::ffi::c_int; extern "C" { // skipped non-limited _PyEval_CallTracing diff --git a/pyo3-ffi/src/cpython/code.rs b/pyo3-ffi/src/cpython/code.rs index 3be303fb38a..fbe895c694d 100644 --- a/pyo3-ffi/src/cpython/code.rs +++ b/pyo3-ffi/src/cpython/code.rs @@ -4,10 +4,10 @@ use crate::pyport::Py_ssize_t; #[cfg(not(GraalPy))] use crate::PyCodeObject; #[cfg(not(GraalPy))] -use std::ffi::c_char; -use std::ffi::{c_int, c_void}; +use core::ffi::c_char; +use core::ffi::{c_int, c_void}; #[cfg(not(PyPy))] -use std::ptr::addr_of_mut; +use core::ptr::addr_of_mut; // skipped private _PY_MONITORING_LOCAL_EVENTS // skipped private _PY_MONITORING_UNGROUPED_EVENTS diff --git a/pyo3-ffi/src/cpython/compile.rs b/pyo3-ffi/src/cpython/compile.rs index df0b982b147..4257d1525dd 100644 --- a/pyo3-ffi/src/cpython/compile.rs +++ b/pyo3-ffi/src/cpython/compile.rs @@ -8,8 +8,8 @@ use crate::pythonrun::*; use crate::PyCodeObject; use crate::INT_MAX; #[cfg(not(any(PyPy, Py_3_10)))] -use std::ffi::c_char; -use std::ffi::c_int; +use core::ffi::c_char; +use core::ffi::c_int; // skipped PyCF_MASK // skipped PyCF_MASK_OBSOLETE diff --git a/pyo3-ffi/src/cpython/complexobject.rs b/pyo3-ffi/src/cpython/complexobject.rs index 3283fc4e52f..1b9afd3c5a3 100644 --- a/pyo3-ffi/src/cpython/complexobject.rs +++ b/pyo3-ffi/src/cpython/complexobject.rs @@ -1,5 +1,5 @@ use crate::PyObject; -use std::ffi::c_double; +use core::ffi::c_double; #[repr(C)] #[derive(Copy, Clone)] diff --git a/pyo3-ffi/src/cpython/descrobject.rs b/pyo3-ffi/src/cpython/descrobject.rs index 88e952f2c53..f18923e7ef9 100644 --- a/pyo3-ffi/src/cpython/descrobject.rs +++ b/pyo3-ffi/src/cpython/descrobject.rs @@ -1,5 +1,5 @@ use crate::{PyGetSetDef, PyMethodDef, PyObject, PyTypeObject}; -use std::ffi::{c_char, c_int, c_void}; +use core::ffi::{c_char, c_int, c_void}; #[cfg(Py_3_11)] use crate::PyMemberDef; diff --git a/pyo3-ffi/src/cpython/floatobject.rs b/pyo3-ffi/src/cpython/floatobject.rs index 4b9ef1a2484..e3ff9a3371f 100644 --- a/pyo3-ffi/src/cpython/floatobject.rs +++ b/pyo3-ffi/src/cpython/floatobject.rs @@ -1,7 +1,7 @@ #[cfg(GraalPy)] use crate::PyFloat_AsDouble; use crate::{PyFloat_Check, PyObject}; -use std::ffi::c_double; +use core::ffi::c_double; #[repr(C)] pub struct PyFloatObject { diff --git a/pyo3-ffi/src/cpython/frameobject.rs b/pyo3-ffi/src/cpython/frameobject.rs index a7714fa1fd7..ffac2465767 100644 --- a/pyo3-ffi/src/cpython/frameobject.rs +++ b/pyo3-ffi/src/cpython/frameobject.rs @@ -6,8 +6,8 @@ use crate::PyFrameObject; #[cfg(not(GraalPy))] use crate::PyThreadState; #[cfg(not(any(PyPy, GraalPy, Py_3_11)))] -use std::ffi::c_char; -use std::ffi::c_int; +use core::ffi::c_char; +use core::ffi::c_int; #[cfg(not(any(PyPy, GraalPy, Py_3_11)))] pub type PyFrameState = c_char; diff --git a/pyo3-ffi/src/cpython/funcobject.rs b/pyo3-ffi/src/cpython/funcobject.rs index 7a242e85abd..688a7330e59 100644 --- a/pyo3-ffi/src/cpython/funcobject.rs +++ b/pyo3-ffi/src/cpython/funcobject.rs @@ -1,6 +1,6 @@ -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(not(all(PyPy, not(Py_3_8))))] -use std::ptr::addr_of_mut; +use core::ptr::addr_of_mut; use crate::PyObject; diff --git a/pyo3-ffi/src/cpython/genobject.rs b/pyo3-ffi/src/cpython/genobject.rs index cc2893cd453..750ba358409 100644 --- a/pyo3-ffi/src/cpython/genobject.rs +++ b/pyo3-ffi/src/cpython/genobject.rs @@ -1,9 +1,9 @@ use crate::object::*; use crate::PyFrameObject; #[cfg(all(Py_3_11, not(any(PyPy, GraalPy, Py_3_14))))] -use std::ffi::c_char; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_char; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg(not(any(PyPy, GraalPy, Py_3_14)))] #[repr(C)] diff --git a/pyo3-ffi/src/cpython/import.rs b/pyo3-ffi/src/cpython/import.rs index 762c5488e9c..d557a7a19e4 100644 --- a/pyo3-ffi/src/cpython/import.rs +++ b/pyo3-ffi/src/cpython/import.rs @@ -1,9 +1,9 @@ #[cfg(any(not(PyPy), Py_3_14))] use crate::PyObject; #[cfg(any(not(PyPy), Py_3_14))] -use std::ffi::c_char; +use core::ffi::c_char; #[cfg(not(PyPy))] -use std::ffi::{c_int, c_uchar}; +use core::ffi::{c_int, c_uchar}; #[cfg(not(PyPy))] #[repr(C)] diff --git a/pyo3-ffi/src/cpython/initconfig.rs b/pyo3-ffi/src/cpython/initconfig.rs index 6b0ae2e5dec..bab77bc0e8b 100644 --- a/pyo3-ffi/src/cpython/initconfig.rs +++ b/pyo3-ffi/src/cpython/initconfig.rs @@ -1,8 +1,8 @@ /* --- PyStatus ----------------------------------------------- */ use crate::Py_ssize_t; +use core::ffi::{c_char, c_int, c_ulong}; use libc::wchar_t; -use std::ffi::{c_char, c_int, c_ulong}; #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] diff --git a/pyo3-ffi/src/cpython/lock.rs b/pyo3-ffi/src/cpython/lock.rs index 487173f9afb..ba616a01d63 100644 --- a/pyo3-ffi/src/cpython/lock.rs +++ b/pyo3-ffi/src/cpython/lock.rs @@ -1,6 +1,6 @@ #[cfg(Py_3_14)] -use std::os::raw::c_int; -use std::sync::atomic::AtomicU8; +use core::ffi::c_int; +use core::sync::atomic::AtomicU8; #[repr(transparent)] #[derive(Debug)] diff --git a/pyo3-ffi/src/cpython/longobject.rs b/pyo3-ffi/src/cpython/longobject.rs index a778d8c26d2..5babf375b55 100644 --- a/pyo3-ffi/src/cpython/longobject.rs +++ b/pyo3-ffi/src/cpython/longobject.rs @@ -2,10 +2,10 @@ use crate::longobject::*; use crate::object::*; #[cfg(Py_3_13)] use crate::pyport::Py_ssize_t; -use libc::size_t; #[cfg(Py_3_13)] -use std::ffi::c_void; -use std::ffi::{c_int, c_uchar}; +use core::ffi::c_void; +use core::ffi::{c_int, c_uchar}; +use libc::size_t; #[cfg(Py_3_13)] extern "C" { diff --git a/pyo3-ffi/src/cpython/methodobject.rs b/pyo3-ffi/src/cpython/methodobject.rs index 096bb02ae13..027fb27227c 100644 --- a/pyo3-ffi/src/cpython/methodobject.rs +++ b/pyo3-ffi/src/cpython/methodobject.rs @@ -1,8 +1,8 @@ use crate::object::*; #[cfg(not(GraalPy))] use crate::{PyCFunctionObject, PyMethodDefPointer, METH_METHOD, METH_STATIC}; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg(not(GraalPy))] pub struct PyCMethodObject { @@ -41,7 +41,7 @@ pub unsafe fn PyCFunction_GET_SELF(func: *mut PyObject) -> *mut PyObject { let func = func.cast::(); if (*(*func).m_ml).ml_flags & METH_STATIC != 0 { - std::ptr::null_mut() + core::ptr::null_mut() } else { (*func).m_self } @@ -66,6 +66,6 @@ pub unsafe fn PyCFunction_GET_CLASS(func: *mut PyObject) -> *mut PyTypeObject { let func = func.cast::(); (*func).mm_class } else { - std::ptr::null_mut() + core::ptr::null_mut() } } diff --git a/pyo3-ffi/src/cpython/object.rs b/pyo3-ffi/src/cpython/object.rs index 488347f877a..61fbb1872e0 100644 --- a/pyo3-ffi/src/cpython/object.rs +++ b/pyo3-ffi/src/cpython/object.rs @@ -1,8 +1,8 @@ #[cfg(Py_3_8)] use crate::vectorcallfunc; use crate::{object, PyGetSetDef, PyMemberDef, PyMethodDef, PyObject, Py_ssize_t}; -use std::ffi::{c_char, c_int, c_uint, c_void}; -use std::mem; +use core::ffi::{c_char, c_int, c_uint, c_void}; +use core::mem; // skipped private _Py_NewReference // skipped private _Py_NewReferenceNoTotal @@ -22,8 +22,8 @@ use std::mem; #[cfg(not(Py_3_11))] // moved to src/buffer.rs from Python mod bufferinfo { use crate::Py_ssize_t; - use std::ffi::{c_char, c_int, c_void}; - use std::ptr; + use core::ffi::{c_char, c_int, c_void}; + use core::ptr; #[repr(C)] #[derive(Copy, Clone)] @@ -233,7 +233,7 @@ pub struct PyTypeObject { pub tp_setattro: Option, pub tp_as_buffer: *mut PyBufferProcs, #[cfg(not(Py_GIL_DISABLED))] - pub tp_flags: std::ffi::c_ulong, + pub tp_flags: core::ffi::c_ulong, #[cfg(Py_GIL_DISABLED)] pub tp_flags: crate::impl_::AtomicCULong, pub tp_doc: *const c_char, diff --git a/pyo3-ffi/src/cpython/objimpl.rs b/pyo3-ffi/src/cpython/objimpl.rs index 71087d28d2c..214e16fbf79 100644 --- a/pyo3-ffi/src/cpython/objimpl.rs +++ b/pyo3-ffi/src/cpython/objimpl.rs @@ -1,9 +1,9 @@ +use core::ffi::c_int; #[cfg(not(all(Py_3_11, any(PyPy, GraalPy))))] use libc::size_t; -use std::ffi::c_int; #[cfg(not(any(PyPy, GraalPy)))] -use std::ffi::c_void; +use core::ffi::c_void; use crate::object::*; @@ -28,7 +28,7 @@ pub struct PyObjectArenaAllocator { impl Default for PyObjectArenaAllocator { #[inline] fn default() -> Self { - unsafe { std::mem::zeroed() } + unsafe { core::mem::zeroed() } } } diff --git a/pyo3-ffi/src/cpython/pydebug.rs b/pyo3-ffi/src/cpython/pydebug.rs index 6878554aead..67b6cfc0057 100644 --- a/pyo3-ffi/src/cpython/pydebug.rs +++ b/pyo3-ffi/src/cpython/pydebug.rs @@ -1,4 +1,4 @@ -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; #[cfg(not(Py_LIMITED_API))] #[cfg_attr(windows, link(name = "pythonXY"))] @@ -65,7 +65,7 @@ extern "C" { pub unsafe fn Py_GETENV(name: *const c_char) -> *mut c_char { #[allow(deprecated)] if Py_IgnoreEnvironmentFlag != 0 { - std::ptr::null_mut() + core::ptr::null_mut() } else { libc::getenv(name) } diff --git a/pyo3-ffi/src/cpython/pyframe.rs b/pyo3-ffi/src/cpython/pyframe.rs index 6da9ecd5b53..81ea7f81e79 100644 --- a/pyo3-ffi/src/cpython/pyframe.rs +++ b/pyo3-ffi/src/cpython/pyframe.rs @@ -2,9 +2,9 @@ use crate::PyFrameObject; use crate::{PyObject, PyTypeObject, Py_TYPE}; #[cfg(Py_3_12)] -use std::ffi::c_char; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_char; +use core::ffi::c_int; +use core::ptr::addr_of_mut; // NB used in `_PyEval_EvalFrameDefault`, maybe we remove this too. #[cfg(all(Py_3_11, not(PyPy)))] diff --git a/pyo3-ffi/src/cpython/pyhash.rs b/pyo3-ffi/src/cpython/pyhash.rs index f5c98c23256..bda285784c3 100644 --- a/pyo3-ffi/src/cpython/pyhash.rs +++ b/pyo3-ffi/src/cpython/pyhash.rs @@ -3,9 +3,9 @@ use crate::Py_ssize_t; #[cfg(Py_3_13)] use crate::{PyObject, Py_hash_t}; #[cfg(any(Py_3_13, not(PyPy)))] -use std::ffi::c_void; +use core::ffi::c_void; #[cfg(not(PyPy))] -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; #[cfg(not(PyPy))] #[repr(C)] @@ -22,7 +22,7 @@ pub struct PyHash_FuncDef { impl Default for PyHash_FuncDef { #[inline] fn default() -> Self { - unsafe { std::mem::zeroed() } + unsafe { core::mem::zeroed() } } } diff --git a/pyo3-ffi/src/cpython/pylifecycle.rs b/pyo3-ffi/src/cpython/pylifecycle.rs index 975dbce1915..037210b0112 100644 --- a/pyo3-ffi/src/cpython/pylifecycle.rs +++ b/pyo3-ffi/src/cpython/pylifecycle.rs @@ -1,6 +1,6 @@ use crate::{PyConfig, PyPreConfig, PyStatus, Py_ssize_t}; +use core::ffi::{c_char, c_int}; use libc::wchar_t; -use std::ffi::{c_char, c_int}; extern "C" { diff --git a/pyo3-ffi/src/cpython/pymem.rs b/pyo3-ffi/src/cpython/pymem.rs index 762e850820f..4916ea65790 100644 --- a/pyo3-ffi/src/cpython/pymem.rs +++ b/pyo3-ffi/src/cpython/pymem.rs @@ -1,5 +1,5 @@ +use core::ffi::c_void; use libc::size_t; -use std::ffi::c_void; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyMem_RawMalloc")] diff --git a/pyo3-ffi/src/cpython/pystate.rs b/pyo3-ffi/src/cpython/pystate.rs index 1849d9a38fe..bc0e8e2f13f 100644 --- a/pyo3-ffi/src/cpython/pystate.rs +++ b/pyo3-ffi/src/cpython/pystate.rs @@ -1,6 +1,6 @@ use crate::PyThreadState; use crate::{PyFrameObject, PyInterpreterState, PyObject}; -use std::ffi::c_int; +use core::ffi::c_int; // skipped private _PyInterpreterState_RequiresIDRef // skipped private _PyInterpreterState_RequireIDRef diff --git a/pyo3-ffi/src/cpython/pythonrun.rs b/pyo3-ffi/src/cpython/pythonrun.rs index db3767cb60c..7ff529501cc 100644 --- a/pyo3-ffi/src/cpython/pythonrun.rs +++ b/pyo3-ffi/src/cpython/pythonrun.rs @@ -4,8 +4,8 @@ use crate::pyarena::PyArena; use crate::PyCompilerFlags; #[cfg(not(any(PyPy, GraalPy, Py_3_10)))] use crate::{_mod, _node}; +use core::ffi::{c_char, c_int}; use libc::FILE; -use std::ffi::{c_char, c_int}; extern "C" { pub fn PyRun_SimpleStringFlags(arg1: *const c_char, arg2: *mut PyCompilerFlags) -> c_int; @@ -137,7 +137,7 @@ extern "C" { #[inline] #[cfg(not(any(PyPy, GraalPy)))] pub unsafe fn Py_CompileString(string: *const c_char, p: *const c_char, s: c_int) -> *mut PyObject { - Py_CompileStringExFlags(string, p, s, std::ptr::null_mut(), -1) + Py_CompileStringExFlags(string, p, s, core::ptr::null_mut(), -1) } #[inline] diff --git a/pyo3-ffi/src/cpython/unicodeobject.rs b/pyo3-ffi/src/cpython/unicodeobject.rs index ae1a9074883..47d255ca484 100644 --- a/pyo3-ffi/src/cpython/unicodeobject.rs +++ b/pyo3-ffi/src/cpython/unicodeobject.rs @@ -1,8 +1,8 @@ #[cfg(any(Py_3_11, not(PyPy)))] use crate::Py_hash_t; use crate::{PyObject, Py_UCS1, Py_UCS2, Py_UCS4, Py_ssize_t}; +use core::ffi::{c_char, c_int, c_uint, c_void}; use libc::wchar_t; -use std::ffi::{c_char, c_int, c_uint, c_void}; // skipped Py_UNICODE_ISSPACE() // skipped Py_UNICODE_ISLOWER() @@ -174,7 +174,7 @@ struct PyASCIIObjectState { impl PyASCIIObjectState { #[inline] unsafe fn interned(&self) -> c_uint { - std::mem::transmute( + core::mem::transmute( self.bitfield .get(STATE_INTERNED_INDEX, STATE_INTERNED_WIDTH) as u32, ) @@ -182,43 +182,43 @@ impl PyASCIIObjectState { #[inline] unsafe fn set_interned(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield .set(STATE_INTERNED_INDEX, STATE_INTERNED_WIDTH, val as u64) } #[inline] unsafe fn kind(&self) -> c_uint { - std::mem::transmute(self.bitfield.get(STATE_KIND_INDEX, STATE_KIND_WIDTH) as u32) + core::mem::transmute(self.bitfield.get(STATE_KIND_INDEX, STATE_KIND_WIDTH) as u32) } #[inline] unsafe fn set_kind(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield .set(STATE_KIND_INDEX, STATE_KIND_WIDTH, val as u64) } #[inline] unsafe fn compact(&self) -> c_uint { - std::mem::transmute(self.bitfield.get(STATE_COMPACT_INDEX, STATE_COMPACT_WIDTH) as u32) + core::mem::transmute(self.bitfield.get(STATE_COMPACT_INDEX, STATE_COMPACT_WIDTH) as u32) } #[inline] unsafe fn set_compact(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield .set(STATE_COMPACT_INDEX, STATE_COMPACT_WIDTH, val as u64) } #[inline] unsafe fn ascii(&self) -> c_uint { - std::mem::transmute(self.bitfield.get(STATE_ASCII_INDEX, STATE_ASCII_WIDTH) as u32) + core::mem::transmute(self.bitfield.get(STATE_ASCII_INDEX, STATE_ASCII_WIDTH) as u32) } #[inline] unsafe fn set_ascii(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield .set(STATE_ASCII_INDEX, STATE_ASCII_WIDTH, val as u64) } @@ -226,7 +226,7 @@ impl PyASCIIObjectState { #[cfg(Py_3_12)] #[inline] unsafe fn statically_allocated(&self) -> c_uint { - std::mem::transmute(self.bitfield.get( + core::mem::transmute(self.bitfield.get( STATE_STATICALLY_ALLOCATED_INDEX, STATE_STATICALLY_ALLOCATED_WIDTH, ) as u32) @@ -235,7 +235,7 @@ impl PyASCIIObjectState { #[cfg(Py_3_12)] #[inline] unsafe fn set_statically_allocated(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield.set( STATE_STATICALLY_ALLOCATED_INDEX, STATE_STATICALLY_ALLOCATED_WIDTH, @@ -246,13 +246,13 @@ impl PyASCIIObjectState { #[cfg(not(Py_3_12))] #[inline] unsafe fn ready(&self) -> c_uint { - std::mem::transmute(self.bitfield.get(STATE_READY_INDEX, STATE_READY_WIDTH) as u32) + core::mem::transmute(self.bitfield.get(STATE_READY_INDEX, STATE_READY_WIDTH) as u32) } #[cfg(not(Py_3_12))] #[inline] unsafe fn set_ready(&mut self, val: c_uint) { - let val: u32 = std::mem::transmute(val); + let val: u32 = core::mem::transmute(val); self.bitfield .set(STATE_READY_INDEX, STATE_READY_WIDTH, val as u64) } diff --git a/pyo3-ffi/src/datetime.rs b/pyo3-ffi/src/datetime.rs index dc3a8b32dec..14464677223 100644 --- a/pyo3-ffi/src/datetime.rs +++ b/pyo3-ffi/src/datetime.rs @@ -9,13 +9,13 @@ use crate::PyCapsule_Import; #[cfg(GraalPy)] use crate::{PyLong_AsLong, PyLong_Check, PyObject_GetAttrString, Py_DecRef}; use crate::{PyObject, PyObject_TypeCheck, PyTypeObject, Py_TYPE}; -use std::ffi::c_char; -use std::ffi::c_int; -use std::ptr; +use core::ffi::c_char; +use core::ffi::c_int; +use core::ptr; +use core::{cell::UnsafeCell, ffi::CStr}; use std::sync::Once; -use std::{cell::UnsafeCell, ffi::CStr}; #[cfg(not(PyPy))] -use {crate::Py_hash_t, std::ffi::c_uchar}; +use {crate::Py_hash_t, core::ffi::c_uchar}; // Type struct wrappers const _PyDateTime_DATE_DATASIZE: usize = 4; const _PyDateTime_TIME_DATASIZE: usize = 6; @@ -345,7 +345,7 @@ pub unsafe fn PyDateTime_DELTA_GET_MICROSECONDS(o: *mut PyObject) -> c_int { // but copying them seems suboptimal #[inline] #[cfg(GraalPy)] -pub unsafe fn _get_attr(obj: *mut PyObject, field: &std::ffi::CStr) -> c_int { +pub unsafe fn _get_attr(obj: *mut PyObject, field: &core::ffi::CStr) -> c_int { let result = PyObject_GetAttrString(obj, field.as_ptr()); Py_DecRef(result); // the original macros are borrowing if PyLong_Check(result) == 1 { @@ -705,7 +705,7 @@ pub unsafe fn PyTZInfo_CheckExact(op: *mut PyObject) -> c_int { // skipped non-limited PyDelta_FromDSU pub unsafe fn PyTimeZone_FromOffset(offset: *mut PyObject) -> *mut PyObject { - ((*PyDateTimeAPI()).TimeZone_FromTimeZone)(offset, std::ptr::null_mut()) + ((*PyDateTimeAPI()).TimeZone_FromTimeZone)(offset, core::ptr::null_mut()) } pub unsafe fn PyTimeZone_FromOffsetAndName( @@ -718,7 +718,7 @@ pub unsafe fn PyTimeZone_FromOffsetAndName( #[cfg(not(PyPy))] pub unsafe fn PyDateTime_FromTimestamp(args: *mut PyObject) -> *mut PyObject { let f = (*PyDateTimeAPI()).DateTime_FromTimestamp; - f((*PyDateTimeAPI()).DateTimeType, args, std::ptr::null_mut()) + f((*PyDateTimeAPI()).DateTimeType, args, core::ptr::null_mut()) } #[cfg(not(PyPy))] diff --git a/pyo3-ffi/src/descrobject.rs b/pyo3-ffi/src/descrobject.rs index 8a4d5839a37..3cc5cb75ff2 100644 --- a/pyo3-ffi/src/descrobject.rs +++ b/pyo3-ffi/src/descrobject.rs @@ -1,8 +1,8 @@ use crate::methodobject::PyMethodDef; use crate::object::{PyObject, PyTypeObject}; use crate::Py_ssize_t; -use std::ffi::{c_char, c_int, c_void}; -use std::ptr; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr; pub type getter = unsafe extern "C" fn(slf: *mut PyObject, closure: *mut c_void) -> *mut PyObject; pub type setter = diff --git a/pyo3-ffi/src/dictobject.rs b/pyo3-ffi/src/dictobject.rs index daec89cd754..b19328265e2 100644 --- a/pyo3-ffi/src/dictobject.rs +++ b/pyo3-ffi/src/dictobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int}; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/fileobject.rs b/pyo3-ffi/src/fileobject.rs index ec3a0409930..9d59d6b23ef 100644 --- a/pyo3-ffi/src/fileobject.rs +++ b/pyo3-ffi/src/fileobject.rs @@ -1,5 +1,5 @@ use crate::object::PyObject; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; pub const PY_STDIOTEXTMODE: &str = "b"; diff --git a/pyo3-ffi/src/fileutils.rs b/pyo3-ffi/src/fileutils.rs index 649751babf5..12018bbea41 100644 --- a/pyo3-ffi/src/fileutils.rs +++ b/pyo3-ffi/src/fileutils.rs @@ -1,6 +1,6 @@ use crate::pyport::Py_ssize_t; +use core::ffi::c_char; use libc::wchar_t; -use std::ffi::c_char; extern "C" { pub fn Py_DecodeLocale(arg1: *const c_char, size: *mut Py_ssize_t) -> *mut wchar_t; diff --git a/pyo3-ffi/src/floatobject.rs b/pyo3-ffi/src/floatobject.rs index 18bbc8bece0..f4da3f92ca1 100644 --- a/pyo3-ffi/src/floatobject.rs +++ b/pyo3-ffi/src/floatobject.rs @@ -1,6 +1,6 @@ use crate::object::*; -use std::ffi::{c_double, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_double, c_int}; +use core::ptr::addr_of_mut; #[cfg(Py_LIMITED_API)] // TODO: remove (see https://github.com/PyO3/pyo3/pull/1341#issuecomment-751515985) diff --git a/pyo3-ffi/src/impl_/mod.rs b/pyo3-ffi/src/impl_/mod.rs index 064df213ba6..df759d25207 100644 --- a/pyo3-ffi/src/impl_/mod.rs +++ b/pyo3-ffi/src/impl_/mod.rs @@ -6,14 +6,14 @@ mod atomic_c_ulong { type Type; } impl AtomicCULongType for GetAtomicCULong<32> { - type Type = std::sync::atomic::AtomicU32; + type Type = core::sync::atomic::AtomicU32; } impl AtomicCULongType for GetAtomicCULong<64> { - type Type = std::sync::atomic::AtomicU64; + type Type = core::sync::atomic::AtomicU64; } pub type TYPE = - () * 8 }> as AtomicCULongType>::Type; + () * 8 }> as AtomicCULongType>::Type; } /// Typedef for an atomic integer to match the platform-dependent c_ulong type. diff --git a/pyo3-ffi/src/import.rs b/pyo3-ffi/src/import.rs index 8ddb70218ec..5784deca7ad 100644 --- a/pyo3-ffi/src/import.rs +++ b/pyo3-ffi/src/import.rs @@ -1,5 +1,5 @@ use crate::object::PyObject; -use std::ffi::{c_char, c_int, c_long}; +use core::ffi::{c_char, c_int, c_long}; extern "C" { pub fn PyImport_GetMagicNumber() -> c_long; diff --git a/pyo3-ffi/src/intrcheck.rs b/pyo3-ffi/src/intrcheck.rs index 05400557d5a..c875ffadeea 100644 --- a/pyo3-ffi/src/intrcheck.rs +++ b/pyo3-ffi/src/intrcheck.rs @@ -1,4 +1,4 @@ -use std::ffi::c_int; +use core::ffi::c_int; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyOS_InterruptOccurred")] diff --git a/pyo3-ffi/src/iterobject.rs b/pyo3-ffi/src/iterobject.rs index 04a28d4826f..81b135867d8 100644 --- a/pyo3-ffi/src/iterobject.rs +++ b/pyo3-ffi/src/iterobject.rs @@ -1,6 +1,6 @@ use crate::object::*; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/lib.rs b/pyo3-ffi/src/lib.rs index 9a3b1db01e1..13c1d711db4 100644 --- a/pyo3-ffi/src/lib.rs +++ b/pyo3-ffi/src/lib.rs @@ -127,9 +127,9 @@ //! **`src/lib.rs`** //! ```rust,no_run //! #[cfg(Py_3_15)] -//! use std::ffi::c_void; -//! use std::ffi::{c_char, c_long}; -//! use std::ptr; +//! use core::ffi::c_void; +//! use core::ffi::{c_char, c_long}; +//! use core::ptr; //! //! use pyo3_ffi::*; //! @@ -139,8 +139,8 @@ //! m_name: c"string_sum".as_ptr(), //! m_doc: c"A Python module written in Rust.".as_ptr(), //! m_size: 0, -//! m_methods: std::ptr::addr_of_mut!(METHODS).cast(), -//! m_slots: std::ptr::addr_of_mut!(SLOTS).cast(), +//! m_methods: core::ptr::addr_of_mut!(METHODS).cast(), +//! m_slots: core::ptr::addr_of_mut!(SLOTS).cast(), //! m_traverse: None, //! m_clear: None, //! m_free: None, @@ -168,7 +168,7 @@ //! #[cfg(Py_3_15)] //! PyModuleDef_Slot { //! slot: Py_mod_abi, -//! value: std::ptr::addr_of_mut!(ABI_INFO).cast(), +//! value: core::ptr::addr_of_mut!(ABI_INFO).cast(), //! }, //! #[cfg(Py_3_15)] //! PyModuleDef_Slot { @@ -185,7 +185,7 @@ //! #[cfg(Py_3_15)] //! PyModuleDef_Slot { //! slot: Py_mod_methods, -//! value: std::ptr::addr_of_mut!(METHODS).cast(), +//! value: core::ptr::addr_of_mut!(METHODS).cast(), //! }, //! #[cfg(Py_3_12)] //! PyModuleDef_Slot { @@ -215,7 +215,7 @@ //! #[allow(non_snake_case, reason = "must be named `PyModExport_`")] //! #[no_mangle] //! pub unsafe extern "C" fn PyModExport_string_sum() -> *mut PyModuleDef_Slot { -//! std::ptr::addr_of_mut!(SLOTS).cast() +//! core::ptr::addr_of_mut!(SLOTS).cast() //! } //! //! /// A helper to parse function arguments @@ -256,7 +256,7 @@ //! let mut size = 0; //! let p = PyUnicode_AsUTF8AndSize(obj_repr, &mut size); //! if !p.is_null() { -//! let s = std::str::from_utf8_unchecked(std::slice::from_raw_parts( +//! let s = core::str::from_utf8_unchecked(core::slice::from_raw_parts( //! p.cast::(), //! size as usize, //! )); @@ -278,18 +278,18 @@ //! PyExc_TypeError, //! c"sum_as_string expected 2 positional arguments".as_ptr(), //! ); -//! return std::ptr::null_mut(); +//! return core::ptr::null_mut(); //! } //! //! let (first, second) = (*args, *args.add(1)); //! //! let first = match parse_arg_as_i32(first, 1) { //! Some(x) => x, -//! None => return std::ptr::null_mut(), +//! None => return core::ptr::null_mut(), //! }; //! let second = match parse_arg_as_i32(second, 2) { //! Some(x) => x, -//! None => return std::ptr::null_mut(), +//! None => return core::ptr::null_mut(), //! }; //! //! match first.checked_add(second) { @@ -299,7 +299,7 @@ //! } //! None => { //! PyErr_SetString(PyExc_OverflowError, c"arguments too large to add".as_ptr()); -//! std::ptr::null_mut() +//! core::ptr::null_mut() //! } //! } //! } @@ -370,6 +370,7 @@ clippy::missing_safety_doc, clippy::ptr_eq )] +#![warn(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] #![warn(elided_lifetimes_in_paths, unused_lifetimes)] // This crate is a hand-maintained translation of CPython's headers, so requiring "unsafe" // blocks within those translations increases maintenance burden without providing any @@ -399,7 +400,7 @@ macro_rules! opaque_struct { /// Examples: /// /// ```rust,no_run -/// use std::ffi::CStr; +/// use core::ffi::CStr; /// /// const HELLO: &CStr = pyo3_ffi::c_str!("hello"); /// static WORLD: &CStr = pyo3_ffi::c_str!("world"); @@ -414,8 +415,8 @@ macro_rules! c_str { /// Private helper for `c_str!` macro. #[doc(hidden)] -pub const fn _cstr_from_utf8_with_nul_checked(s: &str) -> &std::ffi::CStr { - match std::ffi::CStr::from_bytes_with_nul(s.as_bytes()) { +pub const fn _cstr_from_utf8_with_nul_checked(s: &str) -> &core::ffi::CStr { + match core::ffi::CStr::from_bytes_with_nul(s.as_bytes()) { Ok(cstr) => cstr, Err(_) => panic!("string contains nul bytes"), } diff --git a/pyo3-ffi/src/listobject.rs b/pyo3-ffi/src/listobject.rs index 6fd28ff0c99..db25095e7ba 100644 --- a/pyo3-ffi/src/listobject.rs +++ b/pyo3-ffi/src/listobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/longobject.rs b/pyo3-ffi/src/longobject.rs index 6927fcbef5a..1fe3a09bb31 100644 --- a/pyo3-ffi/src/longobject.rs +++ b/pyo3-ffi/src/longobject.rs @@ -1,8 +1,8 @@ use crate::object::*; use crate::pyport::Py_ssize_t; +use core::ffi::{c_char, c_double, c_int, c_long, c_longlong, c_ulong, c_ulonglong, c_void}; +use core::ptr::addr_of_mut; use libc::size_t; -use std::ffi::{c_char, c_double, c_int, c_long, c_longlong, c_ulong, c_ulonglong, c_void}; -use std::ptr::addr_of_mut; opaque_struct!(pub PyLongObject); diff --git a/pyo3-ffi/src/marshal.rs b/pyo3-ffi/src/marshal.rs index bba8f5ece50..fdba0a2f25f 100644 --- a/pyo3-ffi/src/marshal.rs +++ b/pyo3-ffi/src/marshal.rs @@ -1,5 +1,5 @@ use super::{PyObject, Py_ssize_t}; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; // skipped Py_MARSHAL_VERSION // skipped PyMarshal_WriteLongToFile diff --git a/pyo3-ffi/src/memoryobject.rs b/pyo3-ffi/src/memoryobject.rs index 01ceea3bdbe..f484fe1f332 100644 --- a/pyo3-ffi/src/memoryobject.rs +++ b/pyo3-ffi/src/memoryobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int}; +use core::ptr::addr_of_mut; // skipped _PyManagedBuffer_Type diff --git a/pyo3-ffi/src/methodobject.rs b/pyo3-ffi/src/methodobject.rs index 5f367c9bd48..80bb8812afb 100644 --- a/pyo3-ffi/src/methodobject.rs +++ b/pyo3-ffi/src/methodobject.rs @@ -1,8 +1,8 @@ use crate::object::{PyObject, PyTypeObject, Py_TYPE}; #[cfg(Py_3_9)] use crate::PyObject_TypeCheck; -use std::ffi::{c_char, c_int, c_void}; -use std::{mem, ptr}; +use core::ffi::{c_char, c_int, c_void}; +use core::{mem, ptr}; #[cfg(all(Py_3_9, not(Py_LIMITED_API), not(GraalPy)))] pub struct PyCFunctionObject { @@ -198,10 +198,10 @@ impl PartialEq for PyMethodDefPointer { } } -impl std::fmt::Pointer for PyMethodDefPointer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Pointer for PyMethodDefPointer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let ptr = unsafe { self.Void }; - std::fmt::Pointer::fmt(&ptr, f) + core::fmt::Pointer::fmt(&ptr, f) } } @@ -224,7 +224,7 @@ extern "C" { #[cfg(Py_3_9)] #[inline] pub unsafe fn PyCFunction_New(ml: *mut PyMethodDef, slf: *mut PyObject) -> *mut PyObject { - PyCFunction_NewEx(ml, slf, std::ptr::null_mut()) + PyCFunction_NewEx(ml, slf, core::ptr::null_mut()) } #[cfg(Py_3_9)] @@ -234,7 +234,7 @@ pub unsafe fn PyCFunction_NewEx( slf: *mut PyObject, module: *mut PyObject, ) -> *mut PyObject { - PyCMethod_New(ml, slf, module, std::ptr::null_mut()) + PyCMethod_New(ml, slf, module, core::ptr::null_mut()) } #[cfg(Py_3_9)] diff --git a/pyo3-ffi/src/modsupport.rs b/pyo3-ffi/src/modsupport.rs index e3dd1f2ee7c..1718e15dbb2 100644 --- a/pyo3-ffi/src/modsupport.rs +++ b/pyo3-ffi/src/modsupport.rs @@ -2,7 +2,7 @@ use crate::methodobject::PyMethodDef; use crate::moduleobject::PyModuleDef; use crate::object::PyObject; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int, c_long}; +use core::ffi::{c_char, c_int, c_long}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyArg_Parse")] diff --git a/pyo3-ffi/src/moduleobject.rs b/pyo3-ffi/src/moduleobject.rs index ace202d969e..70904d8ed2b 100644 --- a/pyo3-ffi/src/moduleobject.rs +++ b/pyo3-ffi/src/moduleobject.rs @@ -1,8 +1,8 @@ use crate::methodobject::PyMethodDef; use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int, c_void}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { @@ -69,7 +69,7 @@ pub const PyModuleDef_HEAD_INIT: PyModuleDef_Base = PyModuleDef_Base { ob_base: PyObject_HEAD_INIT, m_init: None, m_index: 0, - m_copy: std::ptr::null_mut(), + m_copy: core::ptr::null_mut(), }; #[repr(C)] @@ -83,7 +83,7 @@ impl Default for PyModuleDef_Slot { fn default() -> PyModuleDef_Slot { PyModuleDef_Slot { slot: 0, - value: std::ptr::null_mut(), + value: core::ptr::null_mut(), } } } diff --git a/pyo3-ffi/src/object.rs b/pyo3-ffi/src/object.rs index a6fc6d39ff6..e8e9f4c7e0a 100644 --- a/pyo3-ffi/src/object.rs +++ b/pyo3-ffi/src/object.rs @@ -3,11 +3,11 @@ use crate::pyport::{Py_hash_t, Py_ssize_t}; use crate::refcount; #[cfg(Py_GIL_DISABLED)] use crate::PyMutex; -use std::ffi::{c_char, c_int, c_uint, c_ulong, c_void}; -use std::mem; -use std::ptr; +use core::ffi::{c_char, c_int, c_uint, c_ulong, c_void}; +use core::mem; +use core::ptr; #[cfg(Py_GIL_DISABLED)] -use std::sync::atomic::{AtomicIsize, AtomicU32}; +use core::sync::atomic::{AtomicIsize, AtomicU32}; #[cfg(Py_LIMITED_API)] opaque_struct!(pub PyTypeObject); @@ -74,8 +74,8 @@ pub union PyObjectObRefcnt { } #[cfg(all(Py_3_12, not(Py_GIL_DISABLED)))] -impl std::fmt::Debug for PyObjectObRefcnt { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyObjectObRefcnt { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", unsafe { self.ob_refcnt }) } } @@ -117,7 +117,7 @@ pub struct PyObject { pub ob_type: *mut PyTypeObject, } -const _: () = assert!(std::mem::align_of::() >= _PyObject_MIN_ALIGNMENT); +const _: () = assert!(core::mem::align_of::() >= _PyObject_MIN_ALIGNMENT); #[allow( clippy::declare_interior_mutable_const, @@ -146,7 +146,7 @@ pub const PyObject_HEAD_INIT: PyObject = PyObject { ob_refcnt: 1, #[cfg(PyPy)] ob_pypy_link: 0, - ob_type: std::ptr::null_mut(), + ob_type: core::ptr::null_mut(), }; // skipped _Py_UNOWNED_TID @@ -225,8 +225,8 @@ extern "C" { pub unsafe fn Py_SIZE(ob: *mut PyObject) -> Py_ssize_t { #[cfg(not(GraalPy))] { - debug_assert_ne!((*ob).ob_type, std::ptr::addr_of_mut!(crate::PyLong_Type)); - debug_assert_ne!((*ob).ob_type, std::ptr::addr_of_mut!(crate::PyBool_Type)); + debug_assert_ne!((*ob).ob_type, core::ptr::addr_of_mut!(crate::PyLong_Type)); + debug_assert_ne!((*ob).ob_type, core::ptr::addr_of_mut!(crate::PyBool_Type)); (*ob.cast::()).ob_size } #[cfg(GraalPy)] @@ -697,7 +697,7 @@ pub unsafe fn PyType_HasFeature(ty: *mut PyTypeObject, feature: c_ulong) -> c_in let flags = PyType_GetFlags(ty); #[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))] - let flags = (*ty).tp_flags.load(std::sync::atomic::Ordering::Relaxed); + let flags = (*ty).tp_flags.load(core::sync::atomic::Ordering::Relaxed); #[cfg(all(not(Py_LIMITED_API), not(Py_GIL_DISABLED)))] let flags = (*ty).tp_flags; diff --git a/pyo3-ffi/src/objimpl.rs b/pyo3-ffi/src/objimpl.rs index d34d065ed52..74a4548dec9 100644 --- a/pyo3-ffi/src/objimpl.rs +++ b/pyo3-ffi/src/objimpl.rs @@ -1,5 +1,5 @@ +use core::ffi::{c_int, c_void}; use libc::size_t; -use std::ffi::{c_int, c_void}; use crate::object::*; use crate::pyport::Py_ssize_t; diff --git a/pyo3-ffi/src/pybuffer.rs b/pyo3-ffi/src/pybuffer.rs index 44ae47bdc30..72db6d4fd1b 100644 --- a/pyo3-ffi/src/pybuffer.rs +++ b/pyo3-ffi/src/pybuffer.rs @@ -1,7 +1,7 @@ use crate::object::PyObject; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int, c_void}; -use std::ptr; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr; #[repr(C)] #[derive(Copy, Clone)] diff --git a/pyo3-ffi/src/pycapsule.rs b/pyo3-ffi/src/pycapsule.rs index 65df8837063..2885a7e9af8 100644 --- a/pyo3-ffi/src/pycapsule.rs +++ b/pyo3-ffi/src/pycapsule.rs @@ -1,6 +1,6 @@ use crate::object::*; -use std::ffi::{c_char, c_int, c_void}; -use std::ptr::addr_of_mut; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/pyerrors.rs b/pyo3-ffi/src/pyerrors.rs index 557f314c7cb..9892b8e2aed 100644 --- a/pyo3-ffi/src/pyerrors.rs +++ b/pyo3-ffi/src/pyerrors.rs @@ -1,6 +1,6 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyErr_SetNone")] diff --git a/pyo3-ffi/src/pyframe.rs b/pyo3-ffi/src/pyframe.rs index a8cb9c6e659..d9db3d8c2f8 100644 --- a/pyo3-ffi/src/pyframe.rs +++ b/pyo3-ffi/src/pyframe.rs @@ -2,7 +2,7 @@ #[cfg(any(Py_3_10, all(Py_3_9, not(Py_LIMITED_API))))] use crate::PyCodeObject; use crate::PyFrameObject; -use std::ffi::c_int; +use core::ffi::c_int; extern "C" { pub fn PyFrame_GetLineNumber(frame: *mut PyFrameObject) -> c_int; diff --git a/pyo3-ffi/src/pyhash.rs b/pyo3-ffi/src/pyhash.rs index 4fab07d00d4..d670425ef11 100644 --- a/pyo3-ffi/src/pyhash.rs +++ b/pyo3-ffi/src/pyhash.rs @@ -1,9 +1,9 @@ #[cfg(not(any(Py_LIMITED_API, PyPy)))] use crate::pyport::{Py_hash_t, Py_ssize_t}; #[cfg(not(any(Py_LIMITED_API, PyPy)))] -use std::ffi::c_void; +use core::ffi::c_void; -use std::ffi::{c_int, c_ulong}; +use core::ffi::{c_int, c_ulong}; extern "C" { // skipped non-limited _Py_HashDouble diff --git a/pyo3-ffi/src/pylifecycle.rs b/pyo3-ffi/src/pylifecycle.rs index dd201d20fd0..4f0186fa72e 100644 --- a/pyo3-ffi/src/pylifecycle.rs +++ b/pyo3-ffi/src/pylifecycle.rs @@ -1,7 +1,7 @@ use crate::pytypedefs::PyThreadState; +use core::ffi::{c_char, c_int}; use libc::wchar_t; -use std::ffi::{c_char, c_int}; extern "C" { pub fn Py_Initialize(); @@ -91,7 +91,7 @@ extern "C" { pub fn PyOS_setsig(arg1: c_int, arg2: PyOS_sighandler_t) -> PyOS_sighandler_t; #[cfg(Py_3_11)] - pub static Py_Version: std::ffi::c_ulong; + pub static Py_Version: core::ffi::c_ulong; #[cfg(Py_3_13)] pub fn Py_IsFinalizing() -> c_int; diff --git a/pyo3-ffi/src/pymem.rs b/pyo3-ffi/src/pymem.rs index aaa5a4f6e8d..c39abec593d 100644 --- a/pyo3-ffi/src/pymem.rs +++ b/pyo3-ffi/src/pymem.rs @@ -1,5 +1,5 @@ +use core::ffi::c_void; use libc::size_t; -use std::ffi::c_void; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyMem_Malloc")] diff --git a/pyo3-ffi/src/pyport.rs b/pyo3-ffi/src/pyport.rs index 3a066353ca4..db102368ecf 100644 --- a/pyo3-ffi/src/pyport.rs +++ b/pyo3-ffi/src/pyport.rs @@ -1,7 +1,7 @@ // NB libc does not define this constant on all platforms, so we hard code it // like CPython does. // https://github.com/python/cpython/blob/d8b9011702443bb57579f8834f3effe58e290dfc/Include/pyport.h#L372 -pub const INT_MAX: std::ffi::c_int = 2147483647; +pub const INT_MAX: core::ffi::c_int = 2147483647; pub type PY_UINT32_T = u32; pub type PY_UINT64_T = u64; diff --git a/pyo3-ffi/src/pystate.rs b/pyo3-ffi/src/pystate.rs index b704b90b108..f99876bea5a 100644 --- a/pyo3-ffi/src/pystate.rs +++ b/pyo3-ffi/src/pystate.rs @@ -1,14 +1,14 @@ use crate::moduleobject::PyModuleDef; use crate::object::PyObject; use crate::pytypedefs::{PyInterpreterState, PyThreadState}; -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(any(all(Py_3_9, not(Py_LIMITED_API)), Py_3_10))] #[cfg(not(PyPy))] use crate::PyFrameObject; #[cfg(not(PyPy))] -use std::ffi::c_long; +use core::ffi::c_long; pub const MAX_CO_EXTRA_USERS: c_int = 255; @@ -135,7 +135,7 @@ pub unsafe extern "C" fn PyGILState_Ensure() -> PyGILState_STATE { // nothing we can do it other than waiting for Python 3.14 or not using Windows. At least, // if there is nothing pinned on the stack, it won't cause the process to crash. let ret: PyGILState_STATE = raw::PyGILState_Ensure(); - std::mem::forget(guard); + core::mem::forget(guard); ret } diff --git a/pyo3-ffi/src/pystrtod.rs b/pyo3-ffi/src/pystrtod.rs index 20d5a24387b..07ce46bd41b 100644 --- a/pyo3-ffi/src/pystrtod.rs +++ b/pyo3-ffi/src/pystrtod.rs @@ -1,5 +1,5 @@ use crate::object::PyObject; -use std::ffi::{c_char, c_double, c_int}; +use core::ffi::{c_char, c_double, c_int}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyOS_string_to_double")] diff --git a/pyo3-ffi/src/pythonrun.rs b/pyo3-ffi/src/pythonrun.rs index 090c964d665..5d1836acf85 100644 --- a/pyo3-ffi/src/pythonrun.rs +++ b/pyo3-ffi/src/pythonrun.rs @@ -1,9 +1,9 @@ use crate::object::*; +#[cfg(any(Py_LIMITED_API, not(Py_3_10), PyPy, GraalPy))] +use core::ffi::c_char; +use core::ffi::c_int; #[cfg(not(any(PyPy, Py_LIMITED_API, Py_3_10)))] use libc::FILE; -#[cfg(any(Py_LIMITED_API, not(Py_3_10), PyPy, GraalPy))] -use std::ffi::c_char; -use std::ffi::c_int; extern "C" { #[cfg(any(all(Py_LIMITED_API, not(PyPy)), GraalPy))] @@ -33,13 +33,13 @@ pub unsafe fn Py_CompileString(string: *const c_char, p: *const c_char, s: c_int string: *const c_char, p: *const c_char, s: c_int, - f: *mut std::ffi::c_void, // Actually *mut Py_CompilerFlags in the real definition + f: *mut core::ffi::c_void, // Actually *mut Py_CompilerFlags in the real definition ) -> *mut PyObject; } #[cfg(not(Py_LIMITED_API))] use crate::Py_CompileStringFlags; - Py_CompileStringFlags(string, p, s, std::ptr::null_mut()) + Py_CompileStringFlags(string, p, s, core::ptr::null_mut()) } // skipped PyOS_InputHook diff --git a/pyo3-ffi/src/rangeobject.rs b/pyo3-ffi/src/rangeobject.rs index 35667fed8c2..7902cd47064 100644 --- a/pyo3-ffi/src/rangeobject.rs +++ b/pyo3-ffi/src/rangeobject.rs @@ -1,6 +1,6 @@ use crate::object::*; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/refcount.rs b/pyo3-ffi/src/refcount.rs index 0fefba0bd5c..c5fca435627 100644 --- a/pyo3-ffi/src/refcount.rs +++ b/pyo3-ffi/src/refcount.rs @@ -1,18 +1,18 @@ use crate::pyport::Py_ssize_t; use crate::PyObject; #[cfg(all(not(Py_LIMITED_API), py_sys_config = "Py_REF_DEBUG"))] -use std::ffi::c_char; +use core::ffi::c_char; #[cfg(any(Py_3_12, all(py_sys_config = "Py_REF_DEBUG", not(Py_LIMITED_API))))] -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(all(Py_3_14, any(not(Py_GIL_DISABLED), target_pointer_width = "32")))] -use std::ffi::c_long; +use core::ffi::c_long; #[cfg(any(Py_GIL_DISABLED, all(Py_3_12, not(Py_3_14))))] -use std::ffi::c_uint; +use core::ffi::c_uint; #[cfg(all(Py_3_14, not(Py_GIL_DISABLED)))] -use std::ffi::c_ulong; -use std::ptr; +use core::ffi::c_ulong; +use core::ptr; #[cfg(Py_GIL_DISABLED)] -use std::sync::atomic::Ordering::Relaxed; +use core::sync::atomic::Ordering::Relaxed; #[cfg(all(Py_3_14, not(Py_3_15)))] const _Py_STATICALLY_ALLOCATED_FLAG: c_int = 1 << 7; @@ -298,8 +298,8 @@ pub unsafe fn Py_DECREF(op: *mut PyObject) { #[cfg(py_sys_config = "Py_REF_DEBUG")] if (*op).ob_refcnt.ob_refcnt < 0 { - let location = std::panic::Location::caller(); - let filename = std::ffi::CString::new(location.file()).unwrap(); + let location = core::panic::Location::caller(); + let filename = core::ffi::CString::new(location.file()).unwrap(); _Py_NegativeRefcount(filename.as_ptr(), location.line() as i32, op); } diff --git a/pyo3-ffi/src/setobject.rs b/pyo3-ffi/src/setobject.rs index 4c32952238c..90c4177e3c0 100644 --- a/pyo3-ffi/src/setobject.rs +++ b/pyo3-ffi/src/setobject.rs @@ -2,8 +2,8 @@ use crate::object::*; #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] use crate::pyport::Py_hash_t; use crate::pyport::Py_ssize_t; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; pub const PySet_MINSIZE: usize = 8; diff --git a/pyo3-ffi/src/sliceobject.rs b/pyo3-ffi/src/sliceobject.rs index 7f90289e010..e484bee1259 100644 --- a/pyo3-ffi/src/sliceobject.rs +++ b/pyo3-ffi/src/sliceobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/structmember.rs b/pyo3-ffi/src/structmember.rs index 2d9dd5a4a1f..7b8568c0c54 100644 --- a/pyo3-ffi/src/structmember.rs +++ b/pyo3-ffi/src/structmember.rs @@ -1,4 +1,4 @@ -use std::ffi::c_int; +use core::ffi::c_int; pub use crate::PyMemberDef; diff --git a/pyo3-ffi/src/structseq.rs b/pyo3-ffi/src/structseq.rs index e5cfee1a876..dcc3102f1bc 100644 --- a/pyo3-ffi/src/structseq.rs +++ b/pyo3-ffi/src/structseq.rs @@ -1,7 +1,7 @@ use crate::object::{PyObject, PyTypeObject}; #[cfg(not(PyPy))] use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; #[repr(C)] #[derive(Copy, Clone)] diff --git a/pyo3-ffi/src/sysmodule.rs b/pyo3-ffi/src/sysmodule.rs index c0a3f176228..9a7a168138f 100644 --- a/pyo3-ffi/src/sysmodule.rs +++ b/pyo3-ffi/src/sysmodule.rs @@ -1,6 +1,6 @@ use crate::object::PyObject; +use core::ffi::{c_char, c_int}; use libc::wchar_t; -use std::ffi::{c_char, c_int}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPySys_GetObject")] diff --git a/pyo3-ffi/src/traceback.rs b/pyo3-ffi/src/traceback.rs index 8b1ac216bea..836b34f95e5 100644 --- a/pyo3-ffi/src/traceback.rs +++ b/pyo3-ffi/src/traceback.rs @@ -1,7 +1,7 @@ use crate::object::*; -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(not(PyPy))] -use std::ptr::addr_of_mut; +use core::ptr::addr_of_mut; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyTraceBack_Here")] diff --git a/pyo3-ffi/src/tupleobject.rs b/pyo3-ffi/src/tupleobject.rs index 1bd34081bce..4da6d1913cc 100644 --- a/pyo3-ffi/src/tupleobject.rs +++ b/pyo3-ffi/src/tupleobject.rs @@ -1,7 +1,7 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use std::ffi::c_int; -use std::ptr::addr_of_mut; +use core::ffi::c_int; +use core::ptr::addr_of_mut; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { diff --git a/pyo3-ffi/src/typeslots.rs b/pyo3-ffi/src/typeslots.rs index fd0c3b77a74..d913a2880b1 100644 --- a/pyo3-ffi/src/typeslots.rs +++ b/pyo3-ffi/src/typeslots.rs @@ -1,4 +1,4 @@ -use std::ffi::c_int; +use core::ffi::c_int; pub const Py_bf_getbuffer: c_int = 1; pub const Py_bf_releasebuffer: c_int = 2; diff --git a/pyo3-ffi/src/unicodeobject.rs b/pyo3-ffi/src/unicodeobject.rs index 8ba645bfa05..6c50c654409 100644 --- a/pyo3-ffi/src/unicodeobject.rs +++ b/pyo3-ffi/src/unicodeobject.rs @@ -1,9 +1,9 @@ use crate::object::*; use crate::pyport::Py_ssize_t; -use libc::wchar_t; -use std::ffi::{c_char, c_int, c_void}; +use core::ffi::{c_char, c_int, c_void}; #[cfg(not(PyPy))] -use std::ptr::addr_of_mut; +use core::ptr::addr_of_mut; +use libc::wchar_t; #[cfg(not(Py_LIMITED_API))] #[cfg_attr( diff --git a/pyo3-ffi/src/warnings.rs b/pyo3-ffi/src/warnings.rs index f2cd8adbf9b..69007d61aa4 100644 --- a/pyo3-ffi/src/warnings.rs +++ b/pyo3-ffi/src/warnings.rs @@ -1,6 +1,6 @@ use crate::object::PyObject; use crate::pyport::Py_ssize_t; -use std::ffi::{c_char, c_int}; +use core::ffi::{c_char, c_int}; extern "C" { #[cfg_attr(PyPy, link_name = "PyPyErr_WarnEx")] diff --git a/pyo3-ffi/src/weakrefobject.rs b/pyo3-ffi/src/weakrefobject.rs index 3921310cee8..12a5fbc2a7e 100644 --- a/pyo3-ffi/src/weakrefobject.rs +++ b/pyo3-ffi/src/weakrefobject.rs @@ -1,7 +1,7 @@ use crate::object::*; -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(not(PyPy))] -use std::ptr::addr_of_mut; +use core::ptr::addr_of_mut; #[cfg(all(not(PyPy), Py_LIMITED_API, not(GraalPy)))] opaque_struct!(pub PyWeakReference); diff --git a/src/buffer.rs b/src/buffer.rs index 51f6563b690..7a49e9cf980 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -22,15 +22,15 @@ use crate::inspect::{type_hint_identifier, PyStaticExpr}; use crate::{err, exceptions::PyBufferError, ffi, FromPyObject, PyAny, PyResult, Python}; use crate::{Borrowed, Bound, PyErr}; -use std::ffi::{ +use core::ffi::{ c_char, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, c_ushort, c_void, }; -use std::marker::{PhantomData, PhantomPinned}; -use std::pin::Pin; -use std::ptr::NonNull; -use std::{cell, mem, ptr, slice}; -use std::{ffi::CStr, fmt::Debug}; +use core::marker::{PhantomData, PhantomPinned}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::{cell, mem, ptr, slice}; +use core::{ffi::CStr, fmt::Debug}; /// A typed form of [`PyUntypedBuffer`]. #[repr(transparent)] @@ -56,13 +56,13 @@ unsafe impl Send for PyUntypedBuffer {} unsafe impl Sync for PyUntypedBuffer {} impl Debug for PyBuffer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { debug_buffer("PyBuffer", &self.0, f) } } impl Debug for PyUntypedBuffer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { debug_buffer("PyUntypedBuffer", self, f) } } @@ -70,8 +70,8 @@ impl Debug for PyUntypedBuffer { fn debug_buffer( name: &str, b: &PyUntypedBuffer, - f: &mut std::fmt::Formatter<'_>, -) -> std::fmt::Result { + f: &mut core::fmt::Formatter<'_>, +) -> core::fmt::Result { let raw = b.raw(); f.debug_struct(name) .field("buf", &raw.buf) @@ -366,7 +366,7 @@ impl PyBuffer { #[cfg(not(Py_3_11))] ptr::from_ref(self.raw()).cast_mut(), self.raw().len, - fort as std::ffi::c_char, + fort as core::ffi::c_char, ) }) } @@ -401,7 +401,7 @@ impl PyBuffer { #[cfg(not(Py_3_11))] ptr::from_ref(self.raw()).cast_mut(), self.raw().len, - fort as std::ffi::c_char, + fort as core::ffi::c_char, ) })?; // set vector length to mark the now-initialized space as usable @@ -463,13 +463,13 @@ impl PyBuffer { source.as_ptr().cast::().cast_mut() }, self.raw().len, - fort as std::ffi::c_char, + fort as core::ffi::c_char, ) }) } } -impl std::ops::Deref for PyBuffer { +impl core::ops::Deref for PyBuffer { type Target = PyUntypedBuffer; fn deref(&self) -> &Self::Target { @@ -524,12 +524,12 @@ impl PyUntypedBuffer { if mem::size_of::() != self.item_size() || !T::is_compatible_format(self.format()) { Err(PyBufferError::new_err(format!( "buffer contents are not compatible with {}", - std::any::type_name::() + core::any::type_name::() ))) } else if self.raw().buf.align_offset(mem::align_of::()) != 0 { Err(PyBufferError::new_err(format!( "buffer contents are insufficiently aligned for {}", - std::any::type_name::() + core::any::type_name::() ))) } else { Ok(()) @@ -680,13 +680,13 @@ impl PyUntypedBuffer { /// Gets whether the buffer is contiguous in C-style order (last index varies fastest when visiting items in order of memory address). #[inline] pub fn is_c_contiguous(&self) -> bool { - unsafe { ffi::PyBuffer_IsContiguous(self.raw(), b'C' as std::ffi::c_char) != 0 } + unsafe { ffi::PyBuffer_IsContiguous(self.raw(), b'C' as core::ffi::c_char) != 0 } } /// Gets whether the buffer is contiguous in Fortran-style order (first index varies fastest when visiting items in order of memory address). #[inline] pub fn is_fortran_contiguous(&self) -> bool { - unsafe { ffi::PyBuffer_IsContiguous(self.raw(), b'F' as std::ffi::c_char) != 0 } + unsafe { ffi::PyBuffer_IsContiguous(self.raw(), b'F' as core::ffi::c_char) != 0 } } fn raw(&self) -> &ffi::Py_buffer { @@ -724,7 +724,7 @@ impl Drop for PyUntypedBuffer { } } -/// Like [std::cell::Cell], but only provides read-only access to the data. +/// Like [core::cell::Cell], but only provides read-only access to the data. /// /// `&ReadOnlyCell` is basically a safe version of `*const T`: /// The data cannot be modified through the reference, but other references may @@ -806,7 +806,7 @@ mod tests { #[test] fn test_element_type_from_format() { use super::ElementType::*; - use std::mem::size_of; + use core::mem::size_of; for (cstr, expected) in [ // @ prefix goes to native_element_type_from_type_char @@ -932,8 +932,8 @@ mod tests { fn test_compatible_size() { // for the cast in PyBuffer::shape() assert_eq!( - std::mem::size_of::(), - std::mem::size_of::() + core::mem::size_of::(), + core::mem::size_of::() ); } diff --git a/src/byteswriter.rs b/src/byteswriter.rs index 5e6f22240b4..ad90075be9b 100644 --- a/src/byteswriter.rs +++ b/src/byteswriter.rs @@ -1,3 +1,5 @@ +#![allow(unused_imports, reason = "conditional compilation")] + #[cfg(feature = "experimental-inspect")] use crate::inspect::PyStaticExpr; #[cfg(feature = "experimental-inspect")] @@ -16,12 +18,13 @@ use crate::{ py_result_ext::PyResultExt, }; use crate::{types::PyBytes, Bound, IntoPyObject, PyErr, PyResult, Python}; -use std::io::IoSlice; #[cfg(not(Py_LIMITED_API))] -use std::{ +use core::{ mem::ManuallyDrop, ptr::{self, NonNull}, }; +#[cfg(feature = "std")] +use std::io::IoSlice; pub struct PyBytesWriter<'py> { python: Python<'py>, @@ -82,6 +85,7 @@ impl<'py> PyBytesWriter<'py> { #[inline] #[cfg(not(Py_LIMITED_API))] + #[cfg_attr(not(feature = "std"), allow(dead_code))] fn as_mut_ptr(&mut self) -> *mut u8 { unsafe { PyBytesWriter_GetData(self.writer.as_ptr()) as _ } } @@ -146,6 +150,7 @@ impl<'py> Drop for PyBytesWriter<'py> { } #[cfg(not(Py_LIMITED_API))] +#[cfg(feature = "std")] impl std::io::Write for PyBytesWriter<'_> { fn write(&mut self, buf: &[u8]) -> std::io::Result { self.write_all(buf)?; @@ -189,6 +194,7 @@ impl std::io::Write for PyBytesWriter<'_> { } #[cfg(Py_LIMITED_API)] +#[cfg(feature = "std")] impl std::io::Write for PyBytesWriter<'_> { fn write(&mut self, buf: &[u8]) -> std::io::Result { self.buffer.write(buf) @@ -206,7 +212,7 @@ impl std::io::Write for PyBytesWriter<'_> { self.buffer.write_all(buf) } - fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> { + fn write_fmt(&mut self, args: core::fmt::Arguments<'_>) -> std::io::Result<()> { self.buffer.write_fmt(args) } } @@ -218,6 +224,7 @@ mod tests { use std::io::Write; #[test] + #[cfg(feature = "std")] fn test_io_write() { Python::attach(|py| { let buf = b"hallo world"; @@ -229,6 +236,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_pre_allocated() { Python::attach(|py| { let buf = b"hallo world"; @@ -241,6 +249,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_io_write_vectored() { Python::attach(|py| { let bufs = [IoSlice::new(b"hallo "), IoSlice::new(b"world")]; @@ -252,6 +261,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_large_data() { Python::attach(|py| { let mut writer = PyBytesWriter::new(py).unwrap(); diff --git a/src/call.rs b/src/call.rs index b621e83a9e1..8141c9b5428 100644 --- a/src/call.rs +++ b/src/call.rs @@ -207,7 +207,7 @@ impl<'py> PyCallArgs<'py> for Borrowed<'_, 'py, PyTuple> { _: private::Token, ) -> PyResult> { unsafe { - ffi::PyObject_Call(function.as_ptr(), self.as_ptr(), std::ptr::null_mut()) + ffi::PyObject_Call(function.as_ptr(), self.as_ptr(), core::ptr::null_mut()) .assume_owned_or_err(function.py()) } } diff --git a/src/conversion.rs b/src/conversion.rs index ef349ea97b6..5d172ffdad6 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -13,8 +13,8 @@ use crate::{ Borrowed, Bound, BoundObject, Py, PyAny, PyClass, PyClassGuard, PyErr, PyRef, PyRefMut, PyTypeCheck, Python, }; -use std::convert::Infallible; -use std::marker::PhantomData; +use core::convert::Infallible; +use core::marker::PhantomData; /// Defines a conversion from a Rust type to a Python object, which may fail. /// @@ -533,7 +533,7 @@ pub(crate) use from_py_object_sequence::FromPyObjectSequence; /// ``` /// /// [`PyList`]: crate::types::PyList -/// [`Arc`]: std::sync::Arc +/// [`Arc`]: alloc::sync::Arc pub trait FromPyObjectOwned<'py>: for<'a> FromPyObject<'a, 'py> {} impl<'py, T> FromPyObjectOwned<'py> for T where T: for<'a> FromPyObject<'a, 'py> {} diff --git a/src/conversions/anyhow.rs b/src/conversions/anyhow.rs index af6bf515fee..a02ed68f6f0 100644 --- a/src/conversions/anyhow.rs +++ b/src/conversions/anyhow.rs @@ -37,11 +37,13 @@ //! // A wrapper around a Rust function. //! // The pyfunction macro performs the conversion to a PyErr //! #[pyfunction] +//! # #[cfg(feature = "std")] //! fn py_open(filename: PathBuf) -> anyhow::Result> { //! let data = std::fs::read(filename)?; //! Ok(data) //! } //! +//! # #[cfg(feature = "std")] //! fn main() { //! let error = Python::attach(|py| -> PyResult> { //! let fun = wrap_pyfunction!(py_open, py)?; @@ -51,6 +53,9 @@ //! //! println!("{}", error); //! } +//! +//! # #[cfg(not(feature = "std"))] +//! # fn main() {} //! ``` //! //! # Example: Using `anyhow` in general diff --git a/src/conversions/bigdecimal.rs b/src/conversions/bigdecimal.rs index 041f132e180..c25d3d01e97 100644 --- a/src/conversions/bigdecimal.rs +++ b/src/conversions/bigdecimal.rs @@ -49,7 +49,7 @@ //! assert d + 1 == value //! ``` -use std::str::FromStr; +use core::str::FromStr; #[cfg(feature = "experimental-inspect")] use crate::inspect::PyStaticExpr; @@ -121,7 +121,7 @@ mod test_bigdecimal { use super::*; use crate::types::dict::PyDictMethods; use crate::types::PyDict; - use std::ffi::CString; + use alloc::ffi::CString; use bigdecimal::{One, Zero}; #[cfg(not(target_arch = "wasm32"))] diff --git a/src/conversions/chrono.rs b/src/conversions/chrono.rs index 296b95d5b4b..6b3845394c8 100644 --- a/src/conversions/chrono.rs +++ b/src/conversions/chrono.rs @@ -635,7 +635,7 @@ fn warn_truncated_leap_second(obj: &Bound<'_, PyAny>) { #[cfg(not(Py_LIMITED_API))] fn py_date_to_naive_date( - py_date: impl std::ops::Deref, + py_date: impl core::ops::Deref, ) -> PyResult { NaiveDate::from_ymd_opt( py_date.get_year(), @@ -657,7 +657,7 @@ fn py_date_to_naive_date(py_date: &Bound<'_, PyAny>) -> PyResult { #[cfg(not(Py_LIMITED_API))] fn py_time_to_naive_time( - py_time: impl std::ops::Deref, + py_time: impl core::ops::Deref, ) -> PyResult { NaiveTime::from_hms_micro_opt( py_time.get_hour().into(), @@ -715,7 +715,8 @@ fn py_datetime_to_datetime_with_timezone( mod tests { use super::*; use crate::{test_utils::assert_warnings, types::PyTuple, BoundObject}; - use std::{cmp::Ordering, panic}; + use core::cmp::Ordering; + use std::panic; #[test] // Only Python>=3.9 has the zoneinfo package @@ -1312,8 +1313,8 @@ mod tests { use super::*; use crate::test_utils::CatchWarnings; use crate::types::IntoPyDict; + use alloc::ffi::CString; use proptest::prelude::*; - use std::ffi::CString; proptest! { diff --git a/src/conversions/chrono_tz.rs b/src/conversions/chrono_tz.rs index 76af879d696..153e48817a0 100644 --- a/src/conversions/chrono_tz.rs +++ b/src/conversions/chrono_tz.rs @@ -44,9 +44,9 @@ use crate::types::{any::PyAnyMethods, PyTzInfo}; #[cfg(all(feature = "experimental-inspect", not(Py_3_9)))] use crate::PyTypeInfo; use crate::{intern, Borrowed, Bound, FromPyObject, PyAny, PyErr, Python}; +use alloc::borrow::Cow; use chrono_tz::Tz; -use std::borrow::Cow; -use std::str::FromStr; +use core::str::FromStr; impl<'py> IntoPyObject<'py> for Tz { type Target = PyTzInfo; diff --git a/src/conversions/either.rs b/src/conversions/either.rs index 74d0206ec7d..d67ad38a739 100644 --- a/src/conversions/either.rs +++ b/src/conversions/either.rs @@ -120,8 +120,8 @@ where // is not experimental, rather than the Rust type names. let err_msg = format!( "failed to convert the value to 'Union[{}, {}]'", - std::any::type_name::(), - std::any::type_name::() + core::any::type_name::(), + core::any::type_name::() ); Err(PyTypeError::new_err(err_msg)) } @@ -135,7 +135,7 @@ where #[cfg(test)] mod tests { - use std::borrow::Cow; + use alloc::borrow::Cow; use crate::exceptions::PyTypeError; use crate::{IntoPyObject, Python}; diff --git a/src/conversions/eyre.rs b/src/conversions/eyre.rs index 5923854a188..ab7d7c58d47 100644 --- a/src/conversions/eyre.rs +++ b/src/conversions/eyre.rs @@ -39,11 +39,13 @@ //! // A wrapper around a Rust function. //! // The pyfunction macro performs the conversion to a PyErr //! #[pyfunction] +//! # #[cfg(feature = "std")] //! fn py_open(filename: PathBuf) -> eyre::Result> { //! let data = std::fs::read(filename)?; //! Ok(data) //! } //! +//! # #[cfg(feature = "std")] //! fn main() { //! let error = Python::attach(|py| -> PyResult> { //! let fun = wrap_pyfunction!(py_open, py)?; @@ -53,12 +55,15 @@ //! //! println!("{}", error); //! } +//! +//! # #[cfg(not(feature = "std"))] +//! # fn main() {} //! ``` //! //! # Example: Using `eyre` in general //! //! Note that you don't need this feature to convert a [`PyErr`] into an [`eyre::Report`], because -//! it can already convert anything that implements [`Error`](std::error::Error): +//! it can already convert anything that implements [`Error`](core::error::Error): //! //! ```rust //! use pyo3::prelude::*; @@ -132,8 +137,7 @@ mod tests { use eyre::{bail, eyre, Report, Result, WrapErr}; fn f() -> Result<()> { - use std::io; - bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!")); + bail!("not int".parse::().unwrap_err()) } fn g() -> Result<()> { diff --git a/src/conversions/hashbrown.rs b/src/conversions/hashbrown.rs index 3d6e8f9f54b..c841523e874 100644 --- a/src/conversions/hashbrown.rs +++ b/src/conversions/hashbrown.rs @@ -28,7 +28,7 @@ use crate::{ }; #[cfg(feature = "experimental-inspect")] use crate::{type_hint_subscript, type_hint_union, PyTypeInfo}; -use std::hash; +use core::hash; impl<'py, K, V, H> IntoPyObject<'py> for hashbrown::HashMap where diff --git a/src/conversions/indexmap.rs b/src/conversions/indexmap.rs index 3f0e1cf879d..8088749583b 100644 --- a/src/conversions/indexmap.rs +++ b/src/conversions/indexmap.rs @@ -94,7 +94,7 @@ use crate::types::*; #[cfg(feature = "experimental-inspect")] use crate::{type_hint_subscript, PyTypeInfo}; use crate::{Borrowed, Bound, FromPyObject, PyErr, Python}; -use std::hash; +use core::hash; impl<'py, K, V, H> IntoPyObject<'py> for indexmap::IndexMap where diff --git a/src/conversions/jiff.rs b/src/conversions/jiff.rs index a48839165f1..593811f7641 100644 --- a/src/conversions/jiff.rs +++ b/src/conversions/jiff.rs @@ -55,12 +55,12 @@ use crate::types::{PyDateAccess, PyDeltaAccess, PyTimeAccess}; use crate::{intern, Borrowed, Bound, FromPyObject, IntoPyObject, PyAny, PyErr, PyResult, Python}; #[cfg(feature = "experimental-inspect")] use crate::{type_hint_identifier, PyTypeInfo}; +use alloc::borrow::Cow; use jiff::civil::{Date, DateTime, ISOWeekDate, Time}; use jiff::tz::{Offset, TimeZone}; use jiff::{SignedDuration, Span, Timestamp, Zoned}; #[cfg(feature = "jiff-02")] use jiff_02 as jiff; -use std::borrow::Cow; fn datetime_to_pydatetime<'py>( py: Python<'py>, @@ -604,8 +604,8 @@ impl From for PyErr { mod tests { use super::*; use crate::{types::PyTuple, BoundObject}; + use core::cmp::Ordering; use jiff::tz::Offset; - use std::cmp::Ordering; #[test] // Only Python>=3.9 has the zoneinfo package @@ -860,7 +860,7 @@ mod tests { #[test] #[cfg(all(Py_3_9, not(windows)))] fn test_ambiguous_datetime_to_pyobject() { - use std::str::FromStr; + use core::str::FromStr; let dates = [ Zoned::from_str("2020-10-24 23:00:00[UTC]").unwrap(), Zoned::from_str("2020-10-25 00:00:00[UTC]").unwrap(), @@ -1069,22 +1069,22 @@ mod tests { mod proptests { use super::*; use crate::types::IntoPyDict; + use alloc::ffi::CString; use jiff::tz::TimeZoneTransition; use jiff::SpanRelativeTo; use proptest::prelude::*; - use std::ffi::CString; // This is to skip the test if we are creating an invalid date, like February 31. #[track_caller] fn try_date(year: i16, month: i8, day: i8) -> Result { - let location = std::panic::Location::caller(); + let location = core::panic::Location::caller(); Date::new(year, month, day) .map_err(|err| TestCaseError::reject(format!("{location}: {err:?}"))) } #[track_caller] fn try_time(hour: i8, min: i8, sec: i8, micro: i32) -> Result { - let location = std::panic::Location::caller(); + let location = core::panic::Location::caller(); Time::new(hour, min, sec, micro * 1000) .map_err(|err| TestCaseError::reject(format!("{location}: {err:?}"))) } @@ -1102,7 +1102,7 @@ mod tests { ) -> Result { let date = try_date(year, month, day)?; let time = try_time(hour, min, sec, micro)?; - let location = std::panic::Location::caller(); + let location = core::panic::Location::caller(); DateTime::from_parts(date, time) .to_zoned(tz) .map_err(|err| TestCaseError::reject(format!("{location}: {err:?}"))) diff --git a/src/conversions/num_bigint.rs b/src/conversions/num_bigint.rs index cdc77d8b095..a5b97c63b58 100644 --- a/src/conversions/num_bigint.rs +++ b/src/conversions/num_bigint.rs @@ -47,11 +47,12 @@ //! assert n + 1 == value //! ``` +use super::std::num::nb_index; #[cfg(Py_LIMITED_API)] use crate::types::{bytes::PyBytesMethods, PyBytes}; use crate::{ - conversion::IntoPyObject, std::num::nb_index, types::PyInt, Borrowed, Bound, FromPyObject, - PyAny, PyErr, PyResult, Python, + conversion::IntoPyObject, types::PyInt, Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult, + Python, }; use num_bigint::{BigInt, BigUint}; @@ -266,7 +267,7 @@ fn int_to_u32_vec(long: &Bound<'_, PyInt>) -> PyResult() -> impl Iterator where T: From, - for<'a> &'a T: std::ops::Add, + for<'a> &'a T: core::ops::Add, { let mut f0: T = T::from(1); let mut f1: T = T::from(1); - std::iter::from_fn(move || { + core::iter::from_fn(move || { let f2 = &f0 + &f1; - Some(std::mem::replace(&mut f0, std::mem::replace(&mut f1, f2))) + Some(core::mem::replace(&mut f0, core::mem::replace(&mut f1, f2))) }) } fn python_fib(py: Python<'_>) -> impl Iterator> + '_ { let mut f0 = 1i32.into_pyobject(py).unwrap().into_any(); let mut f1 = 1i32.into_pyobject(py).unwrap().into_any(); - std::iter::from_fn(move || { + core::iter::from_fn(move || { let f2 = f0.call_method1("__add__", (&f1,)).unwrap(); - Some(std::mem::replace(&mut f0, std::mem::replace(&mut f1, f2))) + Some(core::mem::replace(&mut f0, core::mem::replace(&mut f1, f2))) }) } diff --git a/src/conversions/num_complex.rs b/src/conversions/num_complex.rs index 9d4d9a37882..b5ab7593ef4 100644 --- a/src/conversions/num_complex.rs +++ b/src/conversions/num_complex.rs @@ -101,8 +101,8 @@ use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, types::PyComplex, Borrowed, Bound, FromPyObject, PyAny, PyErr, Python, }; +use core::ffi::c_double; use num_complex::Complex; -use std::ffi::c_double; impl PyComplex { /// Creates a new Python `PyComplex` object from `num_complex`'s [`Complex`]. @@ -124,7 +124,7 @@ macro_rules! complex_conversion { impl<'py> crate::conversion::IntoPyObject<'py> for Complex<$float> { type Target = PyComplex; type Output = Bound<'py, Self::Target>; - type Error = std::convert::Infallible; + type Error = core::convert::Infallible; #[cfg(feature = "experimental-inspect")] const OUTPUT_TYPE: PyStaticExpr = type_hint_identifier!("builtins", "complex"); @@ -144,7 +144,7 @@ macro_rules! complex_conversion { impl<'py> crate::conversion::IntoPyObject<'py> for &Complex<$float> { type Target = PyComplex; type Output = Bound<'py, Self::Target>; - type Error = std::convert::Infallible; + type Error = core::convert::Infallible; #[cfg(feature = "experimental-inspect")] const OUTPUT_TYPE: PyStaticExpr = >::OUTPUT_TYPE; diff --git a/src/conversions/ordered_float.rs b/src/conversions/ordered_float.rs index 804192ca909..25391627a5f 100644 --- a/src/conversions/ordered_float.rs +++ b/src/conversions/ordered_float.rs @@ -57,8 +57,8 @@ use crate::exceptions::PyValueError; use crate::inspect::PyStaticExpr; use crate::types::PyFloat; use crate::{Borrowed, Bound, FromPyObject, PyAny, Python}; +use core::convert::Infallible; use ordered_float::{NotNan, OrderedFloat}; -use std::convert::Infallible; macro_rules! float_conversions { ($wrapper:ident, $float_type:ty, $constructor:expr) => { @@ -114,8 +114,8 @@ mod test_ordered_float { use super::*; use crate::types::dict::IntoPyDict; use crate::types::PyAnyMethods; - use std::ffi::CStr; - use std::ffi::CString; + use alloc::ffi::CString; + use core::ffi::CStr; #[cfg(not(target_arch = "wasm32"))] use proptest::prelude::*; diff --git a/src/conversions/rust_decimal.rs b/src/conversions/rust_decimal.rs index 539b65eef06..101ac354dbb 100644 --- a/src/conversions/rust_decimal.rs +++ b/src/conversions/rust_decimal.rs @@ -60,8 +60,8 @@ use crate::types::any::PyAnyMethods; use crate::types::string::PyStringMethods; use crate::types::PyType; use crate::{Borrowed, Bound, FromPyObject, Py, PyAny, PyErr, PyResult, Python}; +use core::str::FromStr; use rust_decimal::Decimal; -use std::str::FromStr; impl FromPyObject<'_, '_> for Decimal { type Error = PyErr; @@ -124,7 +124,7 @@ mod test_rust_decimal { use super::*; use crate::types::dict::PyDictMethods; use crate::types::PyDict; - use std::ffi::CString; + use alloc::ffi::CString; #[cfg(not(target_arch = "wasm32"))] use proptest::prelude::*; diff --git a/src/conversions/std/array.rs b/src/conversions/std/array.rs index 1ce05e4d5ab..16a1d527e0c 100644 --- a/src/conversions/std/array.rs +++ b/src/conversions/std/array.rs @@ -131,6 +131,11 @@ pub(crate) fn invalid_sequence_length(expected: usize, actual: usize) -> PyErr { } #[cfg(test)] +#[allow( + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + reason = "tests" +)] mod tests { #[cfg(panic = "unwind")] use std::{ diff --git a/src/conversions/std/cell.rs b/src/conversions/std/cell.rs index b90d5432748..df1473c5f40 100644 --- a/src/conversions/std/cell.rs +++ b/src/conversions/std/cell.rs @@ -1,4 +1,4 @@ -use std::cell::Cell; +use core::cell::Cell; #[cfg(feature = "experimental-inspect")] use crate::inspect::PyStaticExpr; diff --git a/src/conversions/std/cstring.rs b/src/conversions/std/cstring.rs index 2dd05265639..08573ab083b 100644 --- a/src/conversions/std/cstring.rs +++ b/src/conversions/std/cstring.rs @@ -4,13 +4,14 @@ use crate::inspect::PyStaticExpr; use crate::type_object::PyTypeInfo; use crate::types::PyString; use crate::{Borrowed, Bound, FromPyObject, IntoPyObject, PyAny, PyErr, Python}; -use std::borrow::Cow; -use std::ffi::{CStr, CString}; -use std::str::Utf8Error; +use alloc::borrow::Cow; +use alloc::ffi::CString; +use core::ffi::CStr; +use core::str::Utf8Error; #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] use { crate::{exceptions::PyValueError, ffi}, - std::slice, + core::slice, }; impl<'py> IntoPyObject<'py> for &CStr { @@ -168,7 +169,7 @@ mod tests { fn test_extract_with_nul_error() { Python::attach(|py| { let s = "Hello\0Python"; - let py_string = s.into_pyobject(py).unwrap(); + let py_string: Bound<'_, PyString> = s.into_pyobject(py).unwrap(); #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] { diff --git a/src/conversions/std/ipaddr.rs b/src/conversions/std/ipaddr.rs index cd2f867a51e..305b73bee7b 100644 --- a/src/conversions/std/ipaddr.rs +++ b/src/conversions/std/ipaddr.rs @@ -7,7 +7,7 @@ use crate::types::any::PyAnyMethods; use crate::types::string::PyStringMethods; use crate::types::PyType; use crate::{intern, Borrowed, Bound, FromPyObject, Py, PyAny, PyErr, Python}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use core::net::{IpAddr, Ipv4Addr, Ipv6Addr}; impl FromPyObject<'_, '_> for IpAddr { type Error = PyErr; @@ -130,7 +130,7 @@ impl<'py> IntoPyObject<'py> for &IpAddr { #[cfg(test)] mod test_ipaddr { - use std::str::FromStr; + use core::str::FromStr; use crate::types::PyString; diff --git a/src/conversions/std/map.rs b/src/conversions/std/map.rs index f4f5fad6596..3feeb387fc2 100644 --- a/src/conversions/std/map.rs +++ b/src/conversions/std/map.rs @@ -1,3 +1,5 @@ +#![allow(unused_imports, reason = "conditional compilation")] + #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; #[cfg(feature = "experimental-inspect")] @@ -10,9 +12,11 @@ use crate::{ types::{any::PyAnyMethods, dict::PyDictMethods, PyDict}, Borrowed, FromPyObject, PyAny, PyErr, Python, }; -use std::{cmp, collections, hash}; +use alloc::collections; +use core::{cmp, hash}; -impl<'py, K, V, H> IntoPyObject<'py> for collections::HashMap +#[cfg(feature = "std")] +impl<'py, K, V, H> IntoPyObject<'py> for std::collections::HashMap where K: IntoPyObject<'py> + cmp::Eq + hash::Hash, V: IntoPyObject<'py>, @@ -40,7 +44,8 @@ where } } -impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a collections::HashMap +#[cfg(feature = "std")] +impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a std::collections::HashMap where &'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash, &'a V: IntoPyObject<'py>, @@ -124,7 +129,8 @@ where } } -impl<'py, K, V, S> FromPyObject<'_, 'py> for collections::HashMap +#[cfg(feature = "std")] +impl<'py, K, V, S> FromPyObject<'_, 'py> for std::collections::HashMap where K: FromPyObjectOwned<'py> + cmp::Eq + hash::Hash, V: FromPyObjectOwned<'py>, @@ -138,7 +144,7 @@ where fn extract(ob: Borrowed<'_, 'py, PyAny>) -> Result { let dict = ob.cast::()?; - let mut ret = collections::HashMap::with_capacity_and_hasher(dict.len(), S::default()); + let mut ret = std::collections::HashMap::with_capacity_and_hasher(dict.len(), S::default()); for (k, v) in dict.iter() { ret.insert( k.extract().map_err(Into::into)?, @@ -186,9 +192,12 @@ where #[cfg(test)] mod tests { use super::*; - use std::collections::{BTreeMap, HashMap}; + use alloc::collections::BTreeMap; + #[cfg(feature = "std")] + use std::collections::HashMap; #[test] + #[cfg(feature = "std")] fn test_hashmap_to_python() { Python::attach(|py| { let mut map = HashMap::::new(); @@ -233,6 +242,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_hashmap_into_python() { Python::attach(|py| { let mut map = HashMap::::new(); diff --git a/src/conversions/std/mod.rs b/src/conversions/std/mod.rs index c82f2eba98f..6bf0eaa0de0 100644 --- a/src/conversions/std/mod.rs +++ b/src/conversions/std/mod.rs @@ -5,7 +5,9 @@ mod ipaddr; mod map; pub(crate) mod num; mod option; +#[cfg(feature = "std")] mod osstr; +#[cfg(feature = "std")] mod path; mod set; mod slice; diff --git a/src/conversions/std/num.rs b/src/conversions/std/num.rs index 2161c2f8935..f1ad88c0cff 100644 --- a/src/conversions/std/num.rs +++ b/src/conversions/std/num.rs @@ -10,10 +10,10 @@ use crate::py_result_ext::PyResultExt; use crate::type_object::PyTypeInfo; use crate::types::{PyByteArray, PyByteArrayMethods, PyBytes, PyInt}; use crate::{exceptions, ffi, Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult, Python}; -use std::convert::Infallible; -use std::ffi::c_long; -use std::mem::MaybeUninit; -use std::num::{ +use core::convert::Infallible; +use core::ffi::c_long; +use core::mem::MaybeUninit; +use core::num::{ NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, }; @@ -335,7 +335,7 @@ impl BytesSequenceExtractor<'_, '_> { } // Safety: `slice` and `out` are guaranteed not to overlap due to `&mut` reference on `out`. unsafe { - std::ptr::copy_nonoverlapping(slice.as_ptr(), out.as_mut_ptr().cast(), out.len()) + core::ptr::copy_nonoverlapping(slice.as_ptr(), out.as_mut_ptr().cast(), out.len()) }; Ok(()) }; @@ -367,7 +367,7 @@ impl FromPyObjectSequence for BytesSequenceExtractor<'_, '_> { // Safety: `[u8; N]` has the same layout as `[MaybeUninit; N]` let slice = unsafe { - std::slice::from_raw_parts_mut(out.as_mut_ptr().cast::>(), N) + core::slice::from_raw_parts_mut(out.as_mut_ptr().cast::>(), N) }; self.fill_slice(slice)?; @@ -471,7 +471,7 @@ mod fast_128bit_int_conversion { fn extract(ob: Borrowed<'_, '_, PyAny>) -> Result<$rust_type, Self::Error> { let num = nb_index(&ob)?; - let mut buffer = [0u8; std::mem::size_of::<$rust_type>()]; + let mut buffer = [0u8; core::mem::size_of::<$rust_type>()]; #[cfg(not(Py_3_13))] { crate::err::error_on_minusone(ob.py(), unsafe { @@ -755,7 +755,7 @@ mod test_128bit_integers { use proptest::prelude::*; #[cfg(not(target_arch = "wasm32"))] - use std::ffi::CString; + use alloc::ffi::CString; #[cfg(not(target_arch = "wasm32"))] proptest! { @@ -945,7 +945,7 @@ mod test_128bit_integers { mod tests { use crate::types::PyAnyMethods; use crate::{IntoPyObject, Python}; - use std::num::*; + use core::num::*; #[test] fn test_u32_max() { @@ -1092,7 +1092,7 @@ mod tests { use crate::conversion::IntoPyObject; use crate::types::PyAnyMethods; use crate::Python; - use std::num::*; + use core::num::*; #[test] fn from_py_string_type_error() { diff --git a/src/conversions/std/osstr.rs b/src/conversions/std/osstr.rs index 358c88cf531..0bd1117a658 100644 --- a/src/conversions/std/osstr.rs +++ b/src/conversions/std/osstr.rs @@ -1,3 +1,9 @@ +#![allow( + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + reason = "this entire mod is only for std" +)] + use crate::conversion::IntoPyObject; #[cfg(not(target_os = "wasi"))] use crate::ffi; @@ -128,7 +134,7 @@ impl FromPyObject<'_, '_> for OsString { // Get an owned allocated wide char buffer from PyString, which we have to deallocate // ourselves let size = - unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), std::ptr::null_mut(), 0) }; + unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), core::ptr::null_mut(), 0) }; crate::err::error_on_minusone(ob.py(), size)?; debug_assert!( diff --git a/src/conversions/std/path.rs b/src/conversions/std/path.rs index c92ce11d06d..66188a58c3d 100644 --- a/src/conversions/std/path.rs +++ b/src/conversions/std/path.rs @@ -1,3 +1,9 @@ +#![allow( + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + reason = "this entire mod is only for std" +)] + use crate::conversion::IntoPyObject; use crate::ffi_ptr_ext::FfiPtrExt; #[cfg(feature = "experimental-inspect")] diff --git a/src/conversions/std/set.rs b/src/conversions/std/set.rs index 6dd07fa5a6c..b1d24536215 100644 --- a/src/conversions/std/set.rs +++ b/src/conversions/std/set.rs @@ -1,4 +1,7 @@ -use std::{cmp, collections, hash}; +#![allow(unused_imports, reason = "conditional compilation")] + +use alloc::collections; +use core::{cmp, hash}; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; @@ -14,7 +17,8 @@ use crate::{ Borrowed, Bound, FromPyObject, PyAny, PyErr, Python, }; -impl<'py, K, S> IntoPyObject<'py> for collections::HashSet +#[cfg(feature = "std")] +impl<'py, K, S> IntoPyObject<'py> for std::collections::HashSet where K: IntoPyObject<'py> + Eq + hash::Hash, S: hash::BuildHasher + Default, @@ -36,7 +40,8 @@ where } } -impl<'a, 'py, K, H> IntoPyObject<'py> for &'a collections::HashSet +#[cfg(feature = "std")] +impl<'a, 'py, K, H> IntoPyObject<'py> for &'a std::collections::HashSet where &'a K: IntoPyObject<'py> + Eq + hash::Hash, H: hash::BuildHasher, @@ -57,7 +62,8 @@ where } } -impl<'py, K, S> FromPyObject<'_, 'py> for collections::HashSet +#[cfg(feature = "std")] +impl<'py, K, S> FromPyObject<'_, 'py> for std::collections::HashSet where K: FromPyObjectOwned<'py> + cmp::Eq + hash::Hash, S: hash::BuildHasher + Default, @@ -173,9 +179,11 @@ where mod tests { use crate::types::{any::PyAnyMethods, PyFrozenSet, PySet}; use crate::{IntoPyObject, Python}; - use std::collections::{BTreeSet, HashSet}; + use alloc::collections::BTreeSet; + use std::collections::HashSet; #[test] + #[cfg(feature = "std")] fn test_extract_hashset() { Python::attach(|py| { let set = PySet::new(py, [1, 2, 3, 4, 5]).unwrap(); @@ -205,13 +213,15 @@ mod tests { fn test_set_into_pyobject() { Python::attach(|py| { let bt: BTreeSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let hs: HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let bto = (&bt).into_pyobject(py).unwrap(); - let hso = (&hs).into_pyobject(py).unwrap(); - assert_eq!(bt, bto.extract().unwrap()); - assert_eq!(hs, hso.extract().unwrap()); + + #[cfg(feature = "std")] + { + let hs: HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); + let hso = (&hs).into_pyobject(py).unwrap(); + assert_eq!(hs, hso.extract().unwrap()); + } }); } } diff --git a/src/conversions/std/slice.rs b/src/conversions/std/slice.rs index 069b07a3130..53f96348274 100644 --- a/src/conversions/std/slice.rs +++ b/src/conversions/std/slice.rs @@ -1,4 +1,4 @@ -use std::borrow::Cow; +use alloc::borrow::Cow; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; @@ -104,7 +104,7 @@ where #[cfg(test)] mod tests { - use std::borrow::Cow; + use alloc::borrow::Cow; use crate::{ conversion::IntoPyObject, diff --git a/src/conversions/std/string.rs b/src/conversions/std/string.rs index 4f4024ff377..a72679fe0cb 100644 --- a/src/conversions/std/string.rs +++ b/src/conversions/std/string.rs @@ -8,7 +8,8 @@ use crate::{ conversion::IntoPyObject, instance::Bound, types::PyString, Borrowed, FromPyObject, PyAny, PyErr, Python, }; -use std::{borrow::Cow, convert::Infallible}; +use alloc::borrow::Cow; +use core::convert::Infallible; impl<'py> IntoPyObject<'py> for &str { type Target = PyString; @@ -240,7 +241,7 @@ impl FromPyObject<'_, '_> for char { mod tests { use crate::types::any::PyAnyMethods; use crate::{IntoPyObject, Python}; - use std::borrow::Cow; + use alloc::borrow::Cow; #[test] fn test_cow_into_pyobject() { diff --git a/src/conversions/std/time.rs b/src/conversions/std/time.rs index 35fc784666b..cce64e98530 100644 --- a/src/conversions/std/time.rs +++ b/src/conversions/std/time.rs @@ -1,3 +1,5 @@ +#![allow(unused_imports, reason = "conditional compilation")] + use crate::conversion::IntoPyObject; use crate::exceptions::{PyOverflowError, PyValueError}; #[cfg(feature = "experimental-inspect")] @@ -12,7 +14,9 @@ use crate::types::any::PyAnyMethods; use crate::types::PyDeltaAccess; use crate::types::{PyDateTime, PyDelta, PyTzInfo}; use crate::{Borrowed, Bound, FromPyObject, Py, PyAny, PyErr, PyResult, Python}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use core::time::Duration; +#[cfg(feature = "std")] +use std::time::{SystemTime, UNIX_EPOCH}; const SECONDS_PER_DAY: u64 = 24 * 60 * 60; @@ -102,6 +106,7 @@ impl<'py> IntoPyObject<'py> for &Duration { // // TODO: it might be nice to investigate using timestamps anyway, at least when the datetime is a safe range. +#[cfg(feature = "std")] impl FromPyObject<'_, '_> for SystemTime { type Error = PyErr; @@ -118,6 +123,7 @@ impl FromPyObject<'_, '_> for SystemTime { } } +#[cfg(feature = "std")] impl<'py> IntoPyObject<'py> for SystemTime { type Target = PyDateTime; type Output = Bound<'py, Self::Target>; @@ -136,6 +142,7 @@ impl<'py> IntoPyObject<'py> for SystemTime { } } +#[cfg(feature = "std")] impl<'py> IntoPyObject<'py> for &SystemTime { type Target = PyDateTime; type Output = Bound<'py, Self::Target>; @@ -150,6 +157,7 @@ impl<'py> IntoPyObject<'py> for &SystemTime { } } +#[cfg(feature = "std")] fn unix_epoch_py(py: Python<'_>) -> PyResult> { static UNIX_EPOCH: PyOnceLock> = PyOnceLock::new(); Ok(UNIX_EPOCH @@ -270,6 +278,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_time_frompyobject() { Python::attach(|py| { assert_eq!( @@ -296,6 +305,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_time_frompyobject_before_epoch() { Python::attach(|py| { assert_eq!( @@ -309,6 +319,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_time_intopyobject() { Python::attach(|py| { let assert_eq = |l: Bound<'_, PyDateTime>, r: Bound<'_, PyDateTime>| { @@ -334,6 +345,7 @@ mod tests { }); } + #[cfg(feature = "std")] #[expect(clippy::too_many_arguments)] fn new_datetime( py: Python<'_>, @@ -360,6 +372,7 @@ mod tests { .unwrap() } + #[cfg(feature = "std")] fn max_datetime(py: Python<'_>) -> Bound<'_, PyDateTime> { let naive_max = datetime_class(py).getattr("max").unwrap(); let kargs = PyDict::new(py); @@ -374,6 +387,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_time_intopyobject_overflow() { let big_system_time = UNIX_EPOCH .checked_add(Duration::new(300000000000, 0)) @@ -394,6 +408,7 @@ mod tests { .unwrap() } + #[cfg(feature = "std")] fn datetime_class(py: Python<'_>) -> Bound<'_, PyAny> { py.import("datetime").unwrap().getattr("datetime").unwrap() } diff --git a/src/conversions/uuid.rs b/src/conversions/uuid.rs index edd4c9e5c16..cc2b19c5e12 100644 --- a/src/conversions/uuid.rs +++ b/src/conversions/uuid.rs @@ -172,7 +172,7 @@ mod tests { use super::*; use crate::types::dict::PyDictMethods; use crate::types::PyDict; - use std::ffi::CString; + use alloc::ffi::CString; use uuid::Uuid; macro_rules! convert_constants { diff --git a/src/coroutine.rs b/src/coroutine.rs index e5971853bc9..3f829f1c866 100644 --- a/src/coroutine.rs +++ b/src/coroutine.rs @@ -1,12 +1,12 @@ //! Python coroutine implementation, used notably when wrapping `async fn` //! with `#[pyfunction]`/`#[pymethods]`. -use std::{ +use alloc::sync::Arc; +use core::{ future::Future, - panic, pin::Pin, - sync::Arc, task::{Context, Poll, Waker}, }; +use std::panic; use pyo3_macros::{pyclass, pymethods}; diff --git a/src/coroutine/cancel.rs b/src/coroutine/cancel.rs index 49185fa56d7..02683c898bf 100644 --- a/src/coroutine/cancel.rs +++ b/src/coroutine/cancel.rs @@ -1,8 +1,9 @@ use crate::{Py, PyAny}; -use std::future::Future; -use std::pin::Pin; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll, Waker}; +use alloc::sync::Arc; +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll, Waker}; +use std::sync::Mutex; #[derive(Debug, Default)] struct Inner { diff --git a/src/coroutine/waker.rs b/src/coroutine/waker.rs index f425545346d..eb9f2b87896 100644 --- a/src/coroutine/waker.rs +++ b/src/coroutine/waker.rs @@ -2,9 +2,9 @@ use crate::sync::PyOnceLock; use crate::types::any::PyAnyMethods; use crate::types::PyCFunction; use crate::{intern, wrap_pyfunction, Bound, Py, PyAny, PyResult, Python}; +use alloc::sync::Arc; +use alloc::task::Wake; use pyo3_macros::pyfunction; -use std::sync::Arc; -use std::task::Wake; /// Lazy `asyncio.Future` wrapper, implementing [`Wake`] by calling `Future.set_result`. /// diff --git a/src/err/cast_error.rs b/src/err/cast_error.rs index 72520123bb2..dd09580f36c 100644 --- a/src/err/cast_error.rs +++ b/src/err/cast_error.rs @@ -1,4 +1,4 @@ -use std::borrow::Cow; +use alloc::borrow::Cow; use crate::{ exceptions, @@ -80,7 +80,7 @@ impl PyErrArguments for CastErrorArguments { } /// Convert `CastError` to Python `TypeError`. -impl std::convert::From> for PyErr { +impl core::convert::From> for PyErr { fn from(err: CastError<'_, '_>) -> PyErr { let args = CastErrorArguments { from: err.from.to_owned().unbind(), @@ -91,10 +91,10 @@ impl std::convert::From> for PyErr { } } -impl std::error::Error for CastError<'_, '_> {} +impl core::error::Error for CastError<'_, '_> {} -impl std::fmt::Display for CastError<'_, '_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for CastError<'_, '_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { DisplayCastError { from: &self.from, classinfo: &self.classinfo, @@ -104,7 +104,7 @@ impl std::fmt::Display for CastError<'_, '_> { } /// Convert `CastIntoError` to Python `TypeError`. -impl std::convert::From> for PyErr { +impl core::convert::From> for PyErr { fn from(err: CastIntoError<'_>) -> PyErr { let args = CastErrorArguments { from: err.from.to_owned().unbind(), @@ -115,10 +115,10 @@ impl std::convert::From> for PyErr { } } -impl std::error::Error for CastIntoError<'_> {} +impl core::error::Error for CastIntoError<'_> {} -impl std::fmt::Display for CastIntoError<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for CastIntoError<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { DisplayCastError { from: &self.from.to_owned(), classinfo: &self.classinfo, @@ -132,8 +132,8 @@ struct DisplayCastError<'a, 'py> { classinfo: &'a Bound<'py, PyAny>, } -impl std::fmt::Display for DisplayCastError<'_, '_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for DisplayCastError<'_, '_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let to = DisplayClassInfo(self.classinfo); if self.from.is_none() { write!(f, "'None' is not an instance of '{to}'") @@ -150,14 +150,14 @@ impl std::fmt::Display for DisplayCastError<'_, '_> { struct DisplayClassInfo<'a, 'py>(&'a Bound<'py, PyAny>); -impl std::fmt::Display for DisplayClassInfo<'_, '_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for DisplayClassInfo<'_, '_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { if let Ok(t) = self.0.cast::() { if t.is(PyNone::type_object(t.py())) { f.write_str("None") } else { t.qualname() - .map_err(|_| std::fmt::Error)? + .map_err(|_| core::fmt::Error)? .to_string_lossy() .fmt(f) } diff --git a/src/err/downcast_error.rs b/src/err/downcast_error.rs index d5c054a0111..8610d7b2a77 100644 --- a/src/err/downcast_error.rs +++ b/src/err/downcast_error.rs @@ -1,6 +1,6 @@ #![allow(deprecated)] -use std::borrow::Cow; +use alloc::borrow::Cow; use crate::{ exceptions, @@ -75,7 +75,7 @@ impl PyErrArguments for DowncastErrorArguments { } /// Convert `CastError` to Python `TypeError`. -impl std::convert::From> for PyErr { +impl core::convert::From> for PyErr { fn from(err: DowncastError<'_, '_>) -> PyErr { let args = DowncastErrorArguments { from: err.from.get_type().into(), @@ -86,16 +86,16 @@ impl std::convert::From> for PyErr { } } -impl std::error::Error for DowncastError<'_, '_> {} +impl core::error::Error for DowncastError<'_, '_> {} -impl std::fmt::Display for DowncastError<'_, '_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for DowncastError<'_, '_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { display_downcast_error(f, &self.from, &self.to) } } /// Convert `DowncastIntoError` to Python `TypeError`. -impl std::convert::From> for PyErr { +impl core::convert::From> for PyErr { fn from(err: DowncastIntoError<'_>) -> PyErr { let args = DowncastErrorArguments { from: err.from.get_type().into(), @@ -106,23 +106,23 @@ impl std::convert::From> for PyErr { } } -impl std::error::Error for DowncastIntoError<'_> {} +impl core::error::Error for DowncastIntoError<'_> {} -impl std::fmt::Display for DowncastIntoError<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for DowncastIntoError<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { display_downcast_error(f, &self.from, &self.to) } } fn display_downcast_error( - f: &mut std::fmt::Formatter<'_>, + f: &mut core::fmt::Formatter<'_>, from: &Bound<'_, PyAny>, to: &str, -) -> std::fmt::Result { +) -> core::fmt::Result { write!( f, "'{}' object cannot be converted to '{}'", - from.get_type().qualname().map_err(|_| std::fmt::Error)?, + from.get_type().qualname().map_err(|_| core::fmt::Error)?, to ) } diff --git a/src/err/err_state.rs b/src/err/err_state.rs index 27d884adf2c..7e0b70b50b3 100644 --- a/src/err/err_state.rs +++ b/src/err/err_state.rs @@ -1,5 +1,5 @@ +use core::cell::UnsafeCell; use std::{ - cell::UnsafeCell, sync::{Mutex, Once}, thread::ThreadId, }; @@ -197,9 +197,9 @@ impl PyErrStateNormalized { #[cfg(not(Py_3_12))] { let (ptype, pvalue, ptraceback) = unsafe { - let mut ptype: *mut ffi::PyObject = std::ptr::null_mut(); - let mut pvalue: *mut ffi::PyObject = std::ptr::null_mut(); - let mut ptraceback: *mut ffi::PyObject = std::ptr::null_mut(); + let mut ptype: *mut ffi::PyObject = core::ptr::null_mut(); + let mut pvalue: *mut ffi::PyObject = core::ptr::null_mut(); + let mut ptraceback: *mut ffi::PyObject = core::ptr::null_mut(); ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback); @@ -318,7 +318,7 @@ impl PyErrStateInner { }) => ( ptype.into_ptr(), pvalue.into_ptr(), - ptraceback.map_or(std::ptr::null_mut(), Py::into_ptr), + ptraceback.map_or(core::ptr::null_mut(), Py::into_ptr), ), }; unsafe { ffi::PyErr_Restore(ptype, pvalue, ptraceback) } @@ -343,9 +343,9 @@ fn lazy_into_normalized_ffi_tuple( // To be consistent with 3.12 logic, go via raise_lazy, but also then normalize // the resulting exception raise_lazy(py, lazy); - let mut ptype = std::ptr::null_mut(); - let mut pvalue = std::ptr::null_mut(); - let mut ptraceback = std::ptr::null_mut(); + let mut ptype = core::ptr::null_mut(); + let mut pvalue = core::ptr::null_mut(); + let mut ptraceback = core::ptr::null_mut(); unsafe { ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback); ffi::PyErr_NormalizeException(&mut ptype, &mut pvalue, &mut ptraceback); @@ -417,7 +417,7 @@ mod tests { // releasing the GIL potentially allows for other threads to deadlock // with the normalization going on here py.detach(|| { - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); }); py.None() } diff --git a/src/err/impls.rs b/src/err/impls.rs index c49c7a56f82..26386c9951c 100644 --- a/src/err/impls.rs +++ b/src/err/impls.rs @@ -1,7 +1,11 @@ +#![allow(unused_imports, reason = "conditional compilation")] + use crate::{err::PyErrArguments, exceptions, PyErr, Python}; use crate::{IntoPyObject, Py, PyAny}; +#[cfg(feature = "std")] use std::io; +#[cfg(feature = "std")] /// Convert `PyErr` to `io::Error` impl From for io::Error { fn from(err: PyErr) -> Self { @@ -43,6 +47,7 @@ impl From for io::Error { /// Create `PyErr` from `io::Error` /// (`OSError` except if the `io::Error` is wrapping a Python exception, /// in this case the exception is returned) +#[cfg(feature = "std")] impl From for PyErr { fn from(err: io::Error) -> PyErr { // If the error wraps a Python error we return it @@ -68,6 +73,7 @@ impl From for PyErr { } } +#[cfg(feature = "std")] impl PyErrArguments for io::Error { fn arguments(self, py: Python<'_>) -> Py { //FIXME(icxolu) remove unwrap @@ -79,20 +85,22 @@ impl PyErrArguments for io::Error { } } +#[cfg(feature = "std")] impl From> for PyErr { fn from(err: io::IntoInnerError) -> PyErr { err.into_error().into() } } +#[cfg(feature = "std")] impl PyErrArguments for io::IntoInnerError { fn arguments(self, py: Python<'_>) -> Py { self.into_error().arguments(py) } } -impl From for PyErr { - fn from(_: std::convert::Infallible) -> PyErr { +impl From for PyErr { + fn from(_: core::convert::Infallible) -> PyErr { unreachable!() } } @@ -110,7 +118,7 @@ macro_rules! impl_to_pyerr { } } - impl std::convert::From<$err> for PyErr { + impl core::convert::From<$err> for PyErr { fn from(err: $err) -> PyErr { <$pyexc>::new_err(err) } @@ -118,31 +126,39 @@ macro_rules! impl_to_pyerr { }; } -impl_to_pyerr!(std::array::TryFromSliceError, exceptions::PyValueError); -impl_to_pyerr!(std::num::ParseIntError, exceptions::PyValueError); -impl_to_pyerr!(std::num::ParseFloatError, exceptions::PyValueError); -impl_to_pyerr!(std::num::TryFromIntError, exceptions::PyValueError); -impl_to_pyerr!(std::str::ParseBoolError, exceptions::PyValueError); -impl_to_pyerr!(std::ffi::IntoStringError, exceptions::PyUnicodeDecodeError); -impl_to_pyerr!(std::ffi::NulError, exceptions::PyValueError); -impl_to_pyerr!(std::str::Utf8Error, exceptions::PyUnicodeDecodeError); -impl_to_pyerr!(std::string::FromUtf8Error, exceptions::PyUnicodeDecodeError); +impl_to_pyerr!(core::array::TryFromSliceError, exceptions::PyValueError); +impl_to_pyerr!(core::num::ParseIntError, exceptions::PyValueError); +impl_to_pyerr!(core::num::ParseFloatError, exceptions::PyValueError); +impl_to_pyerr!(core::num::TryFromIntError, exceptions::PyValueError); +impl_to_pyerr!(core::str::ParseBoolError, exceptions::PyValueError); +impl_to_pyerr!( + alloc::ffi::IntoStringError, + exceptions::PyUnicodeDecodeError +); +impl_to_pyerr!(alloc::ffi::NulError, exceptions::PyValueError); +impl_to_pyerr!(core::str::Utf8Error, exceptions::PyUnicodeDecodeError); +impl_to_pyerr!( + alloc::string::FromUtf8Error, + exceptions::PyUnicodeDecodeError +); impl_to_pyerr!( - std::string::FromUtf16Error, + alloc::string::FromUtf16Error, exceptions::PyUnicodeDecodeError ); impl_to_pyerr!( - std::char::DecodeUtf16Error, + core::char::DecodeUtf16Error, exceptions::PyUnicodeDecodeError ); -impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError); +impl_to_pyerr!(core::net::AddrParseError, exceptions::PyValueError); #[cfg(test)] mod tests { use crate::{PyErr, Python}; + #[cfg(feature = "std")] use std::io; #[test] + #[cfg(feature = "std")] fn io_errors() { use crate::types::any::PyAnyMethods; diff --git a/src/err/mod.rs b/src/err/mod.rs index a4ba53ec072..6abb25a3d44 100644 --- a/src/err/mod.rs +++ b/src/err/mod.rs @@ -17,9 +17,9 @@ use crate::types::{ }; use crate::{exceptions::PyBaseException, ffi}; use crate::{BoundObject, Py, PyAny, Python}; +use core::convert::Infallible; +use core::ffi::CStr; use err_state::{PyErrState, PyErrStateLazyFnOutput, PyErrStateNormalized}; -use std::convert::Infallible; -use std::ffi::CStr; mod cast_error; mod downcast_error; @@ -344,18 +344,18 @@ impl PyErr { dict: Option>, ) -> PyResult> { let base: *mut ffi::PyObject = match base { - None => std::ptr::null_mut(), + None => core::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; let dict: *mut ffi::PyObject = match dict { - None => std::ptr::null_mut(), + None => core::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; let doc_ptr = match doc.as_ref() { Some(c) => c.as_ptr(), - None => std::ptr::null(), + None => core::ptr::null(), }; // SAFETY: correct call to FFI function, return value is known to be a new @@ -388,7 +388,7 @@ impl PyErr { self.value(py).as_ptr(), traceback .as_ref() - .map_or(std::ptr::null_mut(), |traceback| traceback.as_ptr()), + .map_or(core::ptr::null_mut(), |traceback| traceback.as_ptr()), ) } } @@ -472,7 +472,7 @@ impl PyErr { #[inline] pub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>) { self.restore(py); - unsafe { ffi::PyErr_WriteUnraisable(obj.map_or(std::ptr::null_mut(), Bound::as_ptr)) } + unsafe { ffi::PyErr_WriteUnraisable(obj.map_or(core::ptr::null_mut(), Bound::as_ptr)) } } /// Issues a warning message. @@ -530,11 +530,11 @@ impl PyErr { registry: Option<&Bound<'py, PyAny>>, ) -> PyResult<()> { let module_ptr = match module { - None => std::ptr::null_mut(), + None => core::ptr::null_mut(), Some(s) => s.as_ptr(), }; let registry: *mut ffi::PyObject = match registry { - None => std::ptr::null_mut(), + None => core::ptr::null_mut(), Some(obj) => obj.as_ptr(), }; error_on_minusone(py, unsafe { @@ -594,7 +594,7 @@ impl PyErr { // PyException_SetCause _steals_ a reference to cause, so must use .into_ptr() ffi::PyException_SetCause( value.as_ptr(), - cause.map_or(std::ptr::null_mut(), Py::into_ptr), + cause.map_or(core::ptr::null_mut(), Py::into_ptr), ); } } @@ -635,8 +635,8 @@ fn failed_to_fetch() -> PyErr { } } -impl std::fmt::Debug for PyErr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Debug for PyErr { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { Python::attach(|py| { f.debug_struct("PyErr") .field("type", &self.get_type(py)) @@ -660,11 +660,11 @@ impl std::fmt::Debug for PyErr { } } -impl std::fmt::Display for PyErr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for PyErr { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { Python::attach(|py| { let value = self.value(py); - let type_name = value.get_type().qualname().map_err(|_| std::fmt::Error)?; + let type_name = value.get_type().qualname().map_err(|_| core::fmt::Error)?; write!(f, "{type_name}")?; if let Ok(s) = value.str() { write!(f, ": {}", &s.to_string_lossy()) @@ -675,7 +675,7 @@ impl std::fmt::Display for PyErr { } } -impl std::error::Error for PyErr {} +impl core::error::Error for PyErr {} impl<'py> IntoPyObject<'py> for PyErr { type Target = PyBaseException; @@ -713,7 +713,7 @@ impl<'py> IntoPyObject<'py> for &PyErr { /// [`crate::import_exception!`] and [`crate::create_exception!`] macros. pub trait ToPyErr {} -impl<'py, T> std::convert::From> for PyErr +impl<'py, T> core::convert::From> for PyErr where T: ToPyErr, { diff --git a/src/exceptions.rs b/src/exceptions.rs index 5ad34227a94..c87bda896f8 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -10,8 +10,8 @@ //! `BaseException`. use crate::{ffi, Bound, PyResult, Python}; -use std::ffi::CStr; -use std::ops; +use core::ffi::CStr; +use core::ops; /// The boilerplate to convert between a Rust type and a Python exception. #[doc(hidden)] @@ -26,7 +26,7 @@ macro_rules! impl_exception_boilerplate { #[allow(dead_code, reason = "user may not call this function")] pub fn new_err(args: A) -> $crate::PyErr where - A: $crate::PyErrArguments + ::std::marker::Send + ::std::marker::Sync + 'static, + A: $crate::PyErrArguments + ::core::marker::Send + ::core::marker::Sync + 'static, { $crate::PyErr::new::<$name, A>(args) } @@ -82,7 +82,7 @@ macro_rules! import_exception { $name::type_object_raw, stringify!($name), stringify!($module), - #module=::std::option::Option::Some(stringify!($module)) + #module=::core::option::Option::Some(stringify!($module)) ); impl $name { @@ -198,14 +198,14 @@ macro_rules! create_exception { #[macro_export] macro_rules! create_exception_type_object { ($module: expr, $name: ident, $base: ty, None) => { - $crate::create_exception_type_object!($module, $name, $base, ::std::option::Option::None); + $crate::create_exception_type_object!($module, $name, $base, ::core::option::Option::None); }; ($module: expr, $name: ident, $base: ty, Some($doc: expr)) => { $crate::create_exception_type_object!( $module, $name, $base, - ::std::option::Option::Some($crate::ffi::c_str!($doc)) + ::core::option::Option::Some($crate::ffi::c_str!($doc)) ); }; ($module: expr, $name: ident, $base: ty, $doc: expr) => { @@ -214,8 +214,8 @@ macro_rules! create_exception_type_object { // SAFETY: macro caller has upheld the safety contracts unsafe impl $crate::type_object::PyTypeInfo for $name { const NAME: &'static str = stringify!($name); - const MODULE: ::std::option::Option<&'static str> = - ::std::option::Option::Some(stringify!($module)); + const MODULE: ::core::option::Option<&'static str> = + ::core::option::Option::Some(stringify!($module)); $crate::create_exception_type_hint!($module, $name); #[inline] @@ -235,8 +235,8 @@ macro_rules! create_exception_type_object { stringify!($name) )), $doc, - ::std::option::Option::Some(&py.get_type::<$base>()), - ::std::option::Option::None, + ::core::option::Option::Some(&py.get_type::<$base>()), + ::core::option::Option::None, ) .expect("Failed to initialize new exception type.") }) @@ -762,7 +762,7 @@ impl PyUnicodeDecodeError { /// Python::attach(|py| { /// let invalid_utf8 = b"fo\xd8o"; /// # #[expect(invalid_from_utf8)] - /// let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); + /// let err = core::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); /// let decode_err = PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err)?; /// assert_eq!( /// decode_err.to_string(), @@ -774,7 +774,7 @@ impl PyUnicodeDecodeError { pub fn new_utf8<'py>( py: Python<'py>, input: &[u8], - err: std::str::Utf8Error, + err: core::str::Utf8Error, ) -> PyResult> { let pos = err.valid_up_to(); PyUnicodeDecodeError::new(py, c"utf-8", input, pos..(pos + 1), c"invalid utf-8") @@ -1118,7 +1118,7 @@ mod tests { fn unicode_decode_error() { let invalid_utf8 = b"fo\xd8o"; #[expect(invalid_from_utf8)] - let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); + let err = core::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); Python::attach(|py| { let decode_err = PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err).unwrap(); assert_eq!( @@ -1175,7 +1175,7 @@ mod tests { test_exception!(PyUnicodeDecodeError, |py| { let invalid_utf8 = b"fo\xd8o"; #[expect(invalid_from_utf8)] - let err = std::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); + let err = core::str::from_utf8(invalid_utf8).expect_err("should be invalid utf8"); PyErr::from_value( PyUnicodeDecodeError::new_utf8(py, invalid_utf8, err) .unwrap() diff --git a/src/ffi/tests.rs b/src/ffi/tests.rs index 8b5226dd444..fd0cfa5f1ae 100644 --- a/src/ffi/tests.rs +++ b/src/ffi/tests.rs @@ -118,7 +118,7 @@ fn test_timezone_from_offset_and_name() { #[test] #[cfg(not(any(Py_LIMITED_API, GraalPy)))] fn ascii_object_bitfield() { - let ob_base: PyObject = unsafe { std::mem::zeroed() }; + let ob_base: PyObject = unsafe { core::mem::zeroed() }; #[cfg_attr(Py_3_14, allow(unused_mut, unused_variables))] let mut o = PyASCIIObject { @@ -128,7 +128,7 @@ fn ascii_object_bitfield() { hash: 0, state: 0u32, #[cfg(not(Py_3_12))] - wstr: std::ptr::null_mut() as *mut wchar_t, + wstr: core::ptr::null_mut() as *mut wchar_t, }; #[cfg(not(Py_3_14))] diff --git a/src/fmt.rs b/src/fmt.rs index 2b5554182f1..91ba3e0cdd4 100644 --- a/src/fmt.rs +++ b/src/fmt.rs @@ -11,9 +11,9 @@ use { crate::py_result_ext::PyResultExt, crate::IntoPyObject, crate::{ffi, Bound, PyErr, PyResult}, - std::fmt, - std::mem::ManuallyDrop, - std::ptr::NonNull, + core::fmt, + core::mem::ManuallyDrop, + core::ptr::NonNull, }; /// This macro is analogous to Rust's [`format!`] macro, but returns a [`PyString`] instead of a [`String`]. @@ -182,7 +182,7 @@ mod tests { #[allow(clippy::write_literal)] #[cfg(all(Py_3_14, not(Py_LIMITED_API)))] fn unicode_writer_test() { - use std::fmt::Write; + use core::fmt::Write; Python::attach(|py| { let mut writer = PyUnicodeWriter::new(py).unwrap(); write!(writer, "Hello {}!", "world").unwrap(); @@ -196,7 +196,7 @@ mod tests { #[allow(clippy::write_literal)] #[cfg(all(Py_3_14, not(Py_LIMITED_API)))] fn unicode_writer_with_capacity() { - use std::fmt::Write; + use core::fmt::Write; Python::attach(|py| { let mut writer = PyUnicodeWriter::with_capacity(py, 10).unwrap(); write!(writer, "Hello {}!", "world").unwrap(); diff --git a/src/impl_/callback.rs b/src/impl_/callback.rs index 268c6cf2b8a..81dd07d50f8 100644 --- a/src/impl_/callback.rs +++ b/src/impl_/callback.rs @@ -4,7 +4,7 @@ use crate::err::{PyErr, PyResult}; use crate::exceptions::PyOverflowError; use crate::ffi::{self, Py_hash_t}; use crate::{BoundObject, IntoPyObject, Py, PyAny, Python}; -use std::ffi::c_int; +use core::ffi::c_int; /// A type which can be the return type of a python C-API callback pub trait PyCallbackOutput: Copy + py_callback_output::Sealed { @@ -14,7 +14,7 @@ pub trait PyCallbackOutput: Copy + py_callback_output::Sealed { /// Seals `PyCallbackOutput` so that types outside PyO3 cannot implement it. mod py_callback_output { - use std::os::raw::c_int; + use core::ffi::c_int; use pyo3_ffi::Py_ssize_t; @@ -28,10 +28,10 @@ mod py_callback_output { } impl PyCallbackOutput for *mut ffi::PyObject { - const ERR_VALUE: Self = std::ptr::null_mut(); + const ERR_VALUE: Self = core::ptr::null_mut(); } -impl PyCallbackOutput for std::ffi::c_int { +impl PyCallbackOutput for core::ffi::c_int { const ERR_VALUE: Self = -1; } @@ -59,8 +59,8 @@ mod into_py_callback_output { impl<'py, T: IntoPyObject<'py>> Sealed<'py, *mut ffi::PyObject> for T {} impl<'py, T: IntoPyCallbackOutput<'py, U>, E: Into, U> Sealed<'py, U> for Result {} impl Sealed<'_, Self> for *mut ffi::PyObject {} - impl Sealed<'_, std::ffi::c_int> for () {} - impl Sealed<'_, std::ffi::c_int> for bool {} + impl Sealed<'_, core::ffi::c_int> for () {} + impl Sealed<'_, core::ffi::c_int> for bool {} impl Sealed<'_, ()> for () {} impl Sealed<'_, ffi::Py_ssize_t> for usize {} impl Sealed<'_, bool> for bool {} @@ -103,16 +103,16 @@ impl IntoPyCallbackOutput<'_, Self> for *mut ffi::PyObject { } } -impl IntoPyCallbackOutput<'_, std::ffi::c_int> for () { +impl IntoPyCallbackOutput<'_, core::ffi::c_int> for () { #[inline] - fn convert(self, _: Python<'_>) -> PyResult { + fn convert(self, _: Python<'_>) -> PyResult { Ok(0) } } -impl IntoPyCallbackOutput<'_, std::ffi::c_int> for bool { +impl IntoPyCallbackOutput<'_, core::ffi::c_int> for bool { #[inline] - fn convert(self, _: Python<'_>) -> PyResult { + fn convert(self, _: Python<'_>) -> PyResult { Ok(self as c_int) } } diff --git a/src/impl_/coroutine.rs b/src/impl_/coroutine.rs index 0bb2d341a17..59a23eaef53 100644 --- a/src/impl_/coroutine.rs +++ b/src/impl_/coroutine.rs @@ -1,4 +1,4 @@ -use std::future::Future; +use core::future::Future; use crate::{ coroutine::{cancel::ThrowCallback, Coroutine}, diff --git a/src/impl_/extract_argument.rs b/src/impl_/extract_argument.rs index 28d2bdfe636..3936217f407 100644 --- a/src/impl_/extract_argument.rs +++ b/src/impl_/extract_argument.rs @@ -1,4 +1,4 @@ -use std::ptr::NonNull; +use core::ptr::NonNull; #[cfg(feature = "experimental-inspect")] use crate::inspect::{type_hint_union, PyStaticExpr}; @@ -135,8 +135,8 @@ where #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] impl<'a, 'holder, 'py> PyFunctionArgument<'a, 'holder, 'py, false> for &'holder str { - type Holder = Option>; - type Error = as FromPyObject<'a, 'py>>::Error; + type Holder = Option>; + type Error = as FromPyObject<'a, 'py>>::Error; #[cfg(feature = "experimental-inspect")] const INPUT_TYPE: PyStaticExpr = PyString::TYPE_HINT; @@ -144,7 +144,7 @@ impl<'a, 'holder, 'py> PyFunctionArgument<'a, 'holder, 'py, false> for &'holder #[inline] fn extract( obj: Borrowed<'a, 'py, PyAny>, - holder: &'holder mut Option>, + holder: &'holder mut Option>, ) -> PyResult { Ok(holder.insert(obj.extract()?)) } @@ -173,7 +173,7 @@ impl FunctionArgumentHolder for Option { } impl<'a, 'holder, T: PyClass> PyFunctionArgument<'a, 'holder, '_, false> for &'holder T { - type Holder = ::std::option::Option>; + type Holder = ::core::option::Option>; type Error = PyErr; #[cfg(feature = "experimental-inspect")] @@ -188,7 +188,7 @@ impl<'a, 'holder, T: PyClass> PyFunctionArgument<'a, 'holder, '_, false> for &'h impl<'a, 'holder, T: PyClass> PyFunctionArgument<'a, 'holder, '_, false> for &'holder mut T { - type Holder = ::std::option::Option>; + type Holder = ::core::option::Option>; type Error = PyErr; #[cfg(feature = "experimental-inspect")] @@ -303,7 +303,7 @@ pub unsafe fn unwrap_required_argument<'a, 'py>( None => unreachable!("required method argument was not extracted"), // SAFETY: invariant of calling this function. Enforced by the macros. #[cfg(not(debug_assertions))] - None => unsafe { std::hint::unreachable_unchecked() }, + None => unsafe { core::hint::unreachable_unchecked() }, } } @@ -318,7 +318,7 @@ pub unsafe fn unwrap_required_argument_bound<'a, 'py>( None => unreachable!("required method argument was not extracted"), // SAFETY: invariant of calling this function. Enforced by the macros. #[cfg(not(debug_assertions))] - None => unsafe { std::hint::unreachable_unchecked() }, + None => unsafe { core::hint::unreachable_unchecked() }, } } @@ -438,7 +438,7 @@ impl FunctionDescription { let positional_args_to_consume = num_positional_parameters.min(positional_args_provided); let (positional_parameters, remaining) = unsafe { - std::slice::from_raw_parts(args, positional_args_provided) + core::slice::from_raw_parts(args, positional_args_provided) .split_at(positional_args_to_consume) }; output[..positional_args_to_consume].copy_from_slice(positional_parameters); @@ -456,7 +456,7 @@ impl FunctionDescription { }; if let Some(kwnames) = kwnames { let kwargs = unsafe { - ::std::slice::from_raw_parts( + ::core::slice::from_raw_parts( // Safety: PyArg has the same memory layout as `*mut ffi::PyObject` args.offset(nargs).cast::>(), kwnames.len(), @@ -621,7 +621,7 @@ impl FunctionDescription { #[cfg(all(not(Py_3_10), Py_LIMITED_API))] let positional_only_keyword_arguments: Vec<_> = positional_only_keyword_arguments .iter() - .map(std::ops::Deref::deref) + .map(core::ops::Deref::deref) .collect(); return Err(self.positional_only_keyword_arguments(&positional_only_keyword_arguments)); } @@ -1033,7 +1033,7 @@ mod tests { function_description.extract_arguments_tuple_dict::( py, args.as_ptr(), - std::ptr::null_mut(), + core::ptr::null_mut(), &mut output, ) } diff --git a/src/impl_/freelist.rs b/src/impl_/freelist.rs index 713bb3f6464..8e176b07f1c 100644 --- a/src/impl_/freelist.rs +++ b/src/impl_/freelist.rs @@ -9,7 +9,7 @@ //! [1]: https://en.wikipedia.org/wiki/Free_list use crate::ffi; -use std::mem; +use core::mem; /// Represents a slot of a [`PyObjectFreeList`]. enum PyObjectSlot { diff --git a/src/impl_/frompyobject.rs b/src/impl_/frompyobject.rs index 98d7ad6a702..26013035d48 100644 --- a/src/impl_/frompyobject.rs +++ b/src/impl_/frompyobject.rs @@ -17,7 +17,7 @@ pub fn failed_to_extract_enum( error_names.join(" | ") ); for ((variant_name, error_name), error) in variant_names.iter().zip(error_names).zip(errors) { - use std::fmt::Write; + use core::fmt::Write; write!( &mut err_msg, "\n- variant {variant_name} ({error_name}): {error_msg}", @@ -32,7 +32,7 @@ pub fn failed_to_extract_enum( /// Flattens a chain of errors into a single string. fn extract_traceback(py: Python<'_>, mut error: PyErr) -> String { - use std::fmt::Write; + use core::fmt::Write; let mut error_msg = error.to_string(); while let Some(cause) = error.cause(py) { @@ -88,7 +88,7 @@ fn failed_to_extract_struct_field( let new_err = PyTypeError::new_err(format!( "failed to extract field {struct_name}.{field_name}" )); - new_err.set_cause(py, ::std::option::Option::Some(inner_err)); + new_err.set_cause(py, ::core::option::Option::Some(inner_err)); new_err } @@ -136,6 +136,6 @@ fn failed_to_extract_tuple_struct_field( index: usize, ) -> PyErr { let new_err = PyTypeError::new_err(format!("failed to extract field {struct_name}.{index}")); - new_err.set_cause(py, ::std::option::Option::Some(inner_err)); + new_err.set_cause(py, ::core::option::Option::Some(inner_err)); new_err } diff --git a/src/impl_/panic.rs b/src/impl_/panic.rs index 70cdab1ecee..6faec5ed67d 100644 --- a/src/impl_/panic.rs +++ b/src/impl_/panic.rs @@ -15,7 +15,7 @@ impl PanicTrap { #[inline] pub const fn disarm(self) { - std::mem::forget(self) + core::mem::forget(self) } } diff --git a/src/impl_/pyclass.rs b/src/impl_/pyclass.rs index 396c079ac0f..97107fca5dc 100644 --- a/src/impl_/pyclass.rs +++ b/src/impl_/pyclass.rs @@ -13,14 +13,12 @@ use crate::{ Borrowed, IntoPyObject, IntoPyObjectExt, Py, PyAny, PyClass, PyClassGuard, PyErr, PyResult, PyTypeCheck, PyTypeInfo, Python, }; -use std::{ - ffi::CStr, +use core::{ + ffi::{c_int, c_void, CStr}, marker::PhantomData, - os::raw::{c_int, c_void}, ptr::{self, NonNull}, - sync::Mutex, - thread, }; +use std::{sync::Mutex, thread}; mod assertions; pub mod doc; @@ -94,7 +92,7 @@ impl PyClassWeakRef for PyClassDummySlot { pub struct PyClassDictSlot(*mut ffi::PyObject); impl PyClassDict for PyClassDictSlot { - const INIT: Self = Self(std::ptr::null_mut()); + const INIT: Self = Self(core::ptr::null_mut()); #[inline] fn clear_dict(&mut self, _py: Python<'_>) { if !self.0.is_null() { @@ -110,7 +108,7 @@ impl PyClassDict for PyClassDictSlot { pub struct PyClassWeakRefSlot(*mut ffi::PyObject); impl PyClassWeakRef for PyClassWeakRefSlot { - const INIT: Self = Self(std::ptr::null_mut()); + const INIT: Self = Self(core::ptr::null_mut()); #[inline] unsafe fn clear_weakrefs(&mut self, obj: *mut ffi::PyObject, _py: Python<'_>) { if !self.0.is_null() { @@ -360,7 +358,7 @@ macro_rules! generate_pyclass_getattro_slot { _slf: *mut $crate::ffi::PyObject, attr: *mut $crate::ffi::PyObject, ) -> $crate::PyResult<*mut $crate::ffi::PyObject> { - use ::std::result::Result::*; + use ::core::result::Result::*; use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); @@ -444,12 +442,12 @@ macro_rules! define_pyclass_setattr_slot { _slf: *mut $crate::ffi::PyObject, attr: *mut $crate::ffi::PyObject, value: *mut $crate::ffi::PyObject, - ) -> $crate::PyResult<::std::ffi::c_int> { - use ::std::option::Option::*; + ) -> $crate::PyResult<::core::ffi::c_int> { + use ::core::option::Option::*; use $crate::impl_::callback::IntoPyCallbackOutput; use $crate::impl_::pyclass::*; let collector = PyClassImplCollector::<$cls>::new(); - if let Some(value) = ::std::ptr::NonNull::new(value) { + if let Some(value) = ::core::ptr::NonNull::new(value) { unsafe { collector.$set(py, _slf, attr, value).convert(py) } } else { unsafe { collector.$del(py, _slf, attr).convert(py) } @@ -564,7 +562,7 @@ macro_rules! define_pyclass_binary_operator_slot { unsafe { $crate::ffi::Py_DECREF(lhs_result) }; unsafe { collector.$rhs(py, _other, _slf) } } else { - ::std::result::Result::Ok(lhs_result) + ::core::result::Result::Ok(lhs_result) } } @@ -746,7 +744,7 @@ macro_rules! generate_pyclass_pow_slot { unsafe { $crate::ffi::Py_DECREF(lhs_result) }; unsafe { collector.__rpow__(py, _other, _slf, _mod) } } else { - ::std::result::Result::Ok(lhs_result) + ::core::result::Result::Ok(lhs_result) } } @@ -863,7 +861,7 @@ macro_rules! generate_pyclass_richcompare_slot { py: $crate::Python<'_>, slf: *mut $crate::ffi::PyObject, other: *mut $crate::ffi::PyObject, - op: ::std::ffi::c_int, + op: ::core::ffi::c_int, ) -> $crate::PyResult<*mut $crate::ffi::PyObject> { use $crate::class::basic::CompareOp; use $crate::impl_::pyclass::*; @@ -1078,13 +1076,13 @@ impl ThreadCheckerImpl { impl PyClassThreadChecker for ThreadCheckerImpl { fn ensure(&self) { - self.ensure(std::any::type_name::()); + self.ensure(core::any::type_name::()); } fn check(&self) -> bool { self.check() } fn can_drop(&self, py: Python<'_>) -> bool { - self.can_drop(py, std::any::type_name::()) + self.can_drop(py, core::any::type_name::()) } fn new() -> Self { ThreadCheckerImpl(thread::current().id()) @@ -1138,7 +1136,7 @@ pub(crate) unsafe extern "C" fn get_sequence_item_from_mapping( ) -> *mut ffi::PyObject { let index = unsafe { ffi::PyLong_FromSsize_t(index) }; if index.is_null() { - return std::ptr::null_mut(); + return core::ptr::null_mut(); } let result = unsafe { ffi::PyObject_GetItem(obj, index) }; unsafe { ffi::Py_DECREF(index) }; @@ -1177,7 +1175,7 @@ pub enum PyObjectOffset { Relative(ffi::Py_ssize_t), } -impl std::ops::Add for PyObjectOffset { +impl core::ops::Add for PyObjectOffset { type Output = PyObjectOffset; fn add(self, rhs: usize) -> Self::Output { @@ -1461,7 +1459,7 @@ mod tests { use crate::pycell::impl_::PyClassObjectContents; use super::*; - use std::mem::offset_of; + use core::mem::offset_of; #[test] fn get_py_for_frozen_class() { @@ -1557,7 +1555,7 @@ mod tests { { use crate::impl_::pymethods::Getter; - assert!(std::ptr::fn_addr_eq( + assert!(core::ptr::fn_addr_eq( def.meth, pyo3_get_value_into_pyobject_ref:: as Getter )); @@ -1579,7 +1577,7 @@ mod tests { { use crate::impl_::pymethods::Getter; - assert!(std::ptr::fn_addr_eq( + assert!(core::ptr::fn_addr_eq( def.meth, pyo3_get_value_into_pyobject:: as Getter )); @@ -1644,7 +1642,7 @@ mod tests { { use crate::impl_::pymethods::Getter; - assert!(std::ptr::fn_addr_eq( + assert!(core::ptr::fn_addr_eq( def.meth, pyo3_get_value_into_pyobject_ref::, FIELD_OFFSET> as Getter )); diff --git a/src/impl_/pyclass/doc.rs b/src/impl_/pyclass/doc.rs index 7675f38c54c..da8e041beb4 100644 --- a/src/impl_/pyclass/doc.rs +++ b/src/impl_/pyclass/doc.rs @@ -1,4 +1,4 @@ -use std::{ffi::CStr, marker::PhantomData}; +use core::{ffi::CStr, marker::PhantomData}; use crate::{impl_::pyclass::PyClassImpl, PyClass}; @@ -39,20 +39,20 @@ impl PyClassDocGenerator { } /// Casts bytes to a CStr, ensuring they are valid. -pub const fn doc_bytes_as_cstr(bytes: &'static [u8]) -> &'static ::std::ffi::CStr { +pub const fn doc_bytes_as_cstr(bytes: &'static [u8]) -> &'static ::core::ffi::CStr { match CStr::from_bytes_with_nul(bytes) { Ok(cstr) => cstr, #[cfg(not(from_bytes_with_nul_error))] // MSRV 1.86 Err(_) => panic!("invalid pyclass doc"), #[cfg(from_bytes_with_nul_error)] // This case may happen if the user provides an invalid docstring - Err(std::ffi::FromBytesWithNulError::InteriorNul { .. }) => { + Err(core::ffi::FromBytesWithNulError::InteriorNul { .. }) => { panic!("pyclass doc contains nul bytes") } // This case shouldn't happen using the macro machinery as long as `PyClassDocGenerator` // uses the RAW_DOC as the final piece, which is nul terminated. #[cfg(from_bytes_with_nul_error)] - Err(std::ffi::FromBytesWithNulError::NotNulTerminated) => { + Err(core::ffi::FromBytesWithNulError::NotNulTerminated) => { panic!("pyclass doc expected to be nul terminated") } } diff --git a/src/impl_/pyclass/lazy_type_object.rs b/src/impl_/pyclass/lazy_type_object.rs index 63a2a07856f..2e4865aecd3 100644 --- a/src/impl_/pyclass/lazy_type_object.rs +++ b/src/impl_/pyclass/lazy_type_object.rs @@ -1,8 +1,5 @@ -use std::{ - ffi::CStr, - marker::PhantomData, - thread::{self, ThreadId}, -}; +use core::{ffi::CStr, marker::PhantomData}; +use std::thread::{self, ThreadId}; #[cfg(Py_3_14)] use crate::err::error_on_minusone; @@ -207,7 +204,7 @@ impl LazyTypeObjectInner { unsafe { (*type_object.as_type_ptr()).tp_flags.fetch_or( ffi::Py_TPFLAGS_IMMUTABLETYPE, - std::sync::atomic::Ordering::Relaxed, + core::sync::atomic::Ordering::Relaxed, ) }; unsafe { ffi::PyType_Modified(type_object.as_type_ptr()) }; diff --git a/src/impl_/pyclass/probes.rs b/src/impl_/pyclass/probes.rs index b467deb7fe1..3ab484e65df 100644 --- a/src/impl_/pyclass/probes.rs +++ b/src/impl_/pyclass/probes.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; use crate::conversion::IntoPyObject; use crate::impl_::pyclass::PyClassBaseType; diff --git a/src/impl_/pyclass_init.rs b/src/impl_/pyclass_init.rs index a3c9607a83d..dbbf2131ff2 100644 --- a/src/impl_/pyclass_init.rs +++ b/src/impl_/pyclass_init.rs @@ -6,7 +6,7 @@ use crate::internal::get_slot::TP_NEW; use crate::types::{PyTuple, PyType}; use crate::{ffi, PyClass, PyClassInitializer, PyErr, PyResult, Python}; use crate::{ffi::PyTypeObject, sealed::Sealed, type_object::PyTypeInfo}; -use std::marker::PhantomData; +use core::marker::PhantomData; /// Initializer for Python types. /// @@ -46,7 +46,8 @@ impl PyObjectInit for PyNativeTypeInitializer { }; // TODO: make it possible to provide real arguments to the base tp_new - let obj = unsafe { tp_new(subtype, PyTuple::empty(py).as_ptr(), std::ptr::null_mut()) }; + let obj = + unsafe { tp_new(subtype, PyTuple::empty(py).as_ptr(), core::ptr::null_mut()) }; if obj.is_null() { Err(PyErr::fetch(py)) } else { diff --git a/src/impl_/pyfunction.rs b/src/impl_/pyfunction.rs index 1932fab3e6c..6ba4412ceaa 100644 --- a/src/impl_/pyfunction.rs +++ b/src/impl_/pyfunction.rs @@ -1,4 +1,4 @@ -use std::cell::UnsafeCell; +use core::cell::UnsafeCell; use crate::{ ffi, @@ -115,12 +115,12 @@ pub unsafe fn create_py_c_function<'py>( let mod_ptr = m.as_ptr(); (mod_ptr, Some(m.name()?)) } else { - (std::ptr::null_mut(), None) + (core::ptr::null_mut(), None) }; let module_name_ptr = module_name .as_ref() - .map_or(std::ptr::null_mut(), Bound::as_ptr); + .map_or(core::ptr::null_mut(), Bound::as_ptr); unsafe { ffi::PyCFunction_NewEx(method_def, mod_ptr, module_name_ptr) diff --git a/src/impl_/pymethods.rs b/src/impl_/pymethods.rs index ae391637dd7..4698bd12e15 100644 --- a/src/impl_/pymethods.rs +++ b/src/impl_/pymethods.rs @@ -12,12 +12,13 @@ use crate::{ ffi, Bound, CastError, Py, PyAny, PyClass, PyClassGuard, PyClassGuardMut, PyErr, PyRef, PyRefMut, PyResult, PyTraverseError, PyTypeCheck, PyVisit, Python, }; -use std::ffi::CStr; -use std::ffi::{c_int, c_void}; -use std::fmt; -use std::marker::PhantomData; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::ptr::{null_mut, NonNull}; +use core::ffi::CStr; +use core::ffi::{c_int, c_void}; +use core::fmt; +use core::marker::PhantomData; +use core::panic::AssertUnwindSafe; +use core::ptr::{null_mut, NonNull}; +use std::panic::catch_unwind; use super::pyclass::PyClassImpl; use super::trampoline; @@ -31,7 +32,7 @@ pub struct IPowModulo(*mut ffi::PyObject); /// Python 3.7 and older - __ipow__ does not have modulo argument correctly populated. #[cfg(not(Py_3_8))] #[repr(transparent)] -pub struct IPowModulo(#[allow(dead_code)] std::mem::MaybeUninit<*mut ffi::PyObject>); +pub struct IPowModulo(#[allow(dead_code)] core::mem::MaybeUninit<*mut ffi::PyObject>); /// Helper to use as pymethod ffi definition #[allow(non_camel_case_types)] @@ -808,7 +809,7 @@ impl From> for Py { } } -impl<'py, T> std::ops::Deref for BoundRef<'_, 'py, T> { +impl<'py, T> core::ops::Deref for BoundRef<'_, 'py, T> { type Target = Bound<'py, T>; #[inline] fn deref(&self) -> &Self::Target { diff --git a/src/impl_/pymodule.rs b/src/impl_/pymodule.rs index 66749e29d1b..bd8476b5bfb 100644 --- a/src/impl_/pymodule.rs +++ b/src/impl_/pymodule.rs @@ -1,10 +1,9 @@ //! Implementation details of `#[pymodule]` which need to be accessible from proc-macro generated code. -use std::{ +use core::{ cell::UnsafeCell, - ffi::CStr, + ffi::{c_int, c_void, CStr}, marker::PhantomData, - os::raw::{c_int, c_void}, }; #[cfg(all( @@ -12,22 +11,22 @@ use std::{ Py_3_9, not(all(windows, Py_LIMITED_API, not(Py_3_10))), ))] -use std::sync::atomic::Ordering; +use core::sync::atomic::Ordering; #[cfg(all( not(any(PyPy, GraalPy)), Py_3_9, not(all(windows, Py_LIMITED_API, not(Py_3_10))), - not(target_has_atomic = "64"), + target_has_atomic = "64", ))] -use portable_atomic::AtomicI64; +use core::sync::atomic::AtomicI64; #[cfg(all( not(any(PyPy, GraalPy)), Py_3_9, not(all(windows, Py_LIMITED_API, not(Py_3_10))), - target_has_atomic = "64", + not(target_has_atomic = "64"), ))] -use std::sync::atomic::AtomicI64; +use portable_atomic::AtomicI64; #[cfg(not(any(PyPy, GraalPy)))] use crate::exceptions::PyImportError; @@ -71,11 +70,11 @@ impl ModuleDef { #[allow(clippy::declare_interior_mutable_const)] const INIT: ffi::PyModuleDef = ffi::PyModuleDef { m_base: ffi::PyModuleDef_HEAD_INIT, - m_name: std::ptr::null(), - m_doc: std::ptr::null(), + m_name: core::ptr::null(), + m_doc: core::ptr::null(), m_size: 0, - m_methods: std::ptr::null_mut(), - m_slots: std::ptr::null_mut(), + m_methods: core::ptr::null_mut(), + m_slots: core::ptr::null_mut(), m_traverse: None, m_clear: None, m_free: None, @@ -197,7 +196,7 @@ impl PyModuleSlotsBuilder { #[allow(clippy::new_without_default)] pub const fn new() -> Self { Self { - values: [unsafe { std::mem::zeroed() }; N], + values: [unsafe { core::mem::zeroed() }; N], len: 0, } } @@ -317,7 +316,8 @@ impl PyAddToModule for ModuleDef { #[cfg(test)] mod tests { - use std::{borrow::Cow, ffi::CStr, os::raw::c_int}; + use alloc::borrow::Cow; + use core::{ffi::c_int, ffi::CStr}; use crate::{ ffi, diff --git a/src/impl_/trampoline.rs b/src/impl_/trampoline.rs index 607280c8e34..5fed979fe8e 100644 --- a/src/impl_/trampoline.rs +++ b/src/impl_/trampoline.rs @@ -3,11 +3,8 @@ //! They exist to monomorphise std::panic::catch_unwind once into PyO3, rather than inline in every //! function, thus saving a huge amount of compile-time complexity. -use std::{ - any::Any, - os::raw::c_int, - panic::{self, UnwindSafe}, -}; +use core::{any::Any, ffi::c_int, panic::UnwindSafe}; +use std::panic::catch_unwind; use crate::internal::state::AttachGuard; use crate::{ @@ -239,7 +236,7 @@ pub(crate) unsafe fn dealloc( f(py, slf); Ok(()) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) } } @@ -272,10 +269,8 @@ where // SAFETY: This function requires the thread to already be attached. let guard = unsafe { AttachGuard::assume() }; let py = guard.python(); - let out = panic_result_into_callback_output( - py, - panic::catch_unwind(move || -> PyResult<_> { body(py) }), - ); + let out = + panic_result_into_callback_output(py, catch_unwind(move || -> PyResult<_> { body(py) })); trap.disarm(); out } @@ -321,7 +316,7 @@ where let guard = unsafe { AttachGuard::assume() }; let py = guard.python(); - if let Err(py_err) = panic::catch_unwind(move || body(py)) + if let Err(py_err) = catch_unwind(move || body(py)) .unwrap_or_else(|payload| Err(PanicException::from_panic_payload(payload))) { py_err.write_unraisable(py, unsafe { ctx.assume_borrowed_or_opt(py) }.as_deref()); diff --git a/src/impl_/unindent.rs b/src/impl_/unindent.rs index ed35cf3ba6f..ba20f9b7a7f 100644 --- a/src/impl_/unindent.rs +++ b/src/impl_/unindent.rs @@ -236,7 +236,7 @@ no indent const INDENTED: &str = SAMPLE_1_WITH_FIRST_LINE; const LEN: usize = INDENTED.len(); let (unindented, unindented_size) = unindent_sized::(INDENTED.as_bytes()); - let unindented = std::str::from_utf8(&unindented[..unindented_size]).unwrap(); + let unindented = core::str::from_utf8(&unindented[..unindented_size]).unwrap(); assert_eq!(unindented, UNINDENTED_1); } diff --git a/src/impl_/wrap.rs b/src/impl_/wrap.rs index f16f00da091..57d923ecb31 100644 --- a/src/impl_/wrap.rs +++ b/src/impl_/wrap.rs @@ -1,4 +1,4 @@ -use std::{convert::Infallible, marker::PhantomData, ops::Deref}; +use core::{convert::Infallible, marker::PhantomData, ops::Deref}; use crate::{ ffi, types::PyNone, Bound, IntoPyObject, IntoPyObjectExt, Py, PyAny, PyResult, Python, diff --git a/src/inspect/mod.rs b/src/inspect/mod.rs index b4f73291ea8..4f065dff2f7 100644 --- a/src/inspect/mod.rs +++ b/src/inspect/mod.rs @@ -3,7 +3,7 @@ //! Tracking issue: . use crate::impl_::introspection::{escape_json_string, escaped_json_string_len}; -use std::fmt::{self, Display, Write}; +use core::fmt::{self, Display, Write}; pub mod types; @@ -478,7 +478,7 @@ mod tests { fn check_serialization(expr: PyStaticExpr, expected: &str) { let mut out = vec![0; serialized_len_for_introspection(&expr)]; serialize_for_introspection(&expr, &mut out); - assert_eq!(std::str::from_utf8(&out).unwrap(), expected) + assert_eq!(core::str::from_utf8(&out).unwrap(), expected) } check_serialization( diff --git a/src/inspect/types.rs b/src/inspect/types.rs index a26ec4beb8e..9c6e7f00b6b 100644 --- a/src/inspect/types.rs +++ b/src/inspect/types.rs @@ -1,7 +1,7 @@ //! Data types used to describe runtime Python types. -use std::borrow::Cow; -use std::fmt::{Display, Formatter}; +use alloc::borrow::Cow; +use core::fmt::{Display, Formatter}; /// Designation of a Python type. /// @@ -199,7 +199,7 @@ impl TypeInfo { } impl Display for TypeInfo { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { match self { TypeInfo::Any | TypeInfo::None | TypeInfo::NoReturn => write!(f, "{}", self.name()), TypeInfo::Callable(input, output) => { @@ -273,7 +273,7 @@ impl Display for TypeInfo { #[cfg(test)] mod test { - use std::borrow::Cow; + use alloc::borrow::Cow; use crate::inspect::types::{ModuleName, TypeInfo}; @@ -403,7 +403,7 @@ mod test { #[cfg(test)] mod conversion { - use std::collections::{HashMap, HashSet}; + use alloc::collections::{BTreeMap, BTreeSet}; use crate::inspect::types::test::assert_display; use crate::{FromPyObject, IntoPyObject}; @@ -477,11 +477,11 @@ mod conversion { assert_display(&>::type_output(), "List[int]"); assert_display(&>::type_input(), "Sequence[int]"); - assert_display(&>::type_output(), "Set[int]"); - assert_display(&>::type_input(), "Set[int]"); + assert_display(&>::type_output(), "Set[int]"); + assert_display(&>::type_input(), "Set[int]"); - assert_display(&>::type_output(), "Dict[int, float]"); - assert_display(&>::type_input(), "Mapping[int, float]"); + assert_display(&>::type_output(), "Dict[int, float]"); + assert_display(&>::type_input(), "Mapping[int, float]"); assert_display(&<(usize, f32)>::type_input(), "Tuple[int, float]"); } diff --git a/src/instance.rs b/src/instance.rs index aea48d8e22b..09b8c70e633 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -18,11 +18,11 @@ use crate::{ PyRefMut, PyTypeInfo, Python, }; use crate::{internal::state, PyTypeCheck}; -use std::marker::PhantomData; -use std::mem::ManuallyDrop; -use std::ops::Deref; -use std::ptr; -use std::ptr::NonNull; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::ops::Deref; +use core::ptr; +use core::ptr::NonNull; /// Owned or borrowed Python smart pointer with a lifetime `'py` signalling /// attachment to the Python interpreter. @@ -328,7 +328,7 @@ impl<'py, T> Bound<'py, T> { #[inline] pub unsafe fn cast_into_unchecked(self) -> Bound<'py, U> { // SAFETY: caller has upheld the safety contract, all `Bound` have the same layout - unsafe { std::mem::transmute(self) } + unsafe { core::mem::transmute(self) } } } @@ -625,7 +625,7 @@ where /// # Examples /// /// ``` - /// use std::sync::atomic::{AtomicUsize, Ordering}; + /// use core::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] @@ -759,15 +759,15 @@ where } } -impl std::fmt::Debug for Bound<'_, T> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Debug for Bound<'_, T> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { let any = self.as_any(); python_format(any, any.repr(), f) } } -impl std::fmt::Display for Bound<'_, T> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for Bound<'_, T> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { let any = self.as_any(); python_format(any, any.str(), f) } @@ -776,15 +776,15 @@ impl std::fmt::Display for Bound<'_, T> { fn python_format( any: &Bound<'_, PyAny>, format_result: PyResult>, - f: &mut std::fmt::Formatter<'_>, -) -> Result<(), std::fmt::Error> { + f: &mut core::fmt::Formatter<'_>, +) -> Result<(), core::fmt::Error> { match format_result { Result::Ok(s) => return f.write_str(&s.to_string_lossy()), Result::Err(err) => err.write_unraisable(any.py(), Some(any)), } match any.get_type().name() { - Result::Ok(name) => std::write!(f, ""), + Result::Ok(name) => core::write!(f, ""), Result::Err(_err) => f.write_str(""), } } @@ -1083,7 +1083,7 @@ impl<'a, 'py, T> Borrowed<'a, 'py, T> { /// # Examples /// /// ``` - /// use std::sync::atomic::{AtomicUsize, Ordering}; + /// use core::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] @@ -1131,7 +1131,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// # Safety /// /// - `ptr` must be a valid pointer to a Python object (or null, which will cause a panic) - /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by + /// - similar to `core::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. /// @@ -1154,7 +1154,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null - /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by + /// - similar to `core::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] @@ -1173,7 +1173,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// # Safety /// /// - `ptr` must be a valid pointer to a Python object, or null - /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by + /// - similar to `core::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] @@ -1192,7 +1192,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// # Safety /// /// - `ptr` must be a valid pointer to a Python object. It must not be null. - /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by + /// - similar to `core::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] @@ -1204,7 +1204,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { /// # Safety /// /// - `ptr` must be a valid pointer to a Python object. - /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by + /// - similar to `core::slice::from_raw_parts`, the lifetime `'a` is completely defined by /// the caller and it is the caller's responsibility to ensure that the reference this is /// derived from is valid for the lifetime `'a`. #[inline] @@ -1228,8 +1228,8 @@ impl AsRef> for Borrowed<'_, '_, T> { } } -impl std::fmt::Debug for Borrowed<'_, '_, T> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for Borrowed<'_, '_, T> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { Bound::fmt(self, f) } } @@ -1690,7 +1690,7 @@ where /// # Examples /// /// ``` - /// use std::sync::atomic::{AtomicUsize, Ordering}; + /// use core::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] @@ -2161,7 +2161,7 @@ impl AsRef> for Py { } } -impl std::convert::From> for Py +impl core::convert::From> for Py where T: DerefToPyAny, { @@ -2171,7 +2171,7 @@ where } } -impl std::convert::From> for Py +impl core::convert::From> for Py where T: DerefToPyAny, { @@ -2181,20 +2181,20 @@ where } } -impl std::convert::From> for Py { +impl core::convert::From> for Py { #[inline] fn from(other: Bound<'_, T>) -> Self { other.unbind() } } -impl std::convert::From> for Py { +impl core::convert::From> for Py { fn from(value: Borrowed<'_, '_, T>) -> Self { value.unbind() } } -impl<'py, T> std::convert::From> for Py +impl<'py, T> core::convert::From> for Py where T: PyClass, { @@ -2205,7 +2205,7 @@ where } } -impl<'py, T> std::convert::From> for Py +impl<'py, T> core::convert::From> for Py where T: PyClass, { @@ -2316,17 +2316,17 @@ where } } -impl std::fmt::Display for Py +impl core::fmt::Display for Py where T: PyTypeInfo, { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - Python::attach(|py| std::fmt::Display::fmt(self.bind(py), f)) + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + Python::attach(|py| core::fmt::Display::fmt(self.bind(py), f)) } } -impl std::fmt::Debug for Py { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for Py { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Py").field(&self.0.as_ptr()).finish() } } @@ -2496,7 +2496,7 @@ mod tests { use crate::test_utils::UnraisableCapture; use crate::types::{dict::IntoPyDict, PyAnyMethods, PyCapsule, PyDict, PyString}; use crate::{ffi, Borrowed, IntoPyObjectExt, PyAny, PyResult, Python}; - use std::ffi::CStr; + use core::ffi::CStr; #[test] fn test_call() { @@ -2757,7 +2757,7 @@ a = A() py, (&mut dropped) as *mut _ as usize, None, - |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, + |ptr, _| unsafe { core::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); @@ -2799,7 +2799,7 @@ a = A() py, (&mut dropped) as *mut _ as usize, None, - |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, + |ptr, _| unsafe { core::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); @@ -2854,7 +2854,7 @@ a = A() #[test] fn test_constructors_panic_on_null() { Python::attach(|py| { - const NULL: *mut ffi::PyObject = std::ptr::null_mut(); + const NULL: *mut ffi::PyObject = core::ptr::null_mut(); #[expect(deprecated, reason = "Py constructors")] // SAFETY: calling all constructors with null pointer to test panic behavior diff --git a/src/internal/get_slot.rs b/src/internal/get_slot.rs index d6f210d69a4..d4423acd089 100644 --- a/src/internal/get_slot.rs +++ b/src/internal/get_slot.rs @@ -3,7 +3,7 @@ use crate::{ types::{PyType, PyTypeMethods}, Borrowed, Bound, }; -use std::ffi::c_int; +use core::ffi::c_int; impl Bound<'_, PyType> { #[inline] @@ -114,7 +114,7 @@ macro_rules! impl_slots { } // SAFETY: slot type is set carefully to be valid - unsafe {std::mem::transmute(ffi::PyType_GetSlot(ty, ffi::$slot))} + unsafe {core::mem::transmute(ffi::PyType_GetSlot(ty, ffi::$slot))} } } } @@ -161,7 +161,7 @@ pub struct PyNumberMethods39Snapshot { pub nb_xor: Option, pub nb_or: Option, pub nb_int: Option, - pub nb_reserved: *mut std::ffi::c_void, + pub nb_reserved: *mut core::ffi::c_void, pub nb_float: Option, pub nb_inplace_add: Option, pub nb_inplace_subtract: Option, @@ -189,9 +189,9 @@ pub struct PySequenceMethods39Snapshot { pub sq_concat: Option, pub sq_repeat: Option, pub sq_item: Option, - pub was_sq_slice: *mut std::ffi::c_void, + pub was_sq_slice: *mut core::ffi::c_void, pub sq_ass_item: Option, - pub was_sq_ass_slice: *mut std::ffi::c_void, + pub was_sq_ass_slice: *mut core::ffi::c_void, pub sq_contains: Option, pub sq_inplace_concat: Option, pub sq_inplace_repeat: Option, @@ -217,8 +217,8 @@ pub struct PyAsyncMethods39Snapshot { #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] pub struct PyBufferProcs39Snapshot { // not available in limited api, but structure needs to have the right size - pub bf_getbuffer: *mut std::ffi::c_void, - pub bf_releasebuffer: *mut std::ffi::c_void, + pub bf_getbuffer: *mut core::ffi::c_void, + pub bf_releasebuffer: *mut core::ffi::c_void, } /// Snapshot of the structure of PyTypeObject for Python 3.7 through 3.9. @@ -230,12 +230,12 @@ pub struct PyBufferProcs39Snapshot { #[cfg(all(Py_LIMITED_API, not(Py_3_10)))] struct PyTypeObject39Snapshot { pub ob_base: ffi::PyVarObject, - pub tp_name: *const std::ffi::c_char, + pub tp_name: *const core::ffi::c_char, pub tp_basicsize: ffi::Py_ssize_t, pub tp_itemsize: ffi::Py_ssize_t, pub tp_dealloc: Option, #[cfg(not(Py_3_8))] - pub tp_print: *mut std::ffi::c_void, // stubbed out, not available in limited API + pub tp_print: *mut core::ffi::c_void, // stubbed out, not available in limited API #[cfg(Py_3_8)] pub tp_vectorcall_offset: ffi::Py_ssize_t, pub tp_getattr: Option, @@ -251,8 +251,8 @@ struct PyTypeObject39Snapshot { pub tp_getattro: Option, pub tp_setattro: Option, pub tp_as_buffer: *mut PyBufferProcs39Snapshot, - pub tp_flags: std::ffi::c_ulong, - pub tp_doc: *const std::ffi::c_char, + pub tp_flags: core::ffi::c_ulong, + pub tp_doc: *const core::ffi::c_char, pub tp_traverse: Option, pub tp_clear: Option, pub tp_richcompare: Option, @@ -278,7 +278,7 @@ struct PyTypeObject39Snapshot { pub tp_subclasses: *mut ffi::PyObject, pub tp_weaklist: *mut ffi::PyObject, pub tp_del: Option, - pub tp_version_tag: std::ffi::c_uint, + pub tp_version_tag: core::ffi::c_uint, pub tp_finalize: Option, #[cfg(Py_3_8)] pub tp_vectorcall: Option, diff --git a/src/internal/state.rs b/src/internal/state.rs index 626d0f08c33..04401c4c339 100644 --- a/src/internal/state.rs +++ b/src/internal/state.rs @@ -4,11 +4,13 @@ use crate::impl_::panic::PanicTrap; use crate::{ffi, Python}; -use std::cell::Cell; +use core::cell::Cell; +#[cfg_attr(pyo3_disable_reference_pool, allow(unused_imports))] +use core::{mem, ptr::NonNull}; +#[cfg_attr(pyo3_disable_reference_pool, allow(unused_imports))] +use std::sync::Mutex; #[cfg(not(pyo3_disable_reference_pool))] use std::sync::OnceLock; -#[cfg_attr(pyo3_disable_reference_pool, allow(unused_imports))] -use std::{mem, ptr::NonNull, sync}; std::thread_local! { /// This is an internal counter in pyo3 monitoring whether this thread is attached to the interpreter. @@ -181,14 +183,14 @@ type PyObjVec = Vec>; #[cfg(not(pyo3_disable_reference_pool))] /// Thread-safe storage for objects which were dec_ref while not attached. struct ReferencePool { - pending_decrefs: sync::Mutex, + pending_decrefs: Mutex, } #[cfg(not(pyo3_disable_reference_pool))] impl ReferencePool { const fn new() -> Self { Self { - pending_decrefs: sync::Mutex::new(Vec::new()), + pending_decrefs: Mutex::new(Vec::new()), } } @@ -551,7 +553,7 @@ mod tests { Bound::from_owned_ptr( pool.python(), - ffi::PyCapsule_GetPointer(capsule, std::ptr::null()) as _, + ffi::PyCapsule_GetPointer(capsule, core::ptr::null()) as _, ) }; } @@ -559,7 +561,7 @@ mod tests { let ptr = obj.into_ptr(); let capsule = - unsafe { ffi::PyCapsule_New(ptr as _, std::ptr::null(), Some(capsule_drop)) }; + unsafe { ffi::PyCapsule_New(ptr as _, core::ptr::null(), Some(capsule_drop)) }; get_pool().register_decref(NonNull::new(capsule).unwrap()); diff --git a/src/internal_tricks.rs b/src/internal_tricks.rs index 8009d1f47ad..502654bee37 100644 --- a/src/internal_tricks.rs +++ b/src/internal_tricks.rs @@ -24,7 +24,7 @@ pub(crate) fn clear_eq(f: Option, g: ffi::inquiry) -> bool { #[expect(clippy::incompatible_msrv, reason = "guarded by cfg(fn_ptr_eq)")] { let Some(f) = f else { return false }; - std::ptr::fn_addr_eq(f, g) + core::ptr::fn_addr_eq(f, g) } #[cfg(not(fn_ptr_eq))] @@ -39,7 +39,7 @@ pub(crate) fn traverse_eq(f: Option, g: ffi::traverseproc) -> #[expect(clippy::incompatible_msrv, reason = "guarded by cfg(fn_ptr_eq)")] { let Some(f) = f else { return false }; - std::ptr::fn_addr_eq(f, g) + core::ptr::fn_addr_eq(f, g) } #[cfg(not(fn_ptr_eq))] diff --git a/src/lib.rs b/src/lib.rs index 3e87cbcc779..dc10f27f654 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ #![warn(missing_docs)] +#![warn(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] #![cfg_attr( feature = "nightly", feature(auto_traits, negative_impls, try_trait_v2, iter_advance_by) @@ -336,6 +337,11 @@ //! [Rust from Python]: https://github.com/PyO3/pyo3#using-rust-from-python #![doc = concat!("[Features chapter of the guide]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/features.html#features-reference \"Features Reference - PyO3 user guide\"")] //! [`Ungil`]: crate::marker::Ungil + +extern crate alloc; +#[cfg(feature = "std")] +extern crate std; + pub use crate::class::*; pub use crate::conversion::{FromPyObject, IntoPyObject, IntoPyObjectExt}; pub use crate::err::{CastError, CastIntoError, PyErr, PyErrArguments, PyResult, ToPyErr}; @@ -470,7 +476,7 @@ pub mod inspect; pub mod prelude; /// Test readme and user guide -#[cfg(doctest)] +#[cfg(all(doctest, feature = "std"))] pub mod doc_test { macro_rules! doctests { ($($path:expr => $mod:ident),* $(,)?) => { diff --git a/src/macros.rs b/src/macros.rs index 1f21fcd6718..3bfe965ce75 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -117,15 +117,16 @@ macro_rules! py_run_impl { $crate::py_run_impl!($py, *d, $code) }}; ($py:expr, *$dict:expr, $code:expr) => {{ - use ::std::option::Option::*; - if let ::std::result::Result::Err(e) = $py.run(&::std::ffi::CString::new($code).unwrap(), None, Some(&$dict)) { + extern crate alloc; + use ::core::option::Option::*; + if let ::core::result::Result::Err(e) = $py.run(&alloc::ffi::CString::new($code).unwrap(), None, Some(&$dict)) { e.print($py); // So when this c api function the last line called printed the error to stderr, // the output is only written into a buffer which is never flushed because we // panic before flushing. This is where this hack comes into place $py.run(c"import sys; sys.stderr.flush()", None, None) .unwrap(); - ::std::panic!("{}", $code) + ::core::panic!("{}", $code) } }}; } @@ -183,13 +184,13 @@ macro_rules! append_to_inittab { ($module:ident) => { unsafe { if $crate::ffi::Py_IsInitialized() != 0 { - ::std::panic!( + ::core::panic!( "called `append_to_inittab` but a Python interpreter is already running." ); } $crate::ffi::PyImport_AppendInittab( $module::__PYO3_NAME.as_ptr(), - ::std::option::Option::Some($module::__pyo3_init), + ::core::option::Option::Some($module::__pyo3_init), ); } }; diff --git a/src/marker.rs b/src/marker.rs index 24604e87f25..480fc8a887c 100644 --- a/src/marker.rs +++ b/src/marker.rs @@ -126,8 +126,8 @@ use crate::types::{ }; use crate::version::PythonVersionInfo; use crate::{ffi, Bound, Py, PyTypeInfo}; -use std::ffi::CStr; -use std::marker::PhantomData; +use core::ffi::CStr; +use core::marker::PhantomData; /// Types that are safe to access while the GIL is not held. /// @@ -145,7 +145,7 @@ use std::marker::PhantomData; /// /// ```compile_fail /// # use pyo3::prelude::*; -/// use std::rc::Rc; +/// use alloc::rc::Rc; /// /// Python::attach(|py| { /// let rc = Rc::new(42); @@ -844,7 +844,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled fn test_detach_releases_and_acquires_gil() { Python::attach(|py| { - let b = std::sync::Arc::new(std::sync::Barrier::new(2)); + let b = alloc::sync::Arc::new(std::sync::Barrier::new(2)); let b2 = b.clone(); std::thread::spawn(move || Python::attach(|_| b2.wait())); @@ -890,7 +890,7 @@ mod tests { fn test_detach_pass_stuff_in() { let list = Python::attach(|py| PyList::new(py, vec!["foo", "bar"]).unwrap().unbind()); let mut v = vec![1, 2, 3]; - let a = std::sync::Arc::new(String::from("foo")); + let a = alloc::sync::Arc::new(String::from("foo")); Python::attach(|py| { py.detach(|| { @@ -902,7 +902,7 @@ mod tests { #[test] #[cfg(not(Py_LIMITED_API))] fn test_acquire_gil() { - use std::ffi::c_int; + use core::ffi::c_int; const GIL_NOT_HELD: c_int = 0; const GIL_HELD: c_int = 1; @@ -961,7 +961,7 @@ mod tests { #[cfg(feature = "macros")] #[test] fn test_py_run_inserts_globals_2() { - use std::ffi::CString; + use alloc::ffi::CString; #[crate::pyclass(crate = "crate", skip_from_py_object)] #[derive(Clone)] @@ -1004,7 +1004,7 @@ cls.func() #[test] fn python_is_zst() { - assert_eq!(std::mem::size_of::>(), 0); + assert_eq!(core::mem::size_of::>(), 0); } #[test] diff --git a/src/marshal.rs b/src/marshal.rs index 6866a7cc1c0..600d482763b 100644 --- a/src/marshal.rs +++ b/src/marshal.rs @@ -7,7 +7,7 @@ use crate::py_result_ext::PyResultExt; use crate::types::{PyAny, PyBytes}; use crate::{ffi, Bound}; use crate::{PyResult, Python}; -use std::ffi::c_int; +use core::ffi::c_int; /// The current version of the marshal binary format. pub const VERSION: i32 = 4; diff --git a/src/panic.rs b/src/panic.rs index 50489d50aeb..8a8c8e73b4b 100644 --- a/src/panic.rs +++ b/src/panic.rs @@ -1,7 +1,7 @@ //! Helper to convert Rust panics to Python exceptions. use crate::exceptions::PyBaseException; use crate::PyErr; -use std::any::Any; +use core::any::Any; pyo3_exception!( " diff --git a/src/pybacked.rs b/src/pybacked.rs index d7feaa2bfa2..f6ec046698e 100644 --- a/src/pybacked.rs +++ b/src/pybacked.rs @@ -11,7 +11,8 @@ use crate::{ }, Borrowed, Bound, CastError, FromPyObject, IntoPyObject, Py, PyAny, PyErr, PyTypeInfo, Python, }; -use std::{borrow::Borrow, convert::Infallible, ops::Deref, ptr::NonNull, sync::Arc}; +use alloc::{borrow::Borrow, sync::Arc}; +use core::{convert::Infallible, ops::Deref, ptr::NonNull}; /// An equivalent to `String` where the storage is owned by a Python `bytes` or `str` object. /// @@ -91,9 +92,9 @@ impl Borrow for PyBackedStr { unsafe impl Send for PyBackedStr {} unsafe impl Sync for PyBackedStr {} -impl std::fmt::Display for PyBackedStr { +impl core::fmt::Display for PyBackedStr { #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.deref().fmt(f) } } @@ -115,7 +116,7 @@ impl TryFrom> for PyBackedStr { #[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))] { let bytes = py_string.encode_utf8()?; - let s = unsafe { std::str::from_utf8_unchecked(bytes.as_bytes()) }; + let s = unsafe { core::str::from_utf8_unchecked(bytes.as_bytes()) }; let data = NonNull::from(s); Ok(Self { storage: bytes.unbind(), @@ -338,9 +339,9 @@ impl<'py> IntoPyObject<'py> for &PyBackedBytes { macro_rules! impl_traits { ($slf:ty, $equiv:ty) => { - impl std::fmt::Debug for $slf { + impl core::fmt::Debug for $slf { #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.deref().fmt(f) } } @@ -384,35 +385,35 @@ macro_rules! impl_traits { impl PartialOrd for $slf { #[inline] - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialOrd<$equiv> for $slf { #[inline] - fn partial_cmp(&self, other: &$equiv) -> Option { + fn partial_cmp(&self, other: &$equiv) -> Option { self.deref().partial_cmp(other) } } impl PartialOrd<$slf> for $equiv { #[inline] - fn partial_cmp(&self, other: &$slf) -> Option { + fn partial_cmp(&self, other: &$slf) -> Option { self.partial_cmp(other.deref()) } } impl Ord for $slf { #[inline] - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.deref().cmp(other.deref()) } } - impl std::hash::Hash for $slf { + impl core::hash::Hash for $slf { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.deref().hash(state) } } @@ -426,8 +427,8 @@ mod test { use crate::impl_::pyclass::{value_of, IsSend, IsSync}; use crate::types::PyAnyMethods as _; use crate::{IntoPyObject, Python}; + use core::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; #[test] fn py_backed_str_empty() { diff --git a/src/pycell.rs b/src/pycell.rs index 80c922114b4..6ae211604bc 100644 --- a/src/pycell.rs +++ b/src/pycell.rs @@ -125,7 +125,7 @@ //! # } //! #[pyfunction] //! fn swap_numbers(a: &mut Number, b: &mut Number) { -//! std::mem::swap(&mut a.inner, &mut b.inner); +//! core::mem::swap(&mut a.inner, &mut b.inner); //! } //! # fn main() { //! # Python::attach(|py| { @@ -159,7 +159,7 @@ //! fn swap_numbers(a: &PyCell, b: &PyCell) { //! // Check that the pointers are unequal //! if !a.is(b) { -//! std::mem::swap(&mut a.borrow_mut().inner, &mut b.borrow_mut().inner); +//! core::mem::swap(&mut a.borrow_mut().inner, &mut b.borrow_mut().inner); //! } else { //! // Do nothing - they are the same object, so don't need swapping. //! } @@ -198,11 +198,11 @@ use crate::exceptions::PyRuntimeError; use crate::ffi_ptr_ext::FfiPtrExt; use crate::pyclass::{boolean_struct::False, PyClass}; use crate::{ffi, Borrowed, Bound, PyErr, Python}; -use std::convert::Infallible; -use std::fmt; -use std::mem::ManuallyDrop; -use std::ops::{Deref, DerefMut}; -use std::ptr::NonNull; +use core::convert::Infallible; +use core::fmt; +use core::mem::ManuallyDrop; +use core::ops::{Deref, DerefMut}; +use core::ptr::NonNull; pub(crate) mod impl_; #[cfg(feature = "experimental-inspect")] diff --git a/src/pycell/impl_.rs b/src/pycell/impl_.rs index 276eaafc600..84998527abe 100644 --- a/src/pycell/impl_.rs +++ b/src/pycell/impl_.rs @@ -1,11 +1,11 @@ #![allow(missing_docs)] //! Crate-private implementation of PyClassObject -use std::cell::UnsafeCell; -use std::marker::PhantomData; -use std::mem::{offset_of, ManuallyDrop, MaybeUninit}; -use std::ptr::addr_of_mut; -use std::sync::atomic::{AtomicUsize, Ordering}; +use core::cell::UnsafeCell; +use core::marker::PhantomData; +use core::mem::{offset_of, ManuallyDrop, MaybeUninit}; +use core::ptr::addr_of_mut; +use core::sync::atomic::{AtomicUsize, Ordering}; use crate::impl_::pyclass::{ PyClassBaseType, PyClassDict, PyClassImpl, PyClassThreadChecker, PyClassWeakRef, PyObjectOffset, @@ -265,7 +265,7 @@ unsafe fn tp_dealloc(slf: *mut ffi::PyObject, type_obj: &crate::Bound<'_, PyType let actual_type = PyType::from_borrowed_type_ptr(py, ffi::Py_TYPE(slf)); // For `#[pyclass]` types which inherit from PyAny, we can just call tp_free - if std::ptr::eq(type_ptr, std::ptr::addr_of!(ffi::PyBaseObject_Type)) { + if core::ptr::eq(type_ptr, core::ptr::addr_of!(ffi::PyBaseObject_Type)) { let tp_free = actual_type .get_slot(TP_FREE) .expect("PyBaseObject_Type should have tp_free"); @@ -390,7 +390,7 @@ impl> PyClassObjectLayout for PyStaticClassObje }; const BASIC_SIZE: ffi::Py_ssize_t = { - let size = std::mem::size_of::(); + let size = core::mem::size_of::(); assert!(size <= ffi::Py_ssize_t::MAX as usize); size as _ }; @@ -505,7 +505,7 @@ impl> PyClassObjectLayout for PyVariableClassObject /// Gets the offset of the contents from the start of the struct in bytes. const CONTENTS_OFFSET: PyObjectOffset = PyObjectOffset::Relative(0); const BASIC_SIZE: ffi::Py_ssize_t = { - let size = std::mem::size_of::>(); + let size = core::mem::size_of::>(); assert!(size <= ffi::Py_ssize_t::MAX as usize); // negative to indicate 'extra' space that cpython will allocate for us -(size as ffi::Py_ssize_t) diff --git a/src/pyclass.rs b/src/pyclass.rs index e68932bc55a..0138fdb90c1 100644 --- a/src/pyclass.rs +++ b/src/pyclass.rs @@ -1,6 +1,6 @@ //! `PyClass` and related traits. use crate::{ffi, impl_::pyclass::PyClassImpl, PyTypeInfo}; -use std::{cmp::Ordering, os::raw::c_int}; +use core::{cmp::Ordering, ffi::c_int}; mod create_type_object; mod gc; @@ -60,7 +60,7 @@ impl CompareOp { } } - /// Returns if a Rust [`std::cmp::Ordering`] matches this ordering query. + /// Returns if a Rust [`core::cmp::Ordering`] matches this ordering query. /// /// Usage example: /// @@ -128,7 +128,7 @@ mod tests { #[test] fn test_compare_op_matches() { use super::CompareOp; - use std::cmp::Ordering; + use core::cmp::Ordering; assert!(CompareOp::Eq.matches(Ordering::Equal)); assert!(CompareOp::Ne.matches(Ordering::Less)); diff --git a/src/pyclass/create_type_object.rs b/src/pyclass/create_type_object.rs index 86429a2b61e..cda5ad43d1d 100644 --- a/src/pyclass/create_type_object.rs +++ b/src/pyclass/create_type_object.rs @@ -18,12 +18,12 @@ use crate::{ types::PyType, Py, PyClass, PyResult, PyTypeInfo, Python, }; -use std::{ - collections::HashMap, - ffi::{CStr, CString}, - os::raw::{c_char, c_int, c_ulong, c_void}, +use alloc::ffi::CString; +use core::{ + ffi::{c_char, c_int, c_ulong, c_void, CStr}, ptr::{self, NonNull}, }; +use std::collections::HashMap; pub(crate) struct PyClassTypeObject { pub type_object: Py, @@ -162,13 +162,13 @@ impl PyTypeBuilder { ffi::Py_bf_getbuffer => { // Safety: slot.pfunc is a valid function pointer self.buffer_procs.bf_getbuffer = - Some(unsafe { std::mem::transmute::<*mut T, ffi::getbufferproc>(pfunc) }); + Some(unsafe { core::mem::transmute::<*mut T, ffi::getbufferproc>(pfunc) }); } #[cfg(all(not(Py_3_9), not(Py_LIMITED_API)))] ffi::Py_bf_releasebuffer => { // Safety: slot.pfunc is a valid function pointer self.buffer_procs.bf_releasebuffer = - Some(unsafe { std::mem::transmute::<*mut T, ffi::releasebufferproc>(pfunc) }); + Some(unsafe { core::mem::transmute::<*mut T, ffi::releasebufferproc>(pfunc) }); } _ => {} } @@ -185,7 +185,7 @@ impl PyTypeBuilder { if !data.is_empty() { // Python expects a zeroed entry to mark the end of the defs unsafe { - data.push(std::mem::zeroed()); + data.push(core::mem::zeroed()); self.push_slot(slot, Box::into_raw(data.into_boxed_slice()) as *mut c_void); } } @@ -216,11 +216,11 @@ impl PyTypeBuilder { } fn finalize_methods_and_properties(&mut self) -> Vec { - let method_defs: Vec = std::mem::take(&mut self.method_defs); + let method_defs: Vec = core::mem::take(&mut self.method_defs); // Safety: Py_tp_methods expects a raw vec of PyMethodDef unsafe { self.push_raw_vec_slot(ffi::Py_tp_methods, method_defs) }; - let member_defs = std::mem::take(&mut self.member_defs); + let member_defs = core::mem::take(&mut self.member_defs); // Safety: Py_tp_members expects a raw vec of PyMemberDef unsafe { self.push_raw_vec_slot(ffi::Py_tp_members, member_defs) }; @@ -267,7 +267,7 @@ impl PyTypeBuilder { let dict_ptr = object.byte_offset(dict_offset).cast::<*mut ffi::PyObject>(); if (*dict_ptr).is_null() { - std::ptr::write(dict_ptr, ffi::PyDict_New()); + core::ptr::write(dict_ptr, ffi::PyDict_New()); } Ok(ffi::compat::Py_XNewRef(*dict_ptr)) }) @@ -389,7 +389,7 @@ impl PyTypeBuilder { type_code: ffi::Py_T_PYSSIZET, offset, flags, - doc: std::ptr::null_mut(), + doc: core::ptr::null_mut(), } } @@ -527,7 +527,7 @@ impl PyTypeBuilder { bpo_45315_workaround(py, class_name); #[cfg(all(not(Py_LIMITED_API), not(Py_3_10)))] - for cleanup in std::mem::take(&mut self.cleanup) { + for cleanup in core::mem::take(&mut self.cleanup) { cleanup(&self, type_object.as_type_ptr()); } @@ -569,7 +569,7 @@ fn bpo_45315_workaround(py: Python<'_>, class_name: CString) { let _ = py; } - std::mem::forget(class_name); + core::mem::forget(class_name); } /// Default new implementation @@ -688,7 +688,7 @@ impl GetSetDefType { closure: *mut c_void, ) -> *mut ffi::PyObject { // Safety: PyO3 sets the closure when constructing the ffi getter so this cast should always be valid - let getter: Getter = unsafe { std::mem::transmute(closure) }; + let getter: Getter = unsafe { core::mem::transmute(closure) }; unsafe { trampoline(|py| getter(py, slf)) } } (Some(getter), None, closure as Getter as _) @@ -700,7 +700,7 @@ impl GetSetDefType { closure: *mut c_void, ) -> c_int { // Safety: PyO3 sets the closure when constructing the ffi setter so this cast should always be valid - let setter: Setter = unsafe { std::mem::transmute(closure) }; + let setter: Setter = unsafe { core::mem::transmute(closure) }; unsafe { trampoline(|py| { if value.is_null() { diff --git a/src/pyclass/gc.rs b/src/pyclass/gc.rs index 6b9da449c3e..0460c92b6d8 100644 --- a/src/pyclass/gc.rs +++ b/src/pyclass/gc.rs @@ -1,7 +1,7 @@ -use std::{ +use core::{ + ffi::{c_int, c_void}, marker::PhantomData, num::NonZero, - os::raw::{c_int, c_void}, }; use crate::{ffi, Py}; @@ -37,7 +37,7 @@ impl PyVisit<'_> { where T: Into>>, { - let ptr = obj.into().map_or_else(std::ptr::null_mut, Py::as_ptr); + let ptr = obj.into().map_or_else(core::ptr::null_mut, Py::as_ptr); if !ptr.is_null() { match NonZero::new(unsafe { (self.visit)(ptr, self.arg) }) { None => Ok(()), diff --git a/src/pyclass/guard.rs b/src/pyclass/guard.rs index 31038b39832..8cbb39bbdb0 100644 --- a/src/pyclass/guard.rs +++ b/src/pyclass/guard.rs @@ -7,11 +7,11 @@ use crate::pycell::PyBorrowMutError; use crate::pycell::{impl_::PyClassBorrowChecker, PyBorrowError}; use crate::pyclass::boolean_struct::False; use crate::{ffi, Borrowed, CastError, FromPyObject, IntoPyObject, Py, PyClass, PyErr}; -use std::convert::Infallible; -use std::fmt; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; -use std::ptr::NonNull; +use core::convert::Infallible; +use core::fmt; +use core::marker::PhantomData; +use core::ops::{Deref, DerefMut}; +use core::ptr::NonNull; /// A wrapper type for an immutably borrowed value from a `PyClass`. /// @@ -142,7 +142,7 @@ impl<'a, T: PyClass> PyClassGuard<'a, T> { where F: FnOnce(&T) -> &U, { - let slf = std::mem::ManuallyDrop::new(self); // the borrow is released when dropping the `PyClassGuardMap` + let slf = core::mem::ManuallyDrop::new(self); // the borrow is released when dropping the `PyClassGuardMap` PyClassGuardMap { ptr: NonNull::from(f(&slf)), checker: slf.as_class_object().borrow_checker(), @@ -271,7 +271,7 @@ where self.as_class_object().borrow_checker().release_borrow() }; PyClassGuard { - ptr: std::mem::ManuallyDrop::new(self).ptr, + ptr: core::mem::ManuallyDrop::new(self).ptr, marker: PhantomData, } } @@ -518,7 +518,7 @@ impl From> for PyErr { /// # } /// #[pyfunction] /// fn swap_numbers(a: &mut Number, b: &mut Number) { -/// std::mem::swap(&mut a.inner, &mut b.inner); +/// core::mem::swap(&mut a.inner, &mut b.inner); /// } /// # fn main() { /// # Python::attach(|py| { @@ -554,7 +554,7 @@ impl From> for PyErr { /// if !a.is(b) { /// let mut a: PyClassGuardMut<'_, Number> = a.extract()?; /// let mut b: PyClassGuardMut<'_, Number> = b.extract()?; -/// std::mem::swap(&mut a.inner, &mut b.inner); +/// core::mem::swap(&mut a.inner, &mut b.inner); /// } else { /// // Do nothing - they are the same object, so don't need swapping. /// } @@ -646,7 +646,7 @@ impl<'a, T: PyClass> PyClassGuardMut<'a, T> { where F: FnOnce(&mut T) -> &mut U, { - let mut slf = std::mem::ManuallyDrop::new(self); // the borrow is released when dropping the `PyClassGuardMap` + let mut slf = core::mem::ManuallyDrop::new(self); // the borrow is released when dropping the `PyClassGuardMap` PyClassGuardMap { ptr: NonNull::from(f(&mut slf)), checker: slf.as_class_object().borrow_checker(), @@ -679,7 +679,7 @@ where // `PyClassGuardMut` is only available for non-frozen classes, so there // is no possibility of leaking borrows like `PyClassGuard` PyClassGuardMut { - ptr: std::mem::ManuallyDrop::new(self).ptr, + ptr: core::mem::ManuallyDrop::new(self).ptr, marker: PhantomData, } } diff --git a/src/pyclass_init.rs b/src/pyclass_init.rs index 9ac1e9aa261..b744b2765ec 100644 --- a/src/pyclass_init.rs +++ b/src/pyclass_init.rs @@ -5,7 +5,7 @@ use crate::impl_::pyclass_init::{PyNativeTypeInitializer, PyObjectInit}; use crate::pycell::impl_::PyClassObjectLayout; use crate::{ffi, Bound, PyClass, PyResult, Python}; use crate::{ffi::PyTypeObject, pycell::impl_::PyClassObjectContents}; -use std::marker::PhantomData; +use core::marker::PhantomData; /// Initializer for our `#[pyclass]` system. /// diff --git a/src/sealed.rs b/src/sealed.rs index ce66511c15a..f7a0b30ac0b 100644 --- a/src/sealed.rs +++ b/src/sealed.rs @@ -64,8 +64,8 @@ impl Sealed for lock_api::Mutex {} #[cfg(feature = "parking_lot")] impl Sealed for parking_lot::Once {} #[cfg(feature = "arc_lock")] -impl Sealed for std::sync::Arc> {} +impl Sealed for alloc::sync::Arc> {} #[cfg(feature = "lock_api")] impl Sealed for lock_api::ReentrantMutex {} #[cfg(feature = "arc_lock")] -impl Sealed for std::sync::Arc> {} +impl Sealed for alloc::sync::Arc> {} diff --git a/src/sync.rs b/src/sync.rs index cb71ccd10f5..59c28101df1 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -15,12 +15,8 @@ use crate::{ types::{PyAny, PyString}, Bound, Py, Python, }; -use std::{ - cell::UnsafeCell, - marker::PhantomData, - mem::MaybeUninit, - sync::{Once, OnceState}, -}; +use core::{cell::UnsafeCell, marker::PhantomData, mem::MaybeUninit}; +use std::sync::{Once, OnceState}; pub mod critical_section; pub(crate) mod once_lock; @@ -454,7 +450,7 @@ impl MutexExt for lock_api::Mutex { } #[cfg(feature = "arc_lock")] -impl MutexExt for std::sync::Arc> +impl MutexExt for alloc::sync::Arc> where R: lock_api::RawMutex, { @@ -499,7 +495,7 @@ where } #[cfg(feature = "arc_lock")] -impl MutexExt for std::sync::Arc> +impl MutexExt for alloc::sync::Arc> where R: lock_api::RawMutex, G: lock_api::GetThreadId, @@ -615,7 +611,7 @@ impl RwLockExt for lock_api::RwLock { } #[cfg(feature = "arc_lock")] -impl RwLockExt for std::sync::Arc> +impl RwLockExt for alloc::sync::Arc> where R: lock_api::RawRwLock, { @@ -719,17 +715,22 @@ mod rwlock_ext_sealed { #[cfg(feature = "lock_api")] impl Sealed for lock_api::RwLock {} #[cfg(feature = "arc_lock")] - impl Sealed for std::sync::Arc> {} + impl Sealed for alloc::sync::Arc> {} } #[cfg(test)] +#[allow( + clippy::std_instead_of_core, + clippy::std_instead_of_alloc, + reason = "tests" +)] mod tests { use super::*; use crate::types::{PyAnyMethods, PyDict, PyDictMethods}; #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "macros")] - use std::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "macros")] use std::sync::Barrier; @@ -948,14 +949,14 @@ mod tests { test_mutex!(parking_lot::ArcMutexGuard<_, _>, |py| { let mutex = parking_lot::Mutex::new(Py::new(py, BoolWrapper(AtomicBool::new(false))).unwrap()); - std::sync::Arc::new(mutex) + alloc::sync::Arc::new(mutex) }); #[cfg(feature = "arc_lock")] test_mutex!(parking_lot::ArcReentrantMutexGuard<_, _, _>, |py| { let mutex = parking_lot::ReentrantMutex::new(Py::new(py, BoolWrapper(AtomicBool::new(false))).unwrap()); - std::sync::Arc::new(mutex) + alloc::sync::Arc::new(mutex) }); } @@ -1115,7 +1116,7 @@ mod tests { let rwlock = parking_lot::RwLock::new( Py::new(py, BoolWrapper(AtomicBool::new(false))).unwrap(), ); - std::sync::Arc::new(rwlock) + alloc::sync::Arc::new(rwlock) } ); } @@ -1184,7 +1185,7 @@ mod tests { let rwlock = parking_lot::RwLock::new( Py::new(py, BoolWrapper(AtomicBool::new(false))).unwrap(), ); - std::sync::Arc::new(rwlock) + alloc::sync::Arc::new(rwlock) } ); } diff --git a/src/sync/critical_section.rs b/src/sync/critical_section.rs index 278be0da12a..d7e8502371e 100644 --- a/src/sync/critical_section.rs +++ b/src/sync/critical_section.rs @@ -44,7 +44,7 @@ use crate::types::PyMutex; use crate::Python; use crate::{types::PyAny, Bound}; #[cfg(all(Py_3_14, not(Py_LIMITED_API)))] -use std::cell::UnsafeCell; +use core::cell::UnsafeCell; #[cfg(Py_GIL_DISABLED)] struct CSGuard(crate::ffi::PyCriticalSection); @@ -132,7 +132,7 @@ where { #[cfg(Py_GIL_DISABLED)] { - let mut guard = CSGuard(unsafe { std::mem::zeroed() }); + let mut guard = CSGuard(unsafe { core::mem::zeroed() }); unsafe { crate::ffi::PyCriticalSection_Begin(&mut guard.0, object.as_ptr()) }; f() } @@ -159,7 +159,7 @@ where { #[cfg(Py_GIL_DISABLED)] { - let mut guard = CS2Guard(unsafe { std::mem::zeroed() }); + let mut guard = CS2Guard(unsafe { core::mem::zeroed() }); unsafe { crate::ffi::PyCriticalSection2_Begin(&mut guard.0, a.as_ptr(), b.as_ptr()) }; f() } @@ -197,7 +197,7 @@ where { #[cfg(Py_GIL_DISABLED)] { - let mut guard = CSGuard(unsafe { std::mem::zeroed() }); + let mut guard = CSGuard(unsafe { core::mem::zeroed() }); unsafe { crate::ffi::PyCriticalSection_BeginMutex(&mut guard.0, &mut *mutex.mutex.get()) }; f(EnteredCriticalSection(&mutex.data)) } @@ -240,7 +240,7 @@ where { #[cfg(Py_GIL_DISABLED)] { - let mut guard = CS2Guard(unsafe { std::mem::zeroed() }); + let mut guard = CS2Guard(unsafe { core::mem::zeroed() }); unsafe { crate::ffi::PyCriticalSection2_BeginMutex( &mut guard.0, @@ -274,7 +274,7 @@ mod tests { #[cfg(all(not(Py_LIMITED_API), Py_3_14))] use crate::types::PyMutex; #[cfg(feature = "macros")] - use std::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(any(feature = "macros", all(not(Py_LIMITED_API), Py_3_14)))] use std::sync::Barrier; @@ -306,7 +306,7 @@ mod tests { let b = bool_wrapper.bind(py); with_critical_section(b, || { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); b.borrow().0.store(true, Ordering::Release); }) }); @@ -336,7 +336,7 @@ mod tests { Python::attach(|py| { with_critical_section_mutex(py, &mutex, |mut b| { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // SAFETY: we never call back into the python interpreter inside this critical section *(unsafe { b.get_mut() }) = true; }); @@ -374,7 +374,7 @@ mod tests { let b2 = bool_wrapper2.bind(py); with_critical_section2(b1, b2, || { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); b1.borrow().0.store(true, Ordering::Release); b2.borrow().0.store(true, Ordering::Release); }) @@ -416,7 +416,7 @@ mod tests { Python::attach(|py| { with_critical_section_mutex2(py, &m1, &m2, |mut b1, mut b2| { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // SAFETY: we never call back into the python interpreter inside this critical section unsafe { (*b1.get_mut()) = true }; unsafe { (*b2.get_mut()) = true }; @@ -452,7 +452,7 @@ mod tests { let b = bool_wrapper.bind(py); with_critical_section2(b, b, || { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); b.borrow().0.store(true, Ordering::Release); }) }); @@ -482,7 +482,7 @@ mod tests { Python::attach(|py| { with_critical_section_mutex2(py, &m, &m, |mut b1, b2| { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // SAFETY: we never call back into the python interpreter inside this critical section unsafe { (*b1.get_mut()) = true }; assert!(unsafe { *b2.get() }); diff --git a/src/tests/hygiene/pyclass.rs b/src/tests/hygiene/pyclass.rs index 0e2f707cdd4..b2d0c0740b2 100644 --- a/src/tests/hygiene/pyclass.rs +++ b/src/tests/hygiene/pyclass.rs @@ -1,6 +1,6 @@ #[crate::pyclass(from_py_object)] #[pyo3(crate = "crate")] -#[derive(::std::clone::Clone)] +#[derive(::core::clone::Clone)] pub struct Foo; #[crate::pyclass] @@ -32,7 +32,7 @@ pub struct Bar { #[pyo3(get, set)] b: Foo, #[pyo3(set)] - c: ::std::option::Option>, + c: ::core::option::Option>, } #[crate::pyclass(eq, eq_int)] @@ -146,9 +146,9 @@ pub struct Point { z: i32, } -impl ::std::fmt::Display for Point { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::write!(f, "({}, {}, {})", self.x, self.y, self.z) +impl ::core::fmt::Display for Point { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + ::core::write!(f, "({}, {}, {})", self.x, self.y, self.z) } } diff --git a/src/tests/hygiene/pyfunction.rs b/src/tests/hygiene/pyfunction.rs index a692b0acd3f..874264aa18c 100644 --- a/src/tests/hygiene/pyfunction.rs +++ b/src/tests/hygiene/pyfunction.rs @@ -1,13 +1,13 @@ #[crate::pyfunction] #[pyo3(crate = "crate")] fn do_something(x: i32) -> crate::PyResult { - ::std::result::Result::Ok(x) + ::core::result::Result::Ok(x) } #[crate::pyfunction] #[pyo3(crate = "crate", name = "check5012")] fn check_5012(x: i32) -> crate::PyResult { - ::std::result::Result::Ok(x) + ::core::result::Result::Ok(x) } #[crate::pyfunction] diff --git a/src/tests/hygiene/pymethods.rs b/src/tests/hygiene/pymethods.rs index 87babfac220..c1d8d8da3bb 100644 --- a/src/tests/hygiene/pymethods.rs +++ b/src/tests/hygiene/pymethods.rs @@ -24,8 +24,8 @@ impl Dummy { crate::types::PyBytes::new(py, &[0]) } - fn __format__(&self, format_spec: ::std::string::String) -> ::std::string::String { - ::std::unimplemented!() + fn __format__(&self, format_spec: ::alloc::string::String) -> ::alloc::string::String { + ::core::unimplemented!() } fn __lt__(&self, other: &Self) -> bool { @@ -60,23 +60,23 @@ impl Dummy { // Customizing attribute access ////////////////////// - fn __getattr__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> { - ::std::unimplemented!() + fn __getattr__(&self, name: ::alloc::string::String) -> &crate::Bound<'_, crate::PyAny> { + ::core::unimplemented!() } - fn __getattribute__(&self, name: ::std::string::String) -> &crate::Bound<'_, crate::PyAny> { - ::std::unimplemented!() + fn __getattribute__(&self, name: ::alloc::string::String) -> &crate::Bound<'_, crate::PyAny> { + ::core::unimplemented!() } - fn __setattr__(&mut self, name: ::std::string::String, value: ::std::string::String) {} + fn __setattr__(&mut self, name: ::alloc::string::String, value: ::alloc::string::String) {} - fn __delattr__(&mut self, name: ::std::string::String) {} + fn __delattr__(&mut self, name: ::alloc::string::String) {} fn __dir__<'py>( &self, py: crate::Python<'py>, ) -> crate::PyResult> { - crate::types::PyList::new(py, ::std::vec![0_u8]) + crate::types::PyList::new(py, ::alloc::vec![0_u8]) } ////////////////////// @@ -88,7 +88,7 @@ impl Dummy { instance: &crate::Bound<'_, crate::PyAny>, owner: &crate::Bound<'_, crate::PyAny>, ) -> crate::PyResult<&crate::Bound<'_, crate::PyAny>> { - ::std::unimplemented!() + ::core::unimplemented!() } fn __set__( @@ -116,7 +116,7 @@ impl Dummy { } fn __getitem__(&self, key: u32) -> crate::PyResult { - ::std::result::Result::Err(crate::exceptions::PyKeyError::new_err("boo")) + ::core::result::Result::Err(crate::exceptions::PyKeyError::new_err("boo")) } fn __setitem__(&self, key: u32, value: u32) {} @@ -127,8 +127,8 @@ impl Dummy { crate::Py::new(py, DummyIter {}).unwrap() } - fn __next__(&mut self) -> ::std::option::Option<()> { - ::std::option::Option::None + fn __next__(&mut self) -> ::core::option::Option<()> { + ::core::option::Option::None } fn __reversed__( @@ -159,11 +159,11 @@ impl Dummy { } fn __truediv__(&self, _other: &Self) -> crate::PyResult<()> { - ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) + ::core::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __floordiv__(&self, _other: &Self) -> crate::PyResult<()> { - ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) + ::core::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __mod__(&self, _other: &Self) -> u32 { @@ -174,7 +174,7 @@ impl Dummy { (0, 0) } - fn __pow__(&self, _other: &Self, modulo: ::std::option::Option) -> Dummy { + fn __pow__(&self, _other: &Self, modulo: ::core::option::Option) -> Dummy { Dummy {} } @@ -211,11 +211,11 @@ impl Dummy { } fn __rtruediv__(&self, _other: &Self) -> crate::PyResult<()> { - ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) + ::core::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __rfloordiv__(&self, _other: &Self) -> crate::PyResult<()> { - ::std::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) + ::core::result::Result::Err(crate::exceptions::PyZeroDivisionError::new_err("boo")) } fn __rmod__(&self, _other: &Self) -> u32 { @@ -226,7 +226,7 @@ impl Dummy { (0, 0) } - fn __rpow__(&self, _other: &Self, modulo: ::std::option::Option) -> Dummy { + fn __rpow__(&self, _other: &Self, modulo: ::core::option::Option) -> Dummy { Dummy {} } @@ -262,7 +262,7 @@ impl Dummy { fn __imod__(&mut self, _other: &Self) {} - fn __ipow__(&mut self, _other: &Self, modulo: ::std::option::Option) {} + fn __ipow__(&mut self, _other: &Self, modulo: ::core::option::Option) {} fn __ilshift__(&mut self, other: &Self) {} @@ -309,8 +309,8 @@ impl Dummy { 0 } - #[pyo3(signature=(ndigits=::std::option::Option::None))] - fn __round__(&self, ndigits: ::std::option::Option) -> u32 { + #[pyo3(signature=(ndigits=::core::option::Option::None))] + fn __round__(&self, ndigits: ::core::option::Option) -> u32 { 0 } @@ -360,8 +360,8 @@ impl Dummy { crate::Py::new(py, DummyIter {}).unwrap() } - fn __anext__(&mut self) -> ::std::option::Option<()> { - ::std::option::Option::None + fn __anext__(&mut self) -> ::core::option::Option<()> { + ::core::option::Option::None } ////////////////////// @@ -390,9 +390,9 @@ impl Dummy { fn __call__( &self, _args: &crate::Bound<'_, crate::types::PyTuple>, - _kwds: ::std::option::Option<&crate::Bound<'_, crate::types::PyDict>>, + _kwds: ::core::option::Option<&crate::Bound<'_, crate::types::PyDict>>, ) -> crate::PyResult { - ::std::unimplemented!() + ::core::unimplemented!() } #[new] fn new(a: u8) -> Self { @@ -425,8 +425,8 @@ impl Clear { pub fn __traverse__( &self, visit: crate::PyVisit<'_>, - ) -> ::std::result::Result<(), crate::PyTraverseError> { - ::std::result::Result::Ok(()) + ) -> ::core::result::Result<(), crate::PyTraverseError> { + ::core::result::Result::Ok(()) } pub fn __clear__(&self) {} @@ -444,7 +444,7 @@ struct Dummy2; impl Dummy2 { #[classmethod] fn __len__(cls: &crate::Bound<'_, crate::types::PyType>) -> crate::PyResult { - ::std::result::Result::Ok(0) + ::core::result::Result::Ok(0) } #[staticmethod] @@ -469,7 +469,7 @@ impl UserDefinedWarning { #[pyo3(signature = (*_args, **_kwargs))] fn new( _args: crate::Bound<'_, crate::PyAny>, - _kwargs: ::std::option::Option>, + _kwargs: ::core::option::Option>, ) -> Self { Self {} } diff --git a/src/tests/hygiene/pymodule.rs b/src/tests/hygiene/pymodule.rs index 56c6f10fa20..7f41e5e1778 100644 --- a/src/tests/hygiene/pymodule.rs +++ b/src/tests/hygiene/pymodule.rs @@ -1,7 +1,7 @@ #[crate::pyfunction] #[pyo3(crate = "crate")] fn do_something(x: i32) -> crate::PyResult { - ::std::result::Result::Ok(x) + ::core::result::Result::Ok(x) } #[crate::pymodule] @@ -10,7 +10,7 @@ fn foo( _py: crate::Python<'_>, _m: &crate::Bound<'_, crate::types::PyModule>, ) -> crate::PyResult<()> { - ::std::result::Result::Ok(()) + ::core::result::Result::Ok(()) } #[crate::pymodule] @@ -25,7 +25,7 @@ fn my_module(m: &crate::Bound<'_, crate::types::PyModule>) -> crate::PyResult<() crate::wrap_pymodule!(foo), )?; - ::std::result::Result::Ok(()) + ::core::result::Result::Ok(()) } #[crate::pymodule(submodule)] diff --git a/src/type_object.rs b/src/type_object.rs index 716969ffe17..cb175524439 100644 --- a/src/type_object.rs +++ b/src/type_object.rs @@ -5,7 +5,7 @@ use crate::ffi_ptr_ext::FfiPtrExt; use crate::inspect::{type_hint_identifier, PyStaticExpr}; use crate::types::{PyAny, PyType}; use crate::{ffi, Bound, Python}; -use std::ptr; +use core::ptr; /// `T: PyLayout` represents that `T` is a concrete representation of `U` in the Python heap. /// E.g., `PyClassObject` is a concrete representation of all `pyclass`es, and `ffi::PyObject` diff --git a/src/types/any.rs b/src/types/any.rs index 8923f429efa..d02df201d7b 100644 --- a/src/types/any.rs +++ b/src/types/any.rs @@ -14,10 +14,10 @@ use crate::types::{PyDict, PyIterator, PyList, PyString, PyType}; use crate::{err, ffi, Borrowed, BoundObject, IntoPyObjectExt, Py, Python}; #[allow(deprecated)] use crate::{DowncastError, DowncastIntoError}; -use std::cell::UnsafeCell; -use std::cmp::Ordering; -use std::ffi::c_int; -use std::ptr; +use core::cell::UnsafeCell; +use core::cmp::Ordering; +use core::ffi::c_int; +use core::ptr; /// Represents any Python object. /// @@ -212,7 +212,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyFloat; - /// use std::cmp::Ordering; + /// use core::cmp::Ordering; /// /// # fn main() -> PyResult<()> { /// Python::attach(|py| -> PyResult<()> { @@ -451,7 +451,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// use pyo3_ffi::c_str; - /// use std::ffi::CStr; + /// use core::ffi::CStr; /// /// const CODE: &CStr = cr#" /// def function(*args, **kwargs): @@ -508,7 +508,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; - /// use std::ffi::CStr; + /// use core::ffi::CStr; /// /// const CODE: &CStr = cr#" /// def function(*args, **kwargs): @@ -545,7 +545,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// use pyo3::prelude::*; /// use pyo3::types::PyDict; /// use pyo3_ffi::c_str; - /// use std::ffi::CStr; + /// use core::ffi::CStr; /// /// const CODE: &CStr = cr#" /// class A: @@ -591,7 +591,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; - /// use std::ffi::CStr; + /// use core::ffi::CStr; /// /// const CODE: &CStr = cr#" /// class A: @@ -628,7 +628,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3_ffi::c_str; - /// use std::ffi::CStr; + /// use core::ffi::CStr; /// /// const CODE: &CStr = cr#" /// class A: @@ -1026,7 +1026,7 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> { ) -> PyResult>> { #[cfg(Py_3_13)] { - let mut resp_ptr: *mut ffi::PyObject = std::ptr::null_mut(); + let mut resp_ptr: *mut ffi::PyObject = core::ptr::null_mut(); match unsafe { ffi::PyObject_GetOptionalAttr(any.as_ptr(), attr_name.as_ptr(), &mut resp_ptr) } { @@ -1671,8 +1671,8 @@ mod tests { types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyInt, PyList, PyModule, PyTypeMethods}, Bound, BoundObject, IntoPyObject, PyTypeInfo, Python, }; + use core::fmt::Debug; use pyo3_ffi::c_str; - use std::fmt::Debug; #[test] fn test_lookup_special() { @@ -2063,7 +2063,7 @@ class SimpleClass: 2.5, 0.0, 3.0, - std::f64::consts::PI, + core::f64::consts::PI, 10.0, 10.0 / 3.0, -1_000_000.0, diff --git a/src/types/boolobject.rs b/src/types/boolobject.rs index 017584b877d..4f86e9e9da7 100644 --- a/src/types/boolobject.rs +++ b/src/types/boolobject.rs @@ -11,8 +11,8 @@ use crate::{ exceptions::PyTypeError, ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, types::typeobject::PyTypeMethods, Borrowed, FromPyObject, PyAny, Python, }; -use std::convert::Infallible; -use std::ptr; +use core::convert::Infallible; +use core::ptr; /// Represents a Python `bool`. /// diff --git a/src/types/bytearray.rs b/src/types/bytearray.rs index 98cf76c427e..d2a96d68427 100644 --- a/src/types/bytearray.rs +++ b/src/types/bytearray.rs @@ -4,7 +4,7 @@ use crate::instance::{Borrowed, Bound}; use crate::py_result_ext::PyResultExt; use crate::sync::critical_section::with_critical_section; use crate::{ffi, PyAny, Python}; -use std::slice; +use core::slice; /// Represents a Python `bytearray`. /// @@ -63,17 +63,17 @@ impl PyByteArray { unsafe { // Allocate buffer and check for an error let pybytearray: Bound<'_, Self> = - ffi::PyByteArray_FromStringAndSize(std::ptr::null(), len as ffi::Py_ssize_t) + ffi::PyByteArray_FromStringAndSize(core::ptr::null(), len as ffi::Py_ssize_t) .assume_owned_or_err(py)? .cast_into_unchecked(); let buffer: *mut u8 = ffi::PyByteArray_AsString(pybytearray.as_ptr()).cast(); debug_assert!(!buffer.is_null()); // Zero-initialise the uninitialised bytearray - std::ptr::write_bytes(buffer, 0u8, len); + core::ptr::write_bytes(buffer, 0u8, len); // (Further) Initialise the bytearray in init // If init returns an Err, pypybytearray will automatically deallocate the buffer - init(std::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytearray) + init(core::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytearray) } } @@ -463,11 +463,11 @@ mod tests { use crate::instance::Py; use crate::sync::{critical_section::with_critical_section, MutexExt}; - use std::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, Ordering}; + use core::time::Duration; use std::sync::Mutex; use std::thread; use std::thread::ScopedJoinHandle; - use std::time::Duration; const SIZE: usize = 1_000_000; const DATA_VALUE: u8 = 42; diff --git a/src/types/bytes.rs b/src/types/bytes.rs index 6b6af15063c..4dcaeb65d90 100644 --- a/src/types/bytes.rs +++ b/src/types/bytes.rs @@ -1,11 +1,14 @@ +#![allow(unused_imports, reason = "conditional compilation")] + use crate::byteswriter::PyBytesWriter; use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::{Borrowed, Bound}; use crate::{ffi, Py, PyAny, PyResult, Python}; +use core::ops::Index; +use core::slice::SliceIndex; +use core::str; +#[cfg(feature = "std")] use std::io::Write; -use std::ops::Index; -use std::slice::SliceIndex; -use std::str; /// Represents a Python `bytes` object. /// @@ -96,16 +99,16 @@ impl PyBytes { F: FnOnce(&mut [u8]) -> PyResult<()>, { unsafe { - let pyptr = ffi::PyBytes_FromStringAndSize(std::ptr::null(), len as ffi::Py_ssize_t); + let pyptr = ffi::PyBytes_FromStringAndSize(core::ptr::null(), len as ffi::Py_ssize_t); // Check for an allocation error and return it let pybytes = pyptr.assume_owned_or_err(py)?.cast_into_unchecked(); let buffer: *mut u8 = ffi::PyBytes_AsString(pyptr).cast(); debug_assert!(!buffer.is_null()); // Zero-initialise the uninitialised bytestring - std::ptr::write_bytes(buffer, 0u8, len); + core::ptr::write_bytes(buffer, 0u8, len); // (Further) Initialise the bytestring in init // If init returns an Err, pypybytearray will automatically deallocate the buffer - init(std::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytes) + init(core::slice::from_raw_parts_mut(buffer, len)).map(|_| pybytes) } } @@ -136,6 +139,7 @@ impl PyBytes { /// }) /// # } /// ``` + #[cfg(feature = "std")] #[inline] pub fn new_with_writer( py: Python<'_>, @@ -195,7 +199,7 @@ impl<'a> Borrowed<'a, '_, PyBytes> { let buffer = ffi::PyBytes_AsString(self.as_ptr()) as *const u8; let length = ffi::PyBytes_Size(self.as_ptr()) as usize; debug_assert!(!buffer.is_null()); - std::slice::from_raw_parts(buffer, length) + core::slice::from_raw_parts(buffer, length) } } } @@ -432,8 +436,8 @@ mod tests { let py_bytes = PyBytes::new(py, b); unsafe { assert_eq!( - ffi::PyBytes_AsString(py_bytes.as_ptr()) as *const std::ffi::c_char, - ffi::PyBytes_AS_STRING(py_bytes.as_ptr()) as *const std::ffi::c_char + ffi::PyBytes_AsString(py_bytes.as_ptr()) as *const core::ffi::c_char, + ffi::PyBytes_AS_STRING(py_bytes.as_ptr()) as *const core::ffi::c_char ); } }) @@ -453,6 +457,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_with_writer() { Python::attach(|py| { let bytes = PyBytes::new_with_writer(py, 0, |writer| { diff --git a/src/types/capsule.rs b/src/types/capsule.rs index 9d4ad5197ce..ef468e5b262 100644 --- a/src/types/capsule.rs +++ b/src/types/capsule.rs @@ -5,10 +5,11 @@ use crate::py_result_ext::PyResultExt; use crate::{ffi, PyAny}; use crate::{Bound, Python}; use crate::{PyErr, PyResult}; -use std::ffi::{c_char, c_int, c_void}; -use std::ffi::{CStr, CString}; -use std::mem::offset_of; -use std::ptr::{self, NonNull}; +use alloc::ffi::CString; +use core::ffi::CStr; +use core::ffi::{c_char, c_int, c_void}; +use core::mem::offset_of; +use core::ptr::{self, NonNull}; /// Represents a Python Capsule /// as described in [Capsules](https://docs.python.org/3/c-api/capsule.html#capsules): @@ -63,8 +64,8 @@ impl PyCapsule { /// /// ``` /// use pyo3::{prelude::*, types::PyCapsule, ffi::c_str}; - /// use std::ffi::CStr; - /// use std::ptr::NonNull; + /// use core::ffi::CStr; + /// use core::ptr::NonNull; /// /// // this can be c"foo" on Rust 1.77+ /// const NAME: &CStr = c"foo"; @@ -114,7 +115,9 @@ impl PyCapsule { // Sanity check for capsule layout debug_assert_eq!(offset_of!(CapsuleContents::, value), 0); - let name_ptr = name.as_ref().map_or(std::ptr::null(), |name| name.as_ptr()); + let name_ptr = name + .as_ref() + .map_or(core::ptr::null(), |name| name.as_ptr()); let val = Box::into_raw(Box::new(CapsuleContents { value, destructor, @@ -155,11 +158,11 @@ impl PyCapsule { /// /// ``` /// use pyo3::{prelude::*, types::PyCapsule}; - /// use std::ffi::c_void; - /// use std::ptr::NonNull; + /// use core::ffi::c_void; + /// use core::ptr::NonNull; /// /// extern "C" fn my_ffi_handler(_: *mut c_void) -> *mut c_void { - /// std::ptr::null_mut() + /// core::ptr::null_mut() /// } /// /// Python::attach(|py| { @@ -206,8 +209,8 @@ impl PyCapsule { /// /// ``` /// use pyo3::{prelude::*, types::PyCapsule}; - /// use std::ffi::c_void; - /// use std::ptr::NonNull; + /// use core::ffi::c_void; + /// use core::ptr::NonNull; /// /// unsafe extern "C" fn free_data(capsule: *mut pyo3::ffi::PyObject) { /// let ptr = pyo3::ffi::PyCapsule_GetPointer(capsule, c"my_module.data".as_ptr()); @@ -303,7 +306,7 @@ pub trait PyCapsuleMethods<'py>: crate::sealed::Sealed { /// # Example /// /// ``` - /// use std::ffi::c_void; + /// use core::ffi::c_void; /// use std::sync::mpsc::{channel, Sender}; /// use pyo3::{prelude::*, types::PyCapsule}; /// @@ -568,7 +571,7 @@ unsafe extern "C" fn capsule_destructor` #[doc(hidden)] pub trait AssertNotZeroSized: Sized { - const _CONDITION: usize = (std::mem::size_of::() == 0) as usize; + const _CONDITION: usize = (core::mem::size_of::() == 0) as usize; const _CHECK: &'static str = ["PyCapsule value type T must not be zero-sized!"][Self::_CONDITION]; #[allow(path_statements, clippy::no_effect)] @@ -612,8 +615,8 @@ mod tests { use crate::types::capsule::PyCapsuleMethods; use crate::types::module::PyModuleMethods; use crate::{types::PyCapsule, Py, PyResult, Python}; - use std::ffi::{c_void, CStr}; - use std::ptr::NonNull; + use core::ffi::{c_void, CStr}; + use core::ptr::NonNull; use std::sync::mpsc::{channel, Sender}; const NAME: &CStr = c"foo"; @@ -791,14 +794,14 @@ mod tests { &0usize ); assert!(cap.name().unwrap().is_none()); - assert_eq!(cap.context().unwrap(), std::ptr::null_mut()); + assert_eq!(cap.context().unwrap(), core::ptr::null_mut()); }); } #[test] fn test_pycapsule_new_with_pointer() { extern "C" fn dummy_handler(_: *mut c_void) -> *mut c_void { - std::ptr::null_mut() + core::ptr::null_mut() } let fn_ptr = @@ -933,7 +936,7 @@ mod tests { // Invalidate the capsule // SAFETY: intentionally breaking the capsule for testing unsafe { - crate::ffi::PyCapsule_SetPointer(cap.as_ptr(), std::ptr::null_mut()); + crate::ffi::PyCapsule_SetPointer(cap.as_ptr(), core::ptr::null_mut()); } // context() on invalid capsule should fail diff --git a/src/types/complex.rs b/src/types/complex.rs index d7b7bca1d4b..4e2ea3dc11a 100644 --- a/src/types/complex.rs +++ b/src/types/complex.rs @@ -3,7 +3,7 @@ use crate::py_result_ext::PyResultExt; #[cfg(not(any(Py_LIMITED_API, PyPy, GraalPy)))] use crate::types::any::PyAnyMethods; use crate::{ffi, Bound, PyAny, Python}; -use std::ffi::c_double; +use core::ffi::c_double; /// Represents a Python [`complex`](https://docs.python.org/3/library/functions.html#complex) object. /// @@ -49,7 +49,7 @@ mod not_limited_impls { use crate::Borrowed; use super::*; - use std::ops::{Add, Div, Mul, Neg, Sub}; + use core::ops::{Add, Div, Mul, Neg, Sub}; macro_rules! bin_ops { ($trait:ident, $fn:ident, $op:tt) => { diff --git a/src/types/datetime.rs b/src/types/datetime.rs index 4c0fce18728..7f2c1d3f247 100644 --- a/src/types/datetime.rs +++ b/src/types/datetime.rs @@ -32,7 +32,7 @@ use crate::{ffi_ptr_ext::FfiPtrExt, py_result_ext::PyResultExt, types::PyTuple, use crate::{sync::PyOnceLock, Py}; use crate::{Borrowed, Bound, IntoPyObject, PyAny, Python}; #[cfg(not(Py_LIMITED_API))] -use std::ffi::c_int; +use core::ffi::c_int; #[cfg(not(Py_LIMITED_API))] fn ensure_datetime_api(py: Python<'_>) -> PyResult<&'static PyDateTime_CAPI> { @@ -782,7 +782,7 @@ impl PyTzInfo { let api = ensure_datetime_api(py)?; let delta = offset.into_pyobject(py).map_err(Into::into)?; unsafe { - (api.TimeZone_FromTimeZone)(delta.as_ptr(), std::ptr::null_mut()) + (api.TimeZone_FromTimeZone)(delta.as_ptr(), core::ptr::null_mut()) .assume_owned_or_err(py) .cast_into_unchecked() } diff --git a/src/types/dict.rs b/src/types/dict.rs index c5934cae93b..4ead3e49324 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -258,13 +258,13 @@ impl<'py> PyDictMethods<'py> for Bound<'py, PyDict> { key: Borrowed<'_, '_, PyAny>, ) -> PyResult>> { let py = dict.py(); - let mut result: *mut ffi::PyObject = std::ptr::null_mut(); + let mut result: *mut ffi::PyObject = core::ptr::null_mut(); match unsafe { ffi::compat::PyDict_GetItemRef(dict.as_ptr(), key.as_ptr(), &mut result) } { - std::ffi::c_int::MIN..=-1 => Err(PyErr::fetch(py)), + core::ffi::c_int::MIN..=-1 => Err(PyErr::fetch(py)), 0 => Ok(None), - 1..=std::ffi::c_int::MAX => { + 1..=core::ffi::c_int::MAX => { // Safety: PyDict_GetItemRef positive return value means the result is a valid // owned reference Ok(Some(unsafe { result.assume_owned_unchecked(py) })) @@ -472,8 +472,8 @@ impl DictIterImpl { panic!("dictionary keys changed during iteration"); }; - let mut key: *mut ffi::PyObject = std::ptr::null_mut(); - let mut value: *mut ffi::PyObject = std::ptr::null_mut(); + let mut key: *mut ffi::PyObject = core::ptr::null_mut(); + let mut value: *mut ffi::PyObject = core::ptr::null_mut(); if unsafe { ffi::PyDict_Next(dict.as_ptr(), ppos, &mut key, &mut value) != 0 } { *remaining -= 1; @@ -560,7 +560,7 @@ impl<'py> Iterator for BoundDictIterator<'py> { where Self: Sized, F: FnMut(B, Self::Item) -> R, - R: std::ops::Try, + R: core::ops::Try, { self.inner.with_critical_section(&self.dict, |inner| { let mut accum = init; @@ -717,8 +717,8 @@ mod borrowed_iter { #[inline] fn next(&mut self) -> Option { - let mut key: *mut ffi::PyObject = std::ptr::null_mut(); - let mut value: *mut ffi::PyObject = std::ptr::null_mut(); + let mut key: *mut ffi::PyObject = core::ptr::null_mut(); + let mut value: *mut ffi::PyObject = core::ptr::null_mut(); // Safety: self.dict lives sufficiently long that the pointer is not dangling if unsafe { ffi::PyDict_Next(self.dict.as_ptr(), &mut self.ppos, &mut key, &mut value) } @@ -831,7 +831,8 @@ where mod tests { use super::*; use crate::types::{PyAnyMethods as _, PyTuple}; - use std::collections::{BTreeMap, HashMap}; + use alloc::collections::BTreeMap; + use std::collections::HashMap; #[test] fn test_new() { @@ -846,8 +847,11 @@ mod tests { .unwrap() ); assert!(dict.get_item(8i32).unwrap().is_none()); - let map: HashMap = [(7, 32)].iter().cloned().collect(); - assert_eq!(map, dict.extract().unwrap()); + #[cfg(feature = "std")] + { + let map: HashMap = [(7, 32)].iter().cloned().collect(); + assert_eq!(map, dict.extract().unwrap()); + } let map: BTreeMap = [(7, 32)].iter().cloned().collect(); assert_eq!(map, dict.extract().unwrap()); }); @@ -875,9 +879,12 @@ mod tests { .extract::() .unwrap() ); - let map: HashMap = - [("a".into(), 1), ("b".into(), 2)].into_iter().collect(); - assert_eq!(map, dict.extract().unwrap()); + #[cfg(feature = "std")] + { + let map: HashMap = + [("a".into(), 1), ("b".into(), 2)].into_iter().collect(); + assert_eq!(map, dict.extract().unwrap()); + } let map: BTreeMap = [("a".into(), 1), ("b".into(), 2)].into_iter().collect(); assert_eq!(map, dict.extract().unwrap()); @@ -915,7 +922,7 @@ mod tests { #[test] fn test_len() { Python::attach(|py| { - let mut v = HashMap::::new(); + let mut v = BTreeMap::::new(); let dict = (&v).into_pyobject(py).unwrap(); assert_eq!(0, dict.len()); v.insert(7, 32); @@ -927,7 +934,7 @@ mod tests { #[test] fn test_contains() { Python::attach(|py| { - let mut v = HashMap::new(); + let mut v = BTreeMap::new(); v.insert(7, 32); let dict = v.into_pyobject(py).unwrap(); assert!(dict.contains(7i32).unwrap()); @@ -940,7 +947,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); assert_eq!( 32, dict.get_item(7i32) @@ -994,7 +1001,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!( @@ -1034,7 +1041,7 @@ mod tests { #[test] fn test_set_item_does_not_update_original_object() { Python::attach(|py| { - let mut v = HashMap::new(); + let mut v = BTreeMap::new(); v.insert(7, 32); let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change @@ -1049,7 +1056,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); assert_eq!(0, dict.len()); assert!(dict.get_item(7i32).unwrap().is_none()); @@ -1059,7 +1066,7 @@ mod tests { #[test] fn test_del_item_does_not_update_original_object() { Python::attach(|py| { - let mut v = HashMap::new(); + let mut v = BTreeMap::new(); v.insert(7, 32); let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); // change @@ -1074,7 +1081,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; let mut value_sum = 0; @@ -1095,7 +1102,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; for el in dict.keys() { @@ -1112,7 +1119,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; for el in dict.values() { @@ -1129,7 +1136,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { @@ -1148,7 +1155,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { @@ -1168,7 +1175,7 @@ mod tests { v.insert(8, 42); v.insert(9, 123); - let dict = (&v).into_pyobject(py).unwrap(); + let dict = (&v).into_py_dict(py).unwrap(); for (key, value) in &dict { dict.set_item(key, value.extract::().unwrap() + 7) @@ -1185,7 +1192,7 @@ mod tests { for i in 0..10 { v.insert(i * 2, i * 2); } - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::().unwrap(); @@ -1209,7 +1216,7 @@ mod tests { for i in 0..10 { v.insert(i * 2, i * 2); } - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::().unwrap(); @@ -1232,7 +1239,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = (&v).into_pyobject(py).unwrap(); + let dict = (&v).into_py_dict(py).unwrap(); let mut iter = dict.iter(); assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); @@ -1257,7 +1264,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let dict = v.into_pyobject(py).unwrap(); + let dict = v.into_py_dict(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { diff --git a/src/types/float.rs b/src/types/float.rs index bc82375bafd..b64c69d97f0 100644 --- a/src/types/float.rs +++ b/src/types/float.rs @@ -8,8 +8,8 @@ use crate::type_object::PyTypeInfo; use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, Borrowed, FromPyObject, PyAny, PyErr, Python, }; -use std::convert::Infallible; -use std::ffi::c_double; +use core::convert::Infallible; +use core::ffi::c_double; /// Represents a Python `float` object. /// diff --git a/src/types/frozenset.rs b/src/types/frozenset.rs index 7e15b9233de..a817e497ddb 100644 --- a/src/types/frozenset.rs +++ b/src/types/frozenset.rs @@ -7,7 +7,7 @@ use crate::{ Bound, PyAny, Python, }; use crate::{Borrowed, BoundObject, IntoPyObject, IntoPyObjectExt}; -use std::ptr; +use core::ptr; /// Allows building a Python `frozenset` one item at a time pub struct PyFrozenSetBuilder<'py> { diff --git a/src/types/function.rs b/src/types/function.rs index 443266611a0..5a0e2c0e669 100644 --- a/src/types/function.rs +++ b/src/types/function.rs @@ -8,9 +8,9 @@ use crate::{ types::{PyCapsule, PyDict, PyModule, PyTuple}, }; use crate::{Bound, PyAny, PyResult, Python}; -use std::cell::UnsafeCell; -use std::ffi::CStr; -use std::ptr::NonNull; +use core::cell::UnsafeCell; +use core::ffi::CStr; +use core::ptr::NonNull; /// Represents a builtin Python function object. /// @@ -110,7 +110,7 @@ impl PyCFunction { // SAFETY: The arguments to `PyCFunction_NewEx` are valid, we are attached to the // interpreter and we know the function either returns a new reference or errors. unsafe { - ffi::PyCFunction_NewEx(method_def, capsule.as_ptr(), std::ptr::null_mut()) + ffi::PyCFunction_NewEx(method_def, capsule.as_ptr(), core::ptr::null_mut()) .assume_owned_or_err(py) .cast_into_unchecked() } diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 9ad41fb29ed..4d632e5261c 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -82,7 +82,7 @@ impl<'py> Bound<'py, PyIterator> { #[inline] pub fn send(&self, value: &Bound<'py, PyAny>) -> PyResult> { let py = self.py(); - let mut result = std::ptr::null_mut(); + let mut result = core::ptr::null_mut(); match unsafe { ffi::PyIter_Send(self.as_ptr(), value.as_ptr(), &mut result) } { ffi::PySendResult::PYGEN_ERROR => Err(PyErr::fetch(py)), ffi::PySendResult::PYGEN_RETURN => Ok(PySendResult::Return(unsafe { @@ -106,14 +106,14 @@ impl<'py> Iterator for Bound<'py, PyIterator> { /// to repeatedly result in the same exception. fn next(&mut self) -> Option { let py = self.py(); - let mut item = std::ptr::null_mut(); + let mut item = core::ptr::null_mut(); // SAFETY: `self` is a valid iterator object, `item` is a valid pointer to receive the next item match unsafe { ffi::compat::PyIter_NextItem(self.as_ptr(), &mut item) } { - std::ffi::c_int::MIN..=-1 => Some(Err(PyErr::fetch(py))), + core::ffi::c_int::MIN..=-1 => Some(Err(PyErr::fetch(py))), 0 => None, // SAFETY: `item` is guaranteed to be a non-null strong reference - 1..=std::ffi::c_int::MAX => Some(Ok(unsafe { item.assume_owned_unchecked(py) })), + 1..=core::ffi::c_int::MAX => Some(Ok(unsafe { item.assume_owned_unchecked(py) })), } } diff --git a/src/types/list.rs b/src/types/list.rs index 5d8b29bb310..d0b0945937d 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -5,9 +5,9 @@ use crate::internal_tricks::get_ssize_index; use crate::types::sequence::PySequenceMethods; use crate::types::{PySequence, PyTuple}; use crate::{Borrowed, Bound, BoundObject, IntoPyObject, IntoPyObjectExt, PyAny, PyErr, Python}; -use std::iter::FusedIterator; +use core::iter::FusedIterator; #[cfg(feature = "nightly")] -use std::num::NonZero; +use core::num::NonZero; /// Represents a Python `list`. /// @@ -701,7 +701,7 @@ impl<'py> Iterator for BoundListIterator<'py> { where Self: Sized, F: FnMut(B, Self::Item) -> R, - R: std::ops::Try, + R: core::ops::Try, { self.with_critical_section(|index, length, list| { let mut accum = init; @@ -874,7 +874,7 @@ impl DoubleEndedIterator for BoundListIterator<'_> { where Self: Sized, F: FnMut(B, Self::Item) -> R, - R: std::ops::Try, + R: core::ops::Try, { self.with_critical_section(|index, length, list| { let mut accum = init; @@ -946,7 +946,7 @@ mod tests { use crate::types::{PyList, PyTuple}; use crate::{IntoPyObject, PyResult, Python}; #[cfg(feature = "nightly")] - use std::num::NonZero; + use core::num::NonZero; #[test] fn test_new() { @@ -1486,7 +1486,7 @@ mod tests { }); } - use std::ops::Range; + use core::ops::Range; // An iterator that lies about its `size_hint` implementation. // See https://github.com/PyO3/pyo3/issues/2118 @@ -1531,8 +1531,8 @@ mod tests { #[cfg(panic = "unwind")] fn bad_intopyobject_doesnt_cause_leaks() { use crate::types::PyInt; - use std::convert::Infallible; - use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use core::convert::Infallible; + use core::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); struct Bad(usize); diff --git a/src/types/mapping.rs b/src/types/mapping.rs index fba32b7d701..531063c2192 100644 --- a/src/types/mapping.rs +++ b/src/types/mapping.rs @@ -197,22 +197,24 @@ impl<'py> PyMappingMethods<'py> for Bound<'py, PyMapping> { mod tests { use std::collections::HashMap; - use crate::{exceptions::PyKeyError, types::PyTuple}; + use crate::{ + exceptions::PyKeyError, + types::{IntoPyDict, PyTuple}, + }; use super::*; - use crate::conversion::IntoPyObject; #[test] fn test_len() { Python::attach(|py| { let mut v = HashMap::::new(); - let ob = (&v).into_pyobject(py).unwrap(); + let ob = (&v).into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); assert_eq!(0, mapping.len().unwrap()); assert!(mapping.is_empty().unwrap()); v.insert(7, 32); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping2 = ob.cast::().unwrap(); assert_eq!(1, mapping2.len().unwrap()); assert!(!mapping2.is_empty().unwrap()); @@ -224,7 +226,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert("key0", 1234); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); mapping.set_item("key1", "foo").unwrap(); @@ -239,7 +241,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); assert_eq!( 32, @@ -257,7 +259,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); assert!(mapping.set_item(7i32, 42i32).is_ok()); // change assert!(mapping.set_item(8i32, 123i32).is_ok()); // insert @@ -277,7 +279,7 @@ mod tests { Python::attach(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); assert!(mapping.del_item(7i32).is_ok()); assert_eq!(0, mapping.len().unwrap()); @@ -295,7 +297,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; @@ -317,7 +319,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; @@ -335,7 +337,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.into_pyobject(py).unwrap(); + let ob = v.into_py_dict(py).unwrap(); let mapping = ob.cast::().unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; diff --git a/src/types/mappingproxy.rs b/src/types/mappingproxy.rs index f8bc4ee727f..9e6200d6a65 100644 --- a/src/types/mappingproxy.rs +++ b/src/types/mappingproxy.rs @@ -8,7 +8,7 @@ use crate::types::any::PyAnyMethods; use crate::types::{PyAny, PyIterator, PyList}; use crate::{ffi, Python}; -use std::ffi::c_int; +use core::ffi::c_int; /// Represents a Python `mappingproxy`. #[repr(transparent)] @@ -16,7 +16,7 @@ pub struct PyMappingProxy(PyAny); #[inline] unsafe fn dict_proxy_check(op: *mut ffi::PyObject) -> c_int { - unsafe { ffi::Py_IS_TYPE(op, std::ptr::addr_of_mut!(ffi::PyDictProxy_Type)) } + unsafe { ffi::Py_IS_TYPE(op, core::ptr::addr_of_mut!(ffi::PyDictProxy_Type)) } } pyobject_native_type_core!( @@ -142,7 +142,8 @@ mod tests { exceptions::PyKeyError, types::{PyInt, PyTuple}, }; - use std::collections::{BTreeMap, HashMap}; + use alloc::collections::BTreeMap; + use std::collections::HashMap; #[test] fn test_new() { diff --git a/src/types/mod.rs b/src/types/mod.rs index bd2cc27b80c..149da079b00 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -132,7 +132,7 @@ macro_rules! pyobject_native_type_named ( #[macro_export] macro_rules! pyobject_native_static_type_object( ($typeobject:expr) => { - |_py| ::std::ptr::addr_of_mut!($typeobject) + |_py| ::core::ptr::addr_of_mut!($typeobject) }; ); @@ -167,7 +167,7 @@ macro_rules! pyobject_native_type_info( // SAFETY: macro caller has upheld the safety contracts unsafe impl<$($generics,)*> $crate::type_object::PyTypeInfo for $name { const NAME: &'static str = stringify!($name); - const MODULE: ::std::option::Option<&'static str> = $module; + const MODULE: ::core::option::Option<&'static str> = $module; $crate::pyobject_type_info_type_hint!($type_hint_module, $type_hint_name); #[inline] @@ -209,7 +209,7 @@ macro_rules! pyobject_native_type_core { $crate::pyobject_native_type_core!($name, $typeobject, $type_hint_module, $type_hint_name, #module=$module $(, #checkfunction=$checkfunction)? $(;$generics)*); }; ($name:ty, $typeobject:expr, $type_hint_module:expr, $type_hint_name:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => { - $crate::pyobject_native_type_core!($name, $typeobject, $type_hint_module, $type_hint_name, #module=::std::option::Option::Some("builtins") $(, #checkfunction=$checkfunction)? $(;$generics)*); + $crate::pyobject_native_type_core!($name, $typeobject, $type_hint_module, $type_hint_name, #module=::core::option::Option::Some("builtins") $(, #checkfunction=$checkfunction)? $(;$generics)*); }; } diff --git a/src/types/module.rs b/src/types/module.rs index 795ec737eeb..dec3c9325ac 100644 --- a/src/types/module.rs +++ b/src/types/module.rs @@ -10,11 +10,11 @@ use crate::types::{ use crate::{ exceptions, ffi, Borrowed, Bound, BoundObject, IntoPyObject, IntoPyObjectExt, Py, Python, }; -use std::borrow::Cow; +use alloc::borrow::Cow; #[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))] -use std::ffi::c_int; -use std::ffi::CStr; -use std::str; +use core::ffi::c_int; +use core::ffi::CStr; +use core::str; /// Represents a Python [`module`][1] object. /// @@ -141,10 +141,15 @@ impl PyModule { /// # Example: Load a file at runtime with [`std::fs::read_to_string`]. /// /// ```rust + /// # extern crate alloc; /// use pyo3::prelude::*; /// use pyo3::ffi::c_str; - /// use std::ffi::CString; + /// use alloc::ffi::CString; /// + /// # #[cfg(not(feature = "std"))] + /// # fn main() {} + /// + /// # #[cfg(feature = "std")] /// # fn main() -> PyResult<()> { /// # #[cfg(not(target_arch = "wasm32"))] // node fs doesn't see this file, maybe cwd wrong? /// # { diff --git a/src/types/mutex.rs b/src/types/mutex.rs index f72115431d8..22103136466 100644 --- a/src/types/mutex.rs +++ b/src/types/mutex.rs @@ -1,8 +1,8 @@ -use std::cell::UnsafeCell; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; +use core::cell::UnsafeCell; +use core::marker::PhantomData; +use core::ops::{Deref, DerefMut}; #[cfg(panic = "unwind")] -use std::sync::atomic::{AtomicBool, Ordering}; +use core::sync::atomic::{AtomicBool, Ordering}; use std::sync::{LockResult, PoisonError}; #[cfg(panic = "unwind")] use std::thread; @@ -271,10 +271,11 @@ impl<'a, T> DerefMut for PyMutexGuard<'a, T> { #[cfg(test)] mod tests { #[cfg(not(target_arch = "wasm32"))] - use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, Barrier, - }; + use alloc::sync::Arc; + #[cfg(not(target_arch = "wasm32"))] + use core::sync::atomic::{AtomicBool, Ordering}; + #[cfg(not(target_arch = "wasm32"))] + use std::sync::Barrier; use super::*; #[cfg(not(target_arch = "wasm32"))] @@ -352,7 +353,7 @@ mod tests { // the other thread isn't blocked on acquiring the mutex yet. // If PyMutex had a try_lock implementation this would be // unnecessary - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // block (and hold the mutex) until the receiver actually receives something barrier.wait(); finished.store(true, Ordering::SeqCst); @@ -363,7 +364,7 @@ mod tests { s.spawn(|| { while !first_thread_locked_once.load(Ordering::SeqCst) { - std::hint::spin_loop(); + core::hint::spin_loop(); } second_thread_locked_once.store(true, Ordering::SeqCst); let guard = mutex.lock(); diff --git a/src/types/num.rs b/src/types/num.rs index 8b6129b5f7d..d2072b57b80 100644 --- a/src/types/num.rs +++ b/src/types/num.rs @@ -1,6 +1,6 @@ use super::any::PyAnyMethods; use crate::{ffi, instance::Bound, IntoPyObject, PyAny, Python}; -use std::convert::Infallible; +use core::convert::Infallible; /// Represents a Python `int` object. /// diff --git a/src/types/sequence.rs b/src/types/sequence.rs index ac89053bd84..08104583607 100644 --- a/src/types/sequence.rs +++ b/src/types/sequence.rs @@ -362,7 +362,7 @@ impl<'py> PySequenceMethods<'py> for Bound<'py, PySequence> { mod tests { use crate::types::{PyAnyMethods, PyList, PySequence, PySequenceMethods, PyTuple}; use crate::{IntoPyObject, Py, PyAny, PyTypeInfo, Python}; - use std::ptr; + use core::ptr; fn get_object() -> Py { // Convenience function for getting a single unique object diff --git a/src/types/set.rs b/src/types/set.rs index c724bb944d6..597c60db2d2 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -6,7 +6,7 @@ use crate::{ py_result_ext::PyResultExt, }; use crate::{ffi, Borrowed, BoundObject, IntoPyObject, IntoPyObjectExt, PyAny, Python}; -use std::ptr; +use core::ptr; /// Represents a Python `set`. /// @@ -266,12 +266,14 @@ impl ExactSizeIterator for BoundSetIterator<'_> { #[cfg(test)] mod tests { + #![allow(unused_imports, reason = "conditional compilation")] use super::PySet; use crate::{ conversion::IntoPyObject, types::{PyAnyMethods, PySetMethods}, Python, }; + #[cfg(feature = "std")] use std::collections::HashSet; #[test] @@ -295,6 +297,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn test_set_len() { Python::attach(|py| { let mut v = HashSet::::new(); diff --git a/src/types/slice.rs b/src/types/slice.rs index b02c684e63f..28b980bb9e8 100644 --- a/src/types/slice.rs +++ b/src/types/slice.rs @@ -7,7 +7,7 @@ use crate::inspect::PyStaticExpr; use crate::type_object::PyTypeInfo; use crate::types::{PyRange, PyRangeMethods}; use crate::{Bound, IntoPyObject, PyAny, Python}; -use std::convert::Infallible; +use core::convert::Infallible; /// Represents a Python `slice`. /// diff --git a/src/types/string.rs b/src/types/string.rs index a2010d3f434..5d01829cd44 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -6,9 +6,9 @@ use crate::py_result_ext::PyResultExt; use crate::types::bytes::PyBytesMethods; use crate::types::PyBytes; use crate::{ffi, Bound, Py, PyAny, PyResult, Python}; -use std::borrow::Cow; -use std::ffi::CStr; -use std::{fmt, str}; +use alloc::borrow::Cow; +use core::ffi::CStr; +use core::{fmt, str}; /// Represents raw data backing a Python `str`. /// @@ -34,10 +34,10 @@ impl<'a> PyStringData<'a> { match self { Self::Ucs1(s) => s, Self::Ucs2(s) => unsafe { - std::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) + core::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) }, Self::Ucs4(s) => unsafe { - std::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) + core::slice::from_raw_parts(s.as_ptr().cast(), s.len() * self.value_width_bytes()) }, } } @@ -83,7 +83,7 @@ impl<'a> PyStringData<'a> { .into()) } }, - Self::Ucs4(data) => match data.iter().map(|&c| std::char::from_u32(c)).collect() { + Self::Ucs4(data) => match data.iter().map(|&c| core::char::from_u32(c)).collect() { Some(s) => Ok(Cow::Owned(s)), None => Err(PyUnicodeDecodeError::new( py, @@ -111,7 +111,7 @@ impl<'a> PyStringData<'a> { Self::Ucs2(data) => Cow::Owned(String::from_utf16_lossy(data)), Self::Ucs4(data) => Cow::Owned( data.iter() - .map(|&c| std::char::from_u32(c).unwrap_or('\u{FFFD}')) + .map(|&c| core::char::from_u32(c).unwrap_or('\u{FFFD}')) .collect(), ), } @@ -217,8 +217,8 @@ impl PyString { encoding: Option<&CStr>, errors: Option<&CStr>, ) -> PyResult> { - let encoding = encoding.map_or(std::ptr::null(), CStr::as_ptr); - let errors = errors.map_or(std::ptr::null(), CStr::as_ptr); + let encoding = encoding.map_or(core::ptr::null(), CStr::as_ptr); + let errors = errors.map_or(core::ptr::null(), CStr::as_ptr); // Safety: // - `src` is a valid Python object // - `encoding` and `errors` are either null or valid C strings. `encoding` and `errors` are @@ -246,7 +246,7 @@ impl PyString { #[cfg(all(Py_3_14, not(Py_LIMITED_API)))] { use crate::fmt::PyUnicodeWriter; - use std::fmt::Write as _; + use core::fmt::Write as _; let mut writer = PyUnicodeWriter::new(py)?; writer @@ -348,7 +348,7 @@ impl<'a> Borrowed<'a, '_, PyString> { Err(crate::PyErr::fetch(self.py())) } else { Ok(unsafe { - std::str::from_utf8_unchecked(std::slice::from_raw_parts(data, size as usize)) + core::str::from_utf8_unchecked(core::slice::from_raw_parts(data, size as usize)) }) } } @@ -410,15 +410,15 @@ impl<'a> Borrowed<'a, '_, PyString> { let kind = ffi::PyUnicode_KIND(ptr); match kind { - ffi::PyUnicode_1BYTE_KIND => Ok(PyStringData::Ucs1(std::slice::from_raw_parts( + ffi::PyUnicode_1BYTE_KIND => Ok(PyStringData::Ucs1(core::slice::from_raw_parts( raw_data as *const u8, length, ))), - ffi::PyUnicode_2BYTE_KIND => Ok(PyStringData::Ucs2(std::slice::from_raw_parts( + ffi::PyUnicode_2BYTE_KIND => Ok(PyStringData::Ucs2(core::slice::from_raw_parts( raw_data as *const u16, length, ))), - ffi::PyUnicode_4BYTE_KIND => Ok(PyStringData::Ucs4(std::slice::from_raw_parts( + ffi::PyUnicode_4BYTE_KIND => Ok(PyStringData::Ucs4(core::slice::from_raw_parts( raw_data as *const u32, length, ))), diff --git a/src/types/tuple.rs b/src/types/tuple.rs index 82b323f7fd6..3aba6363aac 100644 --- a/src/types/tuple.rs +++ b/src/types/tuple.rs @@ -12,9 +12,9 @@ use crate::types::{sequence::PySequenceMethods, PyList, PySequence}; use crate::{ exceptions, Bound, FromPyObject, IntoPyObject, IntoPyObjectExt, PyAny, PyErr, PyResult, Python, }; -use std::iter::FusedIterator; +use core::iter::FusedIterator; #[cfg(feature = "nightly")] -use std::num::NonZero; +use core::num::NonZero; #[inline] #[track_caller] @@ -271,7 +271,7 @@ impl<'py> PyTupleMethods<'py> for Bound<'py, PyTuple> { // SAFETY: self is known to be a tuple object, and tuples are immutable let items = unsafe { &(*self.as_ptr().cast::()).ob_item }; // SAFETY: Bound<'py, PyAny> has the same memory layout as *mut ffi::PyObject - unsafe { std::slice::from_raw_parts(items.as_ptr().cast(), self.len()) } + unsafe { core::slice::from_raw_parts(items.as_ptr().cast(), self.len()) } } #[inline] @@ -671,7 +671,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ // We need this to drop the arguments correctly. let args_bound = [$(self.$n.into_bound_py_any(py)?,)*]; // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; unsafe { ffi::PyObject_VectorcallDict( function.as_ptr(), @@ -705,13 +705,13 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ } // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; unsafe { ffi::PyObject_Vectorcall( function.as_ptr(), args.as_mut_ptr().add(1), $length + ffi::PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -747,7 +747,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ args.as_mut_ptr(), // +1 for the receiver. 1 + $length + ffi::PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -800,7 +800,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ // We need this to drop the arguments correctly. let args_bound = [$(self.$n.into_bound_py_any(py)?,)*]; // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; unsafe { ffi::PyObject_VectorcallDict( function.as_ptr(), @@ -834,13 +834,13 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ } // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_bound[$n].as_ptr()),*]; unsafe { ffi::PyObject_Vectorcall( function.as_ptr(), args.as_mut_ptr().add(1), $length + ffi::PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -876,7 +876,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ args.as_mut_ptr(), // +1 for the receiver. 1 + $length + ffi::PY_VECTORCALL_ARGUMENTS_OFFSET, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -1067,10 +1067,10 @@ tuple_conversion!( mod tests { use crate::types::{any::PyAnyMethods, tuple::PyTupleMethods, PyList, PyTuple}; use crate::{IntoPyObject, Python}; - use std::collections::HashSet; #[cfg(feature = "nightly")] - use std::num::NonZero; - use std::ops::Range; + use core::num::NonZero; + use core::ops::Range; + use std::collections::HashSet; #[test] fn test_new() { Python::attach(|py| { @@ -1445,8 +1445,8 @@ mod tests { #[cfg(panic = "unwind")] fn bad_intopyobject_doesnt_cause_leaks() { use crate::types::PyInt; - use std::convert::Infallible; - use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use core::convert::Infallible; + use core::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); @@ -1508,8 +1508,8 @@ mod tests { #[cfg(panic = "unwind")] fn bad_intopyobject_doesnt_cause_leaks_2() { use crate::types::PyInt; - use std::convert::Infallible; - use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use core::convert::Infallible; + use core::sync::atomic::{AtomicUsize, Ordering::SeqCst}; static NEEDS_DESTRUCTING_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/src/types/weakref/anyref.rs b/src/types/weakref/anyref.rs index 15e3d09d455..615cef2d40e 100644 --- a/src/types/weakref/anyref.rs +++ b/src/types/weakref/anyref.rs @@ -353,11 +353,11 @@ pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakref> { fn upgrade(&self) -> Option> { - let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); + let mut obj: *mut ffi::PyObject = core::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { - std::ffi::c_int::MIN..=-1 => panic!("The 'weakref' weak reference instance should be valid (non-null and actually a weakref reference)"), + core::ffi::c_int::MIN..=-1 => panic!("The 'weakref' weak reference instance should be valid (non-null and actually a weakref reference)"), 0 => None, - 1..=std::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), + 1..=core::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } @@ -384,7 +384,7 @@ mod tests { use crate::types::PyInt; use crate::PyTypeCheck; use crate::{py_result_ext::PyResultExt, types::PyType}; - use std::ptr; + use core::ptr; fn get_type(py: Python<'_>) -> PyResult> { py.run(c"class A:\n pass\n", None, None)?; @@ -551,7 +551,7 @@ mod tests { mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; - use std::ptr; + use core::ptr; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} diff --git a/src/types/weakref/proxy.rs b/src/types/weakref/proxy.rs index 617ebf043a2..75e7a10901d 100644 --- a/src/types/weakref/proxy.rs +++ b/src/types/weakref/proxy.rs @@ -181,11 +181,11 @@ impl PyWeakrefProxy { impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefProxy> { fn upgrade(&self) -> Option> { - let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); + let mut obj: *mut ffi::PyObject = core::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { - std::ffi::c_int::MIN..=-1 => panic!("The 'weakref.ProxyType' (or `weakref.CallableProxyType`) instance should be valid (non-null and actually a weakref reference)"), + core::ffi::c_int::MIN..=-1 => panic!("The 'weakref.ProxyType' (or `weakref.CallableProxyType`) instance should be valid (non-null and actually a weakref reference)"), 0 => None, - 1..=std::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), + 1..=core::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } @@ -257,7 +257,7 @@ mod tests { use crate::types::PyInt; use crate::PyTypeCheck; use crate::{py_result_ext::PyResultExt, types::PyDict, types::PyType}; - use std::ptr; + use core::ptr; fn get_type(py: Python<'_>) -> PyResult> { let globals = PyDict::new(py); @@ -459,7 +459,7 @@ mod tests { mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; - use std::ptr; + use core::ptr; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} @@ -615,7 +615,7 @@ mod tests { use super::*; use crate::PyTypeCheck; use crate::{py_result_ext::PyResultExt, types::PyDict, types::PyType}; - use std::ptr; + use core::ptr; fn get_type(py: Python<'_>) -> PyResult> { let globals = PyDict::new(py); @@ -776,7 +776,7 @@ mod tests { mod pyo3_pyclass { use super::*; use crate::{pyclass, pymethods, Py}; - use std::ptr; + use core::ptr; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} diff --git a/src/types/weakref/reference.rs b/src/types/weakref/reference.rs index ead294f1373..989ddadb53a 100644 --- a/src/types/weakref/reference.rs +++ b/src/types/weakref/reference.rs @@ -187,11 +187,11 @@ impl PyWeakrefReference { impl<'py> PyWeakrefMethods<'py> for Bound<'py, PyWeakrefReference> { fn upgrade(&self) -> Option> { - let mut obj: *mut ffi::PyObject = std::ptr::null_mut(); + let mut obj: *mut ffi::PyObject = core::ptr::null_mut(); match unsafe { ffi::compat::PyWeakref_GetRef(self.as_ptr(), &mut obj) } { - std::ffi::c_int::MIN..=-1 => panic!("The 'weakref.ReferenceType' instance should be valid (non-null and actually a weakref reference)"), + core::ffi::c_int::MIN..=-1 => panic!("The 'weakref.ReferenceType' instance should be valid (non-null and actually a weakref reference)"), 0 => None, - 1..=std::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), + 1..=core::ffi::c_int::MAX => Some(unsafe { obj.assume_owned_unchecked(self.py()) }), } } } @@ -248,7 +248,7 @@ mod tests { use super::*; use crate::PyTypeInfo; use crate::{py_result_ext::PyResultExt, types::PyType}; - use std::ptr; + use core::ptr; fn get_type(py: Python<'_>) -> PyResult> { py.run(c"class A:\n pass\n", None, None)?; @@ -399,7 +399,7 @@ mod tests { mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; - use std::ptr; + use core::ptr; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} diff --git a/src/version.rs b/src/version.rs index 48d8b5d36a8..55f2ab70b1c 100644 --- a/src/version.rs +++ b/src/version.rs @@ -82,13 +82,13 @@ impl PartialEq<(u8, u8, u8)> for PythonVersionInfo<'_> { } impl PartialOrd<(u8, u8)> for PythonVersionInfo<'_> { - fn partial_cmp(&self, other: &(u8, u8)) -> Option { + fn partial_cmp(&self, other: &(u8, u8)) -> Option { (self.major, self.minor).partial_cmp(other) } } impl PartialOrd<(u8, u8, u8)> for PythonVersionInfo<'_> { - fn partial_cmp(&self, other: &(u8, u8, u8)) -> Option { + fn partial_cmp(&self, other: &(u8, u8, u8)) -> Option { (self.major, self.minor, self.patch).partial_cmp(other) } } diff --git a/tests/test_datetime_import.rs b/tests/test_datetime_import.rs index 92298504fa3..c611d3bbf7f 100644 --- a/tests/test_datetime_import.rs +++ b/tests/test_datetime_import.rs @@ -18,7 +18,7 @@ fn test_bad_datetime_module_panic() { let sys = py.import("sys").unwrap(); sys.getattr("path") .unwrap() - .call_method1("insert", (0, tmpdir.path().as_os_str())) + .call_method1("insert", (0, tmpdir.path().to_str().unwrap())) .unwrap(); // This should panic because the "datetime" module is empty diff --git a/tests/test_exceptions.rs b/tests/test_exceptions.rs index d09dd0a1dc2..f5c50e54383 100644 --- a/tests/test_exceptions.rs +++ b/tests/test_exceptions.rs @@ -4,13 +4,13 @@ use pyo3::prelude::*; use pyo3::{exceptions, py_run}; use std::error::Error; use std::fmt; -#[cfg(not(target_os = "windows"))] +#[cfg(all(feature = "std", not(target_os = "windows")))] use std::fs::File; mod test_utils; #[pyfunction] -#[cfg(not(target_os = "windows"))] +#[cfg(all(feature = "std", not(target_os = "windows")))] fn fail_to_open_file() -> PyResult<()> { File::open("not_there.txt")?; Ok(()) @@ -18,7 +18,7 @@ fn fail_to_open_file() -> PyResult<()> { #[test] #[cfg_attr(target_arch = "wasm32", ignore)] // Not sure why this fails. -#[cfg(not(target_os = "windows"))] +#[cfg(all(feature = "std", not(target_os = "windows")))] fn test_filenotfounderror() { Python::attach(|py| { let fail_to_open_file = wrap_pyfunction!(fail_to_open_file)(py).unwrap(); @@ -84,15 +84,16 @@ fn test_custom_error() { #[test] fn test_exception_nosegfault() { - use std::net::TcpListener; + #[cfg(feature = "std")] fn io_err() -> PyResult<()> { - TcpListener::bind("no:address")?; + std::net::TcpListener::bind("no:address")?; Ok(()) } fn parse_int() -> PyResult<()> { "@_@".parse::()?; Ok(()) } + #[cfg(feature = "std")] assert!(io_err().is_err()); assert!(parse_int().is_err()); } diff --git a/tests/test_frompy_intopy_roundtrip.rs b/tests/test_frompy_intopy_roundtrip.rs index c4b120c5292..211872035ac 100644 --- a/tests/test_frompy_intopy_roundtrip.rs +++ b/tests/test_frompy_intopy_roundtrip.rs @@ -2,8 +2,7 @@ use pyo3::types::{PyDict, PyString}; use pyo3::{prelude::*, IntoPyObject, IntoPyObjectExt, IntoPyObjectRef}; -use std::collections::HashMap; -use std::hash::Hash; +use std::collections::BTreeMap; #[macro_use] mod test_utils; @@ -106,12 +105,12 @@ fn test_generic_transparent_named_field_struct() { } #[derive(Debug, IntoPyObject, IntoPyObjectRef, FromPyObject)] -pub struct GenericWithBound(HashMap); +pub struct GenericWithBound(BTreeMap); #[test] fn test_generic_with_bound() { Python::attach(|py| { - let mut hash_map = HashMap::::new(); + let mut hash_map = BTreeMap::::new(); hash_map.insert("1".into(), 1); hash_map.insert("2".into(), 2); let map = GenericWithBound(hash_map); diff --git a/tests/test_frompyobject.rs b/tests/test_frompyobject.rs index b991b558a69..d0a5cacb2db 100644 --- a/tests/test_frompyobject.rs +++ b/tests/test_frompyobject.rs @@ -109,7 +109,7 @@ fn test_generic_transparent_named_field_struct() { } #[derive(Debug, FromPyObject)] -pub struct GenericWithBound(std::collections::HashMap); +pub struct GenericWithBound(std::collections::BTreeMap); #[test] fn test_generic_with_bound() { diff --git a/tests/test_intopyobject.rs b/tests/test_intopyobject.rs index 72ecc0f234d..84c767444ff 100644 --- a/tests/test_intopyobject.rs +++ b/tests/test_intopyobject.rs @@ -2,7 +2,7 @@ use pyo3::types::{PyDict, PyList, PyString}; use pyo3::{prelude::*, py_run, IntoPyObject, IntoPyObjectExt}; -use std::collections::HashMap; +use std::collections::BTreeMap; use std::hash::Hash; #[macro_use] @@ -90,12 +90,12 @@ fn test_generic_transparent_named_field_struct() { } #[derive(Debug, IntoPyObject)] -pub struct GenericWithBound(HashMap); +pub struct GenericWithBound(BTreeMap); #[test] fn test_generic_with_bound() { Python::attach(|py| { - let mut hash_map = HashMap::::new(); + let mut hash_map = BTreeMap::::new(); hash_map.insert("1".into(), 1); hash_map.insert("2".into(), 2); let map = GenericWithBound(hash_map).into_pyobject(py).unwrap(); diff --git a/tests/test_pyfunction.rs b/tests/test_pyfunction.rs index da12311f9e3..94255f6d0b4 100644 --- a/tests/test_pyfunction.rs +++ b/tests/test_pyfunction.rs @@ -1,7 +1,7 @@ #![cfg(feature = "macros")] #![warn(unsafe_op_in_unsafe_fn)] -use std::collections::HashMap; +use std::collections::BTreeMap; #[cfg(not(Py_LIMITED_API))] use pyo3::buffer::PyBuffer; @@ -586,9 +586,9 @@ fn return_value_borrows_from_arguments<'py>( py: Python<'py>, key: &'py Key, value: &'py Value, -) -> HashMap<&'py str, i32> { +) -> BTreeMap<&'py str, i32> { py.detach(move || { - let mut map = HashMap::new(); + let mut map = BTreeMap::new(); map.insert(key.0.as_str(), value.0); map })