From 68dc3da1e2f25ac684b0b95a2784144a55b19c0d Mon Sep 17 00:00:00 2001 From: person93 Date: Sun, 10 May 2026 18:39:32 -0400 Subject: [PATCH 1/3] add clippy lints to prepare for `no_std` support --- src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 50692aa4af7..a90c5fdff3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,8 @@ +#![warn( + clippy::alloc_instead_of_core, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core +)] #![warn(missing_docs)] #![cfg_attr( feature = "nightly", @@ -336,6 +341,9 @@ //! [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; + pub use crate::class::*; pub use crate::conversion::{FromPyObject, IntoPyObject, IntoPyObjectExt}; pub use crate::err::{CastError, CastIntoError, PyErr, PyErrArguments, PyResult, ToPyErr}; From e54cf76957aba3e9d393236c7985af2caf118123 Mon Sep 17 00:00:00 2001 From: person93 Date: Sun, 10 May 2026 18:46:14 -0400 Subject: [PATCH 2/3] import from `alloc` or `core` instead of `std` --- src/buffer.rs | 44 +++++++------- src/byteswriter.rs | 6 +- src/call.rs | 2 +- src/conversion.rs | 12 ++-- src/conversions/anyhow.rs | 2 +- src/conversions/bigdecimal.rs | 4 +- src/conversions/chrono.rs | 9 +-- src/conversions/chrono_tz.rs | 4 +- src/conversions/either.rs | 6 +- src/conversions/eyre.rs | 2 +- src/conversions/hashbrown.rs | 2 +- src/conversions/indexmap.rs | 2 +- src/conversions/jiff.rs | 14 ++--- src/conversions/num_bigint.rs | 12 ++-- src/conversions/num_complex.rs | 6 +- src/conversions/ordered_float.rs | 6 +- src/conversions/rust_decimal.rs | 4 +- src/conversions/std/array.rs | 11 ++-- src/conversions/std/cell.rs | 2 +- src/conversions/std/cstring.rs | 7 ++- src/conversions/std/ipaddr.rs | 4 +- src/conversions/std/map.rs | 6 +- src/conversions/std/num.rs | 20 +++---- src/conversions/std/osstr.rs | 14 ++--- src/conversions/std/path.rs | 4 +- src/conversions/std/set.rs | 6 +- src/conversions/std/slice.rs | 6 +- src/conversions/std/string.rs | 5 +- src/conversions/std/time.rs | 5 +- src/conversions/uuid.rs | 2 +- src/coroutine.rs | 6 +- src/coroutine/cancel.rs | 7 ++- src/coroutine/waker.rs | 4 +- src/err/cast_error.rs | 28 ++++----- src/err/downcast_error.rs | 24 ++++---- src/err/err_state.rs | 18 +++--- src/err/impls.rs | 48 ++++++++-------- src/err/mod.rs | 36 ++++++------ src/exceptions.rs | 34 +++++------ src/ffi/tests.rs | 4 +- src/fmt.rs | 10 ++-- src/impl_/callback.rs | 20 +++---- src/impl_/coroutine.rs | 2 +- src/impl_/extract_argument.rs | 24 ++++---- src/impl_/freelist.rs | 2 +- src/impl_/frompyobject.rs | 8 +-- src/impl_/panic.rs | 2 +- src/impl_/pyclass.rs | 39 +++++++------ src/impl_/pyclass/doc.rs | 8 +-- src/impl_/pyclass/lazy_type_object.rs | 9 +-- src/impl_/pyclass/probes.rs | 2 +- src/impl_/pyclass_init.rs | 5 +- src/impl_/pyfunction.rs | 6 +- src/impl_/pymethods.rs | 13 +++-- src/impl_/pymodule.rs | 31 +++++----- src/impl_/trampoline.rs | 12 ++-- src/impl_/unindent.rs | 2 +- src/impl_/wrap.rs | 2 +- src/inspect.rs | 4 +- src/instance.rs | 82 +++++++++++++-------------- src/internal/get_slot.rs | 22 +++---- src/internal/state.rs | 16 +++--- src/internal_tricks.rs | 6 +- src/macros.rs | 10 ++-- src/marker.rs | 22 +++---- src/marshal.rs | 2 +- src/panic.rs | 2 +- src/pybacked.rs | 27 ++++----- src/pycell.rs | 16 +++--- src/pycell/impl_.rs | 16 +++--- src/pyclass.rs | 6 +- src/pyclass/create_type_object.rs | 28 ++++----- src/pyclass/gc.rs | 4 +- src/pyclass/guard.rs | 24 ++++---- src/pyclass_init.rs | 2 +- src/sealed.rs | 4 +- src/sync.rs | 38 ++++++------- src/sync/critical_section.rs | 24 ++++---- src/tests/hygiene/pyclass.rs | 10 ++-- src/tests/hygiene/pyfunction.rs | 4 +- src/tests/hygiene/pymethods.rs | 60 ++++++++++---------- src/tests/hygiene/pymodule.rs | 6 +- src/type_object.rs | 2 +- src/types/any.rs | 26 ++++----- src/types/boolobject.rs | 4 +- src/types/bytearray.rs | 12 ++-- src/types/bytes.rs | 20 +++---- src/types/capsule.rs | 39 +++++++------ src/types/code.rs | 2 +- src/types/complex.rs | 4 +- src/types/datetime.rs | 4 +- src/types/dict.rs | 25 ++++---- src/types/float.rs | 4 +- src/types/frame.rs | 2 +- src/types/frozenset.rs | 2 +- src/types/function.rs | 8 +-- src/types/iterator.rs | 8 +-- src/types/list.rs | 16 +++--- src/types/mappingproxy.rs | 3 +- src/types/mod.rs | 6 +- src/types/module.rs | 12 ++-- src/types/mutex.rs | 25 ++++---- src/types/num.rs | 2 +- src/types/sequence.rs | 2 +- src/types/set.rs | 2 +- src/types/slice.rs | 2 +- src/types/string.rs | 28 ++++----- src/types/tuple.rs | 36 ++++++------ src/types/weakref/anyref.rs | 18 +++--- src/types/weakref/proxy.rs | 14 ++--- src/types/weakref/reference.rs | 10 ++-- src/version.rs | 4 +- 112 files changed, 708 insertions(+), 704 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index c9f9e70d913..ef89806b66c 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(()) @@ -691,13 +691,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 { @@ -735,7 +735,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 @@ -817,7 +817,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 @@ -943,8 +943,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 80659a633ed..4509ac338a2 100644 --- a/src/byteswriter.rs +++ b/src/byteswriter.rs @@ -16,12 +16,12 @@ 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}, }; +use std::io::IoSlice; pub struct PyBytesWriter<'py> { python: Python<'py>, @@ -211,7 +211,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) } } 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 142215ed76b..200793ab81f 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -11,8 +11,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. /// @@ -375,9 +375,9 @@ impl<'py, T> IntoPyObjectExt<'py> for T where T: IntoPyObject<'py> {} /// The output type may also depend on the Python lifetime `'py`. This allows the output type to /// keep interacting with the Python interpreter. See also [`Bound<'py, T>`]. /// -/// [`Cow<'a, str>`]: std::borrow::Cow -/// [`Cow::Borrowed`]: std::borrow::Cow::Borrowed -/// [`Cow::Owned`]: std::borrow::Cow::Owned +/// [`Cow<'a, str>`]: alloc::borrow::Cow +/// [`Cow::Borrowed`]: alloc::borrow::Cow::Borrowed +/// [`Cow::Owned`]: alloc::borrow::Cow::Owned /// [guide]: https://pyo3.rs/latest/conversions/traits.html#deriving-frompyobject pub trait FromPyObject<'a, 'py>: Sized { /// The type returned in the event of a conversion error. @@ -506,7 +506,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..2ff959546ef 100644 --- a/src/conversions/anyhow.rs +++ b/src/conversions/anyhow.rs @@ -56,7 +56,7 @@ //! # Example: Using `anyhow` in general //! //! Note that you don't need this feature to convert a [`PyErr`] into an [`anyhow::Error`], 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::*; 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 dd3f7aef5ee..5c40511a60e 100644 --- a/src/conversions/either.rs +++ b/src/conversions/either.rs @@ -118,8 +118,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)) } @@ -128,7 +128,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..1aaaaf0d176 100644 --- a/src/conversions/eyre.rs +++ b/src/conversions/eyre.rs @@ -58,7 +58,7 @@ //! # 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::*; 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 c11ca92e6a5..8415f1b03c6 100644 --- a/src/conversions/num_bigint.rs +++ b/src/conversions/num_bigint.rs @@ -266,7 +266,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 9e4ad01aae9..64da5acf30c 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..d75aead28b3 100644 --- a/src/conversions/std/array.rs +++ b/src/conversions/std/array.rs @@ -17,7 +17,7 @@ where #[cfg(feature = "experimental-inspect")] const OUTPUT_TYPE: PyStaticExpr = T::SEQUENCE_OUTPUT_TYPE; - /// Turns [`[u8; N]`](std::array) into [`PyBytes`], all other `T`s will be turned into a [`PyList`] + /// Turns [`[u8; N]`](core::array) into [`PyBytes`], all other `T`s will be turned into a [`PyList`] /// /// [`PyBytes`]: crate::types::PyBytes /// [`PyList`]: crate::types::PyList @@ -82,7 +82,7 @@ where }) } -// TODO use std::array::try_from_fn, if that stabilises: +// TODO use core::array::try_from_fn, if that stabilises: // (https://github.com/rust-lang/rust/issues/89379) fn array_try_from_fn(mut cb: F) -> Result<[T; N], E> where @@ -133,10 +133,9 @@ pub(crate) fn invalid_sequence_length(expected: usize, actual: usize) -> PyErr { #[cfg(test)] mod tests { #[cfg(panic = "unwind")] - use std::{ - panic, - sync::atomic::{AtomicUsize, Ordering}, - }; + use core::sync::atomic::{AtomicUsize, Ordering}; + #[cfg(panic = "unwind")] + use std::panic; use crate::{ conversion::IntoPyObject, 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 43f5aaefcc1..8ff48a51272 100644 --- a/src/conversions/std/cstring.rs +++ b/src/conversions/std/cstring.rs @@ -5,12 +5,13 @@ 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 alloc::borrow::Cow; +use core::ffi::CStr; +use std::ffi::CString; #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] use { crate::{exceptions::PyValueError, ffi}, - std::slice, + core::slice, }; impl<'py> IntoPyObject<'py> for &CStr { 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 b03b3800bb8..b2588eece67 100644 --- a/src/conversions/std/map.rs +++ b/src/conversions/std/map.rs @@ -8,7 +8,8 @@ use crate::{ types::{any::PyAnyMethods, dict::PyDictMethods, PyDict}, Borrowed, FromPyObject, PyAny, PyErr, Python, }; -use std::{cmp, collections, hash}; +use core::{cmp, hash}; +use std::collections; impl<'py, K, V, H> IntoPyObject<'py> for collections::HashMap where @@ -154,7 +155,8 @@ where #[cfg(test)] mod tests { use super::*; - use std::collections::{BTreeMap, HashMap}; + use alloc::collections::BTreeMap; + use std::collections::HashMap; #[test] fn test_hashmap_to_python() { diff --git a/src/conversions/std/num.rs b/src/conversions/std/num.rs index fb122c279ef..2fca7aa9ff3 100644 --- a/src/conversions/std/num.rs +++ b/src/conversions/std/num.rs @@ -8,10 +8,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, }; @@ -278,7 +278,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(()) }; @@ -310,7 +310,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)?; @@ -404,7 +404,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 { @@ -653,7 +653,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! { @@ -843,7 +843,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() { @@ -990,7 +990,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..02b72a55fe3 100644 --- a/src/conversions/std/osstr.rs +++ b/src/conversions/std/osstr.rs @@ -12,8 +12,8 @@ use crate::types::PyString; #[cfg(any(unix, target_os = "emscripten"))] use crate::types::{PyBytes, PyBytesMethods}; use crate::{Borrowed, FromPyObject, PyAny, PyErr, Python}; -use std::borrow::Cow; -use std::convert::Infallible; +use alloc::borrow::Cow; +use core::convert::Infallible; use std::ffi::{OsStr, OsString}; #[cfg(any(unix, target_os = "emscripten"))] use std::os::unix::ffi::OsStrExt; @@ -128,7 +128,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!( @@ -228,15 +228,13 @@ mod tests { use crate::exceptions::PyFileNotFoundError; use crate::types::{PyAnyMethods, PyString, PyStringMethods}; use crate::{Bound, BoundObject, IntoPyObject, Python}; - use std::fmt::Debug; + use alloc::borrow::Cow; + use core::fmt::Debug; + use std::ffi::{OsStr, OsString}; #[cfg(any(unix, target_os = "emscripten"))] use std::os::unix::ffi::OsStringExt; #[cfg(windows)] use std::os::windows::ffi::OsStringExt; - use std::{ - borrow::Cow, - ffi::{OsStr, OsString}, - }; #[test] #[cfg(any(unix, target_os = "emscripten"))] diff --git a/src/conversions/std/path.rs b/src/conversions/std/path.rs index d83a85e47a0..cbf820caa50 100644 --- a/src/conversions/std/path.rs +++ b/src/conversions/std/path.rs @@ -5,7 +5,7 @@ use crate::inspect::{type_hint_identifier, type_hint_subscript, type_hint_union, use crate::sync::PyOnceLock; use crate::types::any::PyAnyMethods; use crate::{ffi, Borrowed, Bound, FromPyObject, Py, PyAny, PyErr, Python}; -use std::borrow::Cow; +use alloc::borrow::Cow; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -138,9 +138,9 @@ mod tests { types::{PyAnyMethods, PyString}, IntoPyObjectExt, }; + use core::fmt::Debug; #[cfg(not(target_os = "wasi"))] use std::ffi::OsStr; - use std::fmt::Debug; #[cfg(any(unix, target_os = "emscripten"))] use std::os::unix::ffi::OsStringExt; #[cfg(windows)] diff --git a/src/conversions/std/set.rs b/src/conversions/std/set.rs index c80fe239890..ce8f4ecf108 100644 --- a/src/conversions/std/set.rs +++ b/src/conversions/std/set.rs @@ -1,4 +1,5 @@ -use std::{cmp, collections, hash}; +use core::{cmp, hash}; +use std::collections; #[cfg(feature = "experimental-inspect")] use crate::inspect::{type_hint_subscript, PyStaticExpr}; @@ -141,7 +142,8 @@ 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] fn test_extract_hashset() { diff --git a/src/conversions/std/slice.rs b/src/conversions/std/slice.rs index 35be5b7850d..7e8bed5bdc4 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::PyStaticExpr; @@ -19,7 +19,7 @@ where #[cfg(feature = "experimental-inspect")] const OUTPUT_TYPE: PyStaticExpr = <&T>::SEQUENCE_OUTPUT_TYPE; - /// Turns [`&[u8]`](std::slice) into [`PyBytes`], all other `T`s will be turned into a [`PyList`] + /// Turns [`&[u8]`](core::slice) into [`PyBytes`], all other `T`s will be turned into a [`PyList`] /// /// [`PyBytes`]: crate::types::PyBytes /// [`PyList`]: crate::types::PyList @@ -84,7 +84,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 a971af4376c..25ea3824e85 100644 --- a/src/conversions/std/string.rs +++ b/src/conversions/std/string.rs @@ -6,7 +6,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; @@ -178,7 +179,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..12a3cb15dfd 100644 --- a/src/conversions/std/time.rs +++ b/src/conversions/std/time.rs @@ -12,7 +12,8 @@ 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; +use std::time::{SystemTime, UNIX_EPOCH}; const SECONDS_PER_DAY: u64 = 24 * 60 * 60; @@ -98,7 +99,7 @@ impl<'py> IntoPyObject<'py> for &Duration { // Conversions between SystemTime and datetime do not rely on the floating point timestamp of the // timestamp/fromtimestamp APIs to avoid possible precision loss but goes through the -// timedelta/std::time::Duration types by taking for reference point the UNIX epoch. +// timedelta/core::time::Duration types by taking for reference point the UNIX epoch. // // TODO: it might be nice to investigate using timestamps anyway, at least when the datetime is a safe range. 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..4b5bc42048d 100644 --- a/src/coroutine.rs +++ b/src/coroutine.rs @@ -1,10 +1,10 @@ //! 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}, }; @@ -90,7 +90,7 @@ impl Coroutine { // poll the Rust future and forward its results if ready // polling is UnwindSafe because the future is dropped in case of panic let poll = || future_rs.as_mut().poll(&mut Context::from_waker(&waker)); - match panic::catch_unwind(panic::AssertUnwindSafe(poll)) { + match std::panic::catch_unwind(panic::AssertUnwindSafe(poll)) { Ok(Poll::Ready(res)) => { self.close(); return Err(PyStopIteration::new_err((res?,))); diff --git a/src/coroutine/cancel.rs b/src/coroutine/cancel.rs index 2368753755e..8607076b9e5 100644 --- a/src/coroutine/cancel.rs +++ b/src/coroutine/cancel.rs @@ -1,7 +1,8 @@ use crate::{Py, PyAny}; -use std::future::poll_fn; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll, Waker}; +use alloc::sync::Arc; +use core::future::poll_fn; +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 6b7ef0df9d4..95a5dc88ac8 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, }; @@ -218,9 +218,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); @@ -347,7 +347,7 @@ impl PyErrStateInner { ptraceback .into_inner() .unwrap() - .map_or(std::ptr::null_mut(), Py::into_ptr), + .map_or(core::ptr::null_mut(), Py::into_ptr), ), }; unsafe { ffi::PyErr_Restore(ptype, pvalue, ptraceback) } @@ -372,9 +372,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); @@ -446,7 +446,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 57aec8f7b21..bdd587eb02a 100644 --- a/src/err/impls.rs +++ b/src/err/impls.rs @@ -91,8 +91,8 @@ impl PyErrArguments for io::IntoInnerError { } } -impl From for PyErr { - fn from(_: std::convert::Infallible) -> PyErr { +impl From for PyErr { + fn from(_: core::convert::Infallible) -> PyErr { unreachable!() } } @@ -110,7 +110,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) } @@ -119,7 +119,7 @@ macro_rules! impl_to_pyerr { } struct Utf8ErrorWithBytes { - err: std::str::Utf8Error, + err: core::str::Utf8Error, bytes: Vec, } @@ -143,7 +143,7 @@ impl PyErrArguments for Utf8ErrorWithBytes { } } -impl PyErrArguments for std::string::FromUtf8Error { +impl PyErrArguments for alloc::string::FromUtf8Error { fn arguments(self, py: Python<'_>) -> Py { Utf8ErrorWithBytes { err: self.utf8_error(), @@ -153,13 +153,13 @@ impl PyErrArguments for std::string::FromUtf8Error { } } -impl std::convert::From for PyErr { - fn from(err: std::string::FromUtf8Error) -> PyErr { +impl core::convert::From for PyErr { + fn from(err: alloc::string::FromUtf8Error) -> PyErr { exceptions::PyUnicodeDecodeError::new_err(err) } } -impl PyErrArguments for std::ffi::IntoStringError { +impl PyErrArguments for alloc::ffi::IntoStringError { fn arguments(self, py: Python<'_>) -> Py { Utf8ErrorWithBytes { err: self.utf8_error(), @@ -169,25 +169,25 @@ impl PyErrArguments for std::ffi::IntoStringError { } } -impl std::convert::From for PyErr { - fn from(err: std::ffi::IntoStringError) -> PyErr { +impl core::convert::From for PyErr { + fn from(err: alloc::ffi::IntoStringError) -> PyErr { exceptions::PyUnicodeDecodeError::new_err(err) } } -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::NulError, exceptions::PyValueError); -impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError); -impl_to_pyerr!(std::time::TryFromFloatSecsError, exceptions::PyValueError); +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::NulError, exceptions::PyValueError); +impl_to_pyerr!(core::net::AddrParseError, exceptions::PyValueError); +impl_to_pyerr!(core::time::TryFromFloatSecsError, exceptions::PyValueError); impl_to_pyerr!(std::time::SystemTimeError, exceptions::PyValueError); impl_to_pyerr!(std::path::StripPrefixError, exceptions::PyValueError); impl_to_pyerr!(std::env::JoinPathsError, exceptions::PyValueError); -impl_to_pyerr!(std::char::ParseCharError, exceptions::PyValueError); -impl_to_pyerr!(std::char::CharTryFromError, exceptions::PyValueError); +impl_to_pyerr!(core::char::ParseCharError, exceptions::PyValueError); +impl_to_pyerr!(core::char::CharTryFromError, exceptions::PyValueError); #[cfg(test)] mod tests { @@ -282,7 +282,7 @@ mod tests { }; let utf8_err_with_bytes = PyUnicodeDecodeError::new_err(Utf8ErrorWithBytes { - err: std::str::from_utf8(&bytes).expect_err("\\xff is invalid utf-8"), + err: core::str::from_utf8(&bytes).expect_err("\\xff is invalid utf-8"), bytes: bytes.clone(), }); check_err(utf8_err_with_bytes); @@ -292,7 +292,7 @@ mod tests { .into(); check_err(from_utf8_err); - let from_utf8_err = std::ffi::CString::new(bytes.clone()) + let from_utf8_err = alloc::ffi::CString::new(bytes.clone()) .unwrap() .into_string() .expect_err("\\xff is invalid utf-8") @@ -311,13 +311,13 @@ mod tests { }; // TryFromFloatSecsError - let float_secs_err = std::time::Duration::try_from_secs_f32(-1.0).unwrap_err(); + let float_secs_err = core::time::Duration::try_from_secs_f32(-1.0).unwrap_err(); let expected = float_secs_err.to_string(); check_err(float_secs_err.into(), &expected); // SystemTimeError let sys_time_err = std::time::SystemTime::now() - .duration_since(std::time::SystemTime::now() + std::time::Duration::from_secs(1)) + .duration_since(std::time::SystemTime::now() + core::time::Duration::from_secs(1)) .unwrap_err(); let expected = sys_time_err.to_string(); check_err(sys_time_err.into(), &expected); diff --git a/src/err/mod.rs b/src/err/mod.rs index 43d006d2332..d3e30a4da09 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; @@ -349,18 +349,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 @@ -393,7 +393,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()), ) } } @@ -477,7 +477,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. @@ -535,11 +535,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 { @@ -599,7 +599,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), ); } } @@ -622,7 +622,7 @@ impl PyErr { unsafe { ffi::PyException_SetContext( value.as_ptr(), - context.map_or(std::ptr::null_mut(), Py::into_ptr), + context.map_or(core::ptr::null_mut(), Py::into_ptr), ); } } @@ -663,8 +663,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)) @@ -688,11 +688,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()) @@ -703,7 +703,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; @@ -741,7 +741,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 f47d6f1ab50..b45274a4509 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 start = err.valid_up_to(); let end = err.error_len().map_or(input.len(), |l| start + l); @@ -795,14 +795,14 @@ 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 py_err = PyUnicodeDecodeError::new_err_from_utf8(py, invalid_utf8, err); /// }) /// ``` pub fn new_err_from_utf8( py: Python<'_>, bytes: &[u8], - err: std::str::Utf8Error, + err: core::str::Utf8Error, ) -> crate::PyErr { match Self::new_utf8(py, bytes, err) { Ok(e) => crate::PyErr::from_value(e.into_any()), @@ -1148,7 +1148,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!( @@ -1205,7 +1205,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() @@ -1300,7 +1300,7 @@ mod tests { let utf8_err_with_bytes = PyUnicodeDecodeError::new_err_from_utf8( py, &bytes, - std::str::from_utf8(&bytes).expect_err("\\xff is invalid utf-8"), + core::str::from_utf8(&bytes).expect_err("\\xff is invalid utf-8"), ); check_err(utf8_err_with_bytes); }) diff --git a/src/ffi/tests.rs b/src/ffi/tests.rs index 203669083c0..25e4358a5c3 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 f21f8e2f3d7..b0e897524a9 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::ffi::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 6fb9c84057d..f6eaeeb8f6a 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")] @@ -301,7 +301,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() }, } } @@ -316,7 +316,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() }, } } @@ -436,7 +436,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); @@ -454,7 +454,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(), @@ -619,7 +619,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)); } @@ -1031,7 +1031,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 b20e65945c0..253064f27d9 100644 --- a/src/impl_/pyclass.rs +++ b/src/impl_/pyclass.rs @@ -13,14 +13,13 @@ use crate::{ Borrowed, IntoPyObject, IntoPyObjectExt, Py, PyAny, PyClass, PyClassGuard, PyErr, PyResult, PyTypeCheck, PyTypeInfo, Python, }; -use std::{ +use core::{ ffi::CStr, ffi::{c_int, c_void}, marker::PhantomData, ptr::{self, NonNull}, - sync::Mutex, - thread, }; +use std::{sync::Mutex, thread}; mod assertions; pub mod doc; @@ -94,7 +93,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 +109,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() { @@ -368,7 +367,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(); @@ -452,12 +451,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) } @@ -572,7 +571,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) } } @@ -754,7 +753,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) } } @@ -871,7 +870,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::*; @@ -1063,13 +1062,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()) @@ -1117,7 +1116,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) }; @@ -1156,7 +1155,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 { @@ -1446,7 +1445,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() { @@ -1542,7 +1541,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 )); @@ -1564,7 +1563,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 )); @@ -1629,7 +1628,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 a5acb7cd72d..ce2845f9013 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 03db5b90b6d..9bbb6fde063 100644 --- a/src/impl_/pymethods.rs +++ b/src/impl_/pymethods.rs @@ -7,12 +7,13 @@ use crate::internal::state::ForbidAttaching; use crate::pycell::impl_::{PyClassBorrowChecker as _, PyClassObjectLayout}; use crate::types::PyType; use crate::{ffi, Bound, Py, PyAny, PyClass, PyErr, PyResult, PyTraverseError, 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; diff --git a/src/impl_/pymodule.rs b/src/impl_/pymodule.rs index d0a32881b6c..7674573f774 100644 --- a/src/impl_/pymodule.rs +++ b/src/impl_/pymodule.rs @@ -1,6 +1,6 @@ //! 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}, @@ -12,22 +12,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; @@ -76,11 +76,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, @@ -264,7 +264,7 @@ impl PyModuleSlotsBuilder { #[allow(clippy::new_without_default)] pub const fn new() -> Self { Self { - values: [unsafe { std::mem::zeroed() }; MAX_SLOTS_WITH_TRAILING_NULL], + values: [unsafe { core::mem::zeroed() }; MAX_SLOTS_WITH_TRAILING_NULL], len: 0, } } @@ -312,7 +312,7 @@ impl PyModuleSlotsBuilder { #[cfg(Py_3_15)] { ffi::PyABIInfo_VAR!(ABI_INFO); - self.push(ffi::Py_mod_abi, std::ptr::addr_of_mut!(ABI_INFO).cast()) + self.push(ffi::Py_mod_abi, core::ptr::addr_of_mut!(ABI_INFO).cast()) } #[cfg(not(Py_3_15))] @@ -418,7 +418,8 @@ impl PyAddToModule for ModuleDef { #[cfg(test)] mod tests { - use std::{borrow::Cow, ffi::c_int, ffi::CStr}; + use alloc::borrow::Cow; + use core::{ffi::c_int, ffi::CStr}; use crate::{ ffi, @@ -521,8 +522,8 @@ mod tests { .with_gil_used(false) .with_abi_info(); - assert!(builder.values[builder.len] == unsafe { std::mem::zeroed() }); - assert!(builder.values[builder.len - 1] != unsafe { std::mem::zeroed() }); + assert!(builder.values[builder.len] == unsafe { core::mem::zeroed() }); + assert!(builder.values[builder.len - 1] != unsafe { core::mem::zeroed() }); assert!(builder.len == MAX_SLOTS); let result = std::panic::catch_unwind(|| builder.with_mod_exec(module_exec).build()); diff --git a/src/impl_/trampoline.rs b/src/impl_/trampoline.rs index c184335d302..f1d9e040687 100644 --- a/src/impl_/trampoline.rs +++ b/src/impl_/trampoline.rs @@ -5,11 +5,7 @@ //! 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, - ffi::c_int, - panic::{self, UnwindSafe}, -}; +use core::{any::Any, ffi::c_int, panic::UnwindSafe}; use crate::internal::state::AttachGuard; use crate::{ @@ -277,7 +273,7 @@ pub(crate) unsafe fn dealloc( f(py, slf); Ok(()) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) } } @@ -302,7 +298,7 @@ where let py = guard.python(); let out = panic_result_into_callback_output( py, - panic::catch_unwind(move || -> PyResult<_> { body(py) }), + std::panic::catch_unwind(move || -> PyResult<_> { body(py) }), ); trap.disarm(); out @@ -349,7 +345,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) = std::panic::catch_unwind(move || body(py)) .unwrap_or_else(|payload| Err(PanicException::from_panic_payload(payload))) { // SAFETY: caller upholds requirements diff --git a/src/impl_/unindent.rs b/src/impl_/unindent.rs index 8b12fe6b001..d04bbf3071c 100644 --- a/src/impl_/unindent.rs +++ b/src/impl_/unindent.rs @@ -238,7 +238,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 b9a8082c6b3..49ae60b3d8d 100644 --- a/src/impl_/wrap.rs +++ b/src/impl_/wrap.rs @@ -1,6 +1,6 @@ #![warn(clippy::undocumented_unsafe_blocks)] -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.rs b/src/inspect.rs index ba2e6d92948..33f27e4e018 100644 --- a/src/inspect.rs +++ b/src/inspect.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}; /// Builds a type hint from a module name and a member name in the module /// @@ -476,7 +476,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/instance.rs b/src/instance.rs index 95108897b08..40ac4db5016 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) } } } @@ -624,7 +624,7 @@ where /// # Examples /// /// ``` - /// use std::sync::atomic::{AtomicUsize, Ordering}; + /// use core::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] @@ -758,15 +758,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) } @@ -775,15 +775,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(""), } } @@ -1082,7 +1082,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)] @@ -1130,7 +1130,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`. /// @@ -1153,7 +1153,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] @@ -1172,7 +1172,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] @@ -1191,7 +1191,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] @@ -1203,7 +1203,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] @@ -1227,8 +1227,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) } } @@ -1485,9 +1485,9 @@ impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T> { /// value when there is ownership transfer. Without ownership transfer, `*mut ffi::PyObject` or `NonNull` /// are more appropriate. /// -/// [`Rc`]: std::rc::Rc -/// [`Arc`]: std::sync::Arc -/// [`RefCell`]: std::cell::RefCell +/// [`Rc`]: alloc::rc::Rc +/// [`Arc`]: alloc::sync::Arc +/// [`RefCell`]: core::cell::RefCell #[doc = concat!("[gc]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class/protocols.html#garbage-collector-integration")] #[repr(transparent)] pub struct Py(NonNull, PhantomData); @@ -1699,7 +1699,7 @@ where /// # Examples /// /// ``` - /// use std::sync::atomic::{AtomicUsize, Ordering}; + /// use core::sync::atomic::{AtomicUsize, Ordering}; /// # use pyo3::prelude::*; /// /// #[pyclass(frozen)] @@ -2170,7 +2170,7 @@ impl AsRef> for Py { } } -impl std::convert::From> for Py +impl core::convert::From> for Py where T: DerefToPyAny, { @@ -2180,7 +2180,7 @@ where } } -impl std::convert::From> for Py +impl core::convert::From> for Py where T: DerefToPyAny, { @@ -2190,7 +2190,7 @@ where } } -impl std::convert::From> for Py { +impl core::convert::From> for Py { #[inline] fn from(other: Bound<'_, T>) -> Self { other.unbind() @@ -2209,13 +2209,13 @@ impl From<&Bound<'_, T>> for Py { } } -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, { @@ -2226,7 +2226,7 @@ where } } -impl<'py, T> std::convert::From> for Py +impl<'py, T> core::convert::From> for Py where T: PyClass, { @@ -2337,17 +2337,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() } } @@ -2517,7 +2517,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() { @@ -2778,7 +2778,7 @@ a = A() py, (&mut dropped) as *mut _ as usize, c"bound_from_borrowed_ptr_constructors", - |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, + |ptr, _| unsafe { core::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); @@ -2820,7 +2820,7 @@ a = A() py, (&mut dropped) as *mut _ as usize, c"borrowed_ptr_constructors", - |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) }, + |ptr, _| unsafe { core::ptr::write(ptr as *mut bool, true) }, ) .unwrap(); @@ -2875,7 +2875,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 763333719ab..c9a6705fb50 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.8 through 3.9. @@ -230,7 +230,7 @@ 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, @@ -248,8 +248,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, @@ -275,7 +275,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, pub tp_vectorcall: Option, } diff --git a/src/internal/state.rs b/src/internal/state.rs index 606f1638893..f94688c2eef 100644 --- a/src/internal/state.rs +++ b/src/internal/state.rs @@ -4,11 +4,11 @@ use crate::impl_::panic::PanicTrap; use crate::{ffi, Python}; -use std::cell::Cell; -#[cfg(not(pyo3_disable_reference_pool))] -use std::sync::OnceLock; +use core::cell::Cell; #[cfg_attr(pyo3_disable_reference_pool, allow(unused_imports))] -use std::{mem, ptr::NonNull, sync}; +use core::{mem, ptr::NonNull}; +#[cfg(not(pyo3_disable_reference_pool))] +use std::sync::{Mutex, OnceLock}; std::thread_local! { /// This is an internal counter in pyo3 monitoring whether this thread is attached to the interpreter. @@ -186,14 +186,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()), } } @@ -556,7 +556,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 _, ) }; } @@ -564,7 +564,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 cdeae3f19cd..0d21c69dcc7 100644 --- a/src/internal_tricks.rs +++ b/src/internal_tricks.rs @@ -1,4 +1,4 @@ -use std::ptr::NonNull; +use core::ptr::NonNull; use crate::ffi::{self, Py_ssize_t, PY_SSIZE_T_MAX}; @@ -26,7 +26,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))] @@ -41,7 +41,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/macros.rs b/src/macros.rs index 56ba7e6870e..a246288f46c 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -117,15 +117,15 @@ 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)) { + use ::core::option::Option::*; + if let ::core::result::Result::Err(e) = $py.run(&::std::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) } }}; } @@ -217,13 +217,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 39154c66391..83c3f7a7078 100644 --- a/src/marker.rs +++ b/src/marker.rs @@ -41,7 +41,7 @@ //! # #[cfg(feature = "nightly")] //! # compile_error!("this actually works on nightly") //! use pyo3::prelude::*; -//! use std::rc::Rc; +//! use alloc::rc::Rc; //! //! fn main() { //! Python::attach(|py| { @@ -114,7 +114,7 @@ //! With this feature enabled, the above two examples will start working and not working, respectively. //! //! [`SendWrapper`]: https://docs.rs/send_wrapper/latest/send_wrapper/struct.SendWrapper.html -//! [`Rc`]: std::rc::Rc +//! [`Rc`]: alloc::rc::Rc //! [`Py`]: crate::Py use crate::conversion::IntoPyObject; use crate::err::{self, PyResult}; @@ -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; use std::sync::LazyLock; /// Types that are safe to access while the GIL is not held. @@ -146,7 +146,7 @@ use std::sync::LazyLock; /// /// ```compile_fail /// # use pyo3::prelude::*; -/// use std::rc::Rc; +/// use alloc::rc::Rc; /// /// Python::attach(|py| { /// let rc = Rc::new(42); @@ -257,7 +257,7 @@ mod nightly { /// /// ```rust /// # use pyo3::prelude::*; - /// use std::rc::Rc; + /// use alloc::rc::Rc; /// /// Python::attach(|py| { /// let rc = Rc::new(42); @@ -846,7 +846,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())); @@ -892,7 +892,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(|| { @@ -904,7 +904,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; @@ -963,7 +963,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)] @@ -1006,7 +1006,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..85d36b479e0 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::sync::Arc; +use core::{borrow::Borrow, 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 257bd09511d..0b2f53b68e5 100644 --- a/src/pycell.rs +++ b/src/pycell.rs @@ -15,7 +15,7 @@ //! use the [`Python<'py>`](crate::Python) token to guarantee thread-safe access to them, it cannot //! statically guarantee uniqueness of `&mut` references. As such those references have to be tracked //! dynamically at runtime, using `PyCell` and the other types defined in this module. This works -//! similar to std's [`RefCell`](std::cell::RefCell) type. +//! similar to std's [`RefCell`](core::cell::RefCell) type. //! //! # When *not* to use PyCell //! @@ -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 8eb4a9e0f97..fa538734648 100644 --- a/src/pycell/impl_.rs +++ b/src/pycell/impl_.rs @@ -1,10 +1,10 @@ #![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::sync::atomic::{AtomicUsize, Ordering}; +use core::cell::UnsafeCell; +use core::marker::PhantomData; +use core::mem::{offset_of, ManuallyDrop, MaybeUninit}; +use core::sync::atomic::{AtomicUsize, Ordering}; use crate::impl_::pyclass::{ PyClassBaseType, PyClassDict, PyClassImpl, PyClassThreadChecker, PyClassWeakRef, PyObjectOffset, @@ -267,14 +267,14 @@ unsafe fn tp_dealloc(slf: *mut ffi::PyObject, type_obj: &crate::Bound<'_, PyType // For `#[pyclass]` types which inherit from PyAny, we can just call tp_free #[cfg(not(RustPython))] - if std::ptr::eq(type_ptr, &raw const ffi::PyBaseObject_Type) { + if core::ptr::eq(type_ptr, &raw const ffi::PyBaseObject_Type) { let tp_free = actual_type .get_slot(TP_FREE) .expect("PyBaseObject_Type should have tp_free"); return tp_free(slf.cast()); } #[cfg(RustPython)] - if std::ptr::eq(type_ptr, { + if core::ptr::eq(type_ptr, { static TYPE: PyOnceLock> = PyOnceLock::new(); TYPE.import(py, "builtins", "object").unwrap().as_type_ptr() }) { @@ -402,7 +402,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 _ }; @@ -517,7 +517,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 cd2fb1e4b83..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, ffi::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 f417df75f42..dde4cb50a62 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, +use core::{ + ffi::CStr, ffi::{c_char, c_int, c_ulong, c_void}, - ffi::{CStr, CString}, ptr::{self, NonNull}, }; +use std::{collections::HashMap, ffi::CString}; 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 @@ -689,7 +689,7 @@ impl GetSetDefType { ) -> *mut ffi::PyObject { let slf = unsafe { NonNull::new_unchecked(slf) }; // 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 _) @@ -702,7 +702,7 @@ impl GetSetDefType { ) -> c_int { let slf = unsafe { NonNull::new_unchecked(slf) }; // 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 let Some(value) = NonNull::new(value) { diff --git a/src/pyclass/gc.rs b/src/pyclass/gc.rs index 0b404a0f034..0460c92b6d8 100644 --- a/src/pyclass/gc.rs +++ b/src/pyclass/gc.rs @@ -1,4 +1,4 @@ -use std::{ +use core::{ ffi::{c_int, c_void}, marker::PhantomData, num::NonZero, @@ -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 3749ae0cb94..655aff4c0c3 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, Bound, 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`. /// @@ -34,7 +34,7 @@ use std::ptr::NonNull; /// uniqueness of `&mut` references. As such those references have to be /// tracked dynamically at runtime, using [`PyClassGuard`] and /// [`PyClassGuardMut`] defined in this module. This works similar to std's -/// [`RefCell`](std::cell::RefCell) type. Especially when building for +/// [`RefCell`](core::cell::RefCell) type. Especially when building for /// free-threaded Python it gets harder to track which thread borrows which /// object at any time. This can lead to method calls failing with /// [`PyBorrowError`]. In these cases consider using `frozen` classes together @@ -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, } } @@ -526,7 +526,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| { @@ -562,7 +562,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. /// } @@ -654,7 +654,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(), @@ -687,7 +687,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 3155ce9d2fa..0155aa93349 100644 --- a/src/sealed.rs +++ b/src/sealed.rs @@ -68,8 +68,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..1c91668b437 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,7 +715,7 @@ 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)] @@ -729,7 +725,7 @@ mod tests { 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; @@ -882,7 +878,7 @@ mod tests { let b = mutex.lock_py_attached(py).unwrap(); barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); (*b).bind(py).borrow().0.store(true, Ordering::Release); drop(b); }); @@ -917,7 +913,7 @@ mod tests { let b: $guard = mutex.lock_py_attached(py); barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); (*b).bind(py).borrow().0.store(true, Ordering::Release); drop(b); }); @@ -948,14 +944,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) }); } @@ -1002,7 +998,7 @@ mod tests { let b = rwlock.write_py_attached(py).unwrap(); barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); (*b).bind(py).borrow().0.store(true, Ordering::Release); drop(b); }); @@ -1037,7 +1033,7 @@ mod tests { barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // The bool must still be false (i.e., the writer did not actually write the // value yet). @@ -1082,7 +1078,7 @@ mod tests { let b: $write_guard = rwlock.write_py_attached(py); barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); (*b).bind(py).borrow().0.store(true, Ordering::Release); drop(b); }); @@ -1115,7 +1111,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) } ); } @@ -1140,7 +1136,7 @@ mod tests { barrier.wait(); // sleep to ensure the other thread actually blocks - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(core::time::Duration::from_millis(10)); // The bool must still be false (i.e., the writer did not actually write the // value yet). @@ -1184,7 +1180,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 002af4b26cd..ded2123d939 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 d6ad902166e..fc3a3332b1f 100644 --- a/src/types/any.rs +++ b/src/types/any.rs @@ -16,10 +16,10 @@ use crate::{err, ffi, Borrowed, BoundObject, IntoPyObjectExt, Py}; use crate::{sync::PyOnceLock, types::typeobject::PyTypeMethods}; #[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. /// @@ -228,7 +228,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<()> { @@ -467,7 +467,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): @@ -524,7 +524,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): @@ -561,7 +561,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: @@ -607,7 +607,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: @@ -644,7 +644,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: @@ -1046,7 +1046,7 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> { any: &Bound<'py, PyAny>, attr_name: Borrowed<'_, 'py, PyString>, ) -> PyResult>> { - 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::compat::PyObject_GetOptionalAttr( any.as_ptr(), @@ -1674,8 +1674,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() { @@ -2093,7 +2093,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 61845007748..81ea29ac071 100644 --- a/src/types/boolobject.rs +++ b/src/types/boolobject.rs @@ -11,8 +11,8 @@ use crate::{ }; #[cfg(RustPython)] use crate::{sync::PyOnceLock, types::PyType, Py}; -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 f8e08388163..8755e380d1e 100644 --- a/src/types/bytearray.rs +++ b/src/types/bytearray.rs @@ -10,7 +10,7 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -use std::slice; +use core::slice; /// Represents a Python `bytearray`. /// @@ -82,17 +82,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) } } @@ -482,11 +482,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 07e1469a65a..2e01ddad3ce 100644 --- a/src/types/bytes.rs +++ b/src/types/bytes.rs @@ -7,10 +7,10 @@ use crate::{ sync::PyOnceLock, types::{PyType, PyTypeMethods}, }; +use core::ops::Index; +use core::slice::SliceIndex; +use core::str; use std::io::Write; -use std::ops::Index; -use std::slice::SliceIndex; -use std::str; /// Represents a Python `bytes` object. /// @@ -114,16 +114,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) } } @@ -176,7 +176,7 @@ impl PyBytes { /// /// This function dereferences the raw pointer `ptr` as the /// leading pointer of a slice of length `len`. [As with - /// `std::slice::from_raw_parts`, this is + /// `core::slice::from_raw_parts`, this is /// unsafe](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety). pub unsafe fn from_ptr(py: Python<'_>, ptr: *const u8, len: usize) -> Bound<'_, PyBytes> { unsafe { @@ -213,7 +213,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) } } } @@ -450,8 +450,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 ); } }) diff --git a/src/types/capsule.rs b/src/types/capsule.rs index ef5bedbd63c..798eb29f0be 100644 --- a/src/types/capsule.rs +++ b/src/types/capsule.rs @@ -12,10 +12,11 @@ use crate::{ }; 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 core::ffi::CStr; +use core::ffi::{c_char, c_int, c_void}; +use core::mem::offset_of; +use core::ptr::{self, NonNull}; +use std::ffi::CString; /// Represents a Python Capsule /// as described in [Capsules](https://docs.python.org/3/c-api/capsule.html#capsules): @@ -108,8 +109,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"; @@ -237,7 +238,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, @@ -278,11 +281,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| { @@ -330,8 +333,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()); @@ -427,7 +430,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}; /// @@ -729,8 +732,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"; @@ -908,14 +911,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 = @@ -1052,7 +1055,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/code.rs b/src/types/code.rs index d35ca6c545e..0416fb3cd20 100644 --- a/src/types/code.rs +++ b/src/types/code.rs @@ -9,7 +9,7 @@ use crate::types::{PyType, PyTypeMethods}; #[cfg(any(Py_LIMITED_API, PyPy))] use crate::Py; use crate::{ffi, Bound, PyAny, PyResult, Python}; -use std::ffi::CStr; +use core::ffi::CStr; /// Represents a Python code object. /// diff --git a/src/types/complex.rs b/src/types/complex.rs index 3efe82df1ac..d0e9015f59c 100644 --- a/src/types/complex.rs +++ b/src/types/complex.rs @@ -9,7 +9,7 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -use std::ffi::c_double; +use core::ffi::c_double; /// Represents a Python [`complex`](https://docs.python.org/3/library/functions.html#complex) object. /// @@ -69,7 +69,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 225885d425c..25234e1ec07 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 f3eabcddbd8..a65d5c557f1 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -301,13 +301,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) })) @@ -446,7 +446,7 @@ impl<'py> PyDictMethods<'py> for Bound<'py, PyDict> { dict.as_ptr(), key.as_ptr(), value.as_ptr(), - std::ptr::null_mut(), + core::ptr::null_mut(), ) }, )) @@ -478,7 +478,7 @@ impl<'py> PyDictMethods<'py> for Bound<'py, PyDict> { value: Borrowed<'_, '_, PyAny>, py: Python<'py>, ) -> PyResult<(bool, Bound<'py, PyAny>)> { - let mut result = std::ptr::NonNull::dangling().as_ptr(); + let mut result = core::ptr::NonNull::dangling().as_ptr(); let code = setdefault_result_from_nonerror_return_code( err::error_on_minusone_with_result(dict.py(), unsafe { ffi::compat::PyDict_SetDefaultRef( @@ -506,7 +506,7 @@ impl<'py> PyDictMethods<'py> for Bound<'py, PyDict> { } } -fn setdefault_result_from_nonerror_return_code(code: PyResult) -> PyResult { +fn setdefault_result_from_nonerror_return_code(code: PyResult) -> PyResult { match code? { // inserted 0 => Ok(true), @@ -595,8 +595,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; @@ -683,7 +683,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; @@ -840,8 +840,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) } @@ -954,7 +954,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() { diff --git a/src/types/float.rs b/src/types/float.rs index e27ffb09e35..107ec7bd2b9 100644 --- a/src/types/float.rs +++ b/src/types/float.rs @@ -12,8 +12,8 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -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/frame.rs b/src/types/frame.rs index a5f2a6a3325..c3002397333 100644 --- a/src/types/frame.rs +++ b/src/types/frame.rs @@ -4,8 +4,8 @@ use crate::sealed::Sealed; use crate::types::{PyCode, PyDict}; use crate::PyAny; use crate::{ffi, Bound, PyResult, Python}; +use core::ffi::CStr; use pyo3_ffi::PyObject; -use std::ffi::CStr; /// Represents a Python frame. /// diff --git a/src/types/frozenset.rs b/src/types/frozenset.rs index bd4340d3fc3..6fa9a838f6e 100644 --- a/src/types/frozenset.rs +++ b/src/types/frozenset.rs @@ -13,7 +13,7 @@ use crate::{ Py, }; 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 542fcf94a19..ec17e9c2e62 100644 --- a/src/types/function.rs +++ b/src/types/function.rs @@ -14,9 +14,9 @@ use crate::{ Py, }; 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. /// @@ -131,7 +131,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 f366d7b5c63..7408c43568a 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -81,7 +81,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 { @@ -105,14 +105,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 13fb8260015..6d02039da93 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -11,9 +11,9 @@ use crate::{ Py, }; 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`. /// @@ -720,7 +720,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; @@ -893,7 +893,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; @@ -965,7 +965,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() { @@ -1505,7 +1505,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 @@ -1550,8 +1550,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/mappingproxy.rs b/src/types/mappingproxy.rs index f664b688e74..33ae6de7ca8 100644 --- a/src/types/mappingproxy.rs +++ b/src/types/mappingproxy.rs @@ -154,7 +154,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 c5e611f5cea..a9ad7ebb3ae 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -92,7 +92,7 @@ pub mod iter { /// This marks types that can be upcast into a [`PyAny`] and used in its place. /// This essentially includes every Python object except [`PyAny`] itself. /// -/// This is used to provide the [`Deref>`](std::ops::Deref) +/// This is used to provide the [`Deref>`](core::ops::Deref) /// implementations for [`Bound<'_, T>`](crate::Bound). /// /// Users should not need to implement this trait directly. It's implementation @@ -166,7 +166,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] @@ -208,7 +208,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 936c576b99c..bea42e5d78e 100644 --- a/src/types/module.rs +++ b/src/types/module.rs @@ -15,11 +15,11 @@ use crate::{ sync::PyOnceLock, types::{PyType, PyTypeMethods}, }; -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. /// @@ -136,9 +136,9 @@ impl PyModule { /// Returns `PyErr` if: /// - `code` is not syntactically correct Python. /// - Any Python exceptions are raised while initializing the module. - /// - Any of the arguments cannot be converted to [`CString`][std::ffi::CString]s. + /// - Any of the arguments cannot be converted to [`CString`][alloc::ffi::CString]s. /// - /// # Example: bundle in a file at compile time with [`include_str!`][std::include_str]: + /// # Example: bundle in a file at compile time with [`include_str!`][core::include_str]: /// /// ```rust /// use pyo3::prelude::*; diff --git a/src/types/mutex.rs b/src/types/mutex.rs index f72115431d8..0b3c6ce9c9b 100644 --- a/src/types/mutex.rs +++ b/src/types/mutex.rs @@ -1,13 +1,13 @@ -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; -// See std::sync::poison in the rust standard library. +// See core::sync::poison in the rust standard library. // This is more-or-less copied from there since it is not public. // this type detects a panic and poisons the wrapping mutex struct Flag { @@ -158,7 +158,7 @@ unsafe impl Send for PyMutex {} /// Also note that it is not necessary for `T` to be `Sync` as `&T` is only made available /// to one thread at a time if `T` is not `Sync`. /// -/// [`Rc`]: std::rc::Rc +/// [`Rc`]: alloc::rc::Rc unsafe impl Sync for PyMutex {} impl PyMutex { @@ -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 9f29c36ddb5..b5f73e420e2 100644 --- a/src/types/num.rs +++ b/src/types/num.rs @@ -6,7 +6,7 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -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 b14721e0ab2..279d96a2baa 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -12,7 +12,7 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -use std::ptr; +use core::ptr; /// Represents a Python `set`. /// diff --git a/src/types/slice.rs b/src/types/slice.rs index 574a735e217..17a9acbfcf4 100644 --- a/src/types/slice.rs +++ b/src/types/slice.rs @@ -13,7 +13,7 @@ use crate::{ Py, }; 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 44212bb9117..bb577a245fc 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -11,9 +11,9 @@ use crate::{ sync::PyOnceLock, types::{PyType, PyTypeMethods}, }; -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`. /// @@ -39,10 +39,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()) }, } } @@ -88,7 +88,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, @@ -116,7 +116,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| char::from_u32(c).unwrap_or('\u{FFFD}')) .collect(), ), } @@ -235,8 +235,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 @@ -264,7 +264,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 @@ -366,7 +366,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)) }) } } @@ -428,15 +428,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 9df68a7f9df..bfbbe9a048f 100644 --- a/src/types/tuple.rs +++ b/src/types/tuple.rs @@ -22,9 +22,9 @@ use crate::{ types::{PyType, PyTypeMethods}, Py, }; -use std::iter::FusedIterator; +use core::iter::FusedIterator; #[cfg(feature = "nightly")] -use std::num::NonZero; +use core::num::NonZero; #[cfg(all( not(any(PyPy, GraalPy)), @@ -311,7 +311,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] @@ -701,7 +701,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ // We need this to drop the arguments correctly. let args_objects = ($(self.$n.into_pyobject_or_pyerr(py)?),*,); // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; unsafe { ffi::PyObject_VectorcallDict( function.as_ptr(), @@ -734,13 +734,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_objects.$n.as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; unsafe { ffi::PyObject_Vectorcall( function.as_ptr(), args.as_mut_ptr().add(1), const { with_vectorcall_arguments_offset($length) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -775,7 +775,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ args.as_mut_ptr(), // +1 for the receiver. const { with_vectorcall_arguments_offset(1 + $length) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -827,7 +827,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ let py = function.py(); let args_objects = ($(self.$n.into_pyobject_or_pyerr(py)?),*,); // Prepend one null argument for `PY_VECTORCALL_ARGUMENTS_OFFSET`. - let mut args = [std::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; unsafe { ffi::PyObject_VectorcallDict( function.as_ptr(), @@ -860,13 +860,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_objects.$n.as_ptr()),*]; + let mut args = [core::ptr::null_mut(), $(args_objects.$n.as_ptr()),*]; unsafe { ffi::PyObject_Vectorcall( function.as_ptr(), args.as_mut_ptr().add(1), const { with_vectorcall_arguments_offset($length) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -901,7 +901,7 @@ macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+ args.as_mut_ptr(), // +1 for the receiver. const { with_vectorcall_arguments_offset(1 + $length) }, - std::ptr::null_mut(), + core::ptr::null_mut(), ) .assume_owned_or_err(py) } @@ -1109,10 +1109,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| { @@ -1487,8 +1487,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); @@ -1550,8 +1550,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 e89d4e21ef3..0f9af47df6b 100644 --- a/src/types/weakref/anyref.rs +++ b/src/types/weakref/anyref.rs @@ -64,7 +64,7 @@ unsafe impl PyTypeCheck for PyWeakref { pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { /// Upgrade the weakref to a direct Bound object reference. /// - /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). + /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](alloc::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Example @@ -140,7 +140,7 @@ pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { /// Upgrade the weakref to a direct Bound object reference unchecked. The type of the recovered object is not checked before casting, this could lead to unexpected behavior. Use only when absolutely certain the type can be guaranteed. The `weakref` may still return `None`. /// - /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). + /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](alloc::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Safety @@ -214,7 +214,7 @@ pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { /// Upgrade the weakref to a exact direct Bound object reference. /// - /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). + /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](alloc::rc::Weak::upgrade). /// In Python it would be equivalent to [`PyWeakref_GetRef`]. /// /// # Example @@ -290,7 +290,7 @@ pub trait PyWeakrefMethods<'py>: crate::sealed::Sealed { /// Upgrade the weakref to a Bound [`PyAny`] reference to the target object if possible. /// - /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](std::rc::Weak::upgrade). + /// It is named `upgrade` to be inline with [rust's `Weak::upgrade`](alloc::rc::Weak::upgrade). /// This function returns `Some(Bound<'py, PyAny>)` if the reference still exists, otherwise `None` will be returned. /// /// This function gets the optional target of this [`weakref.ReferenceType`] (result of calling [`weakref.ref`]). @@ -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 b5f99e4a045..18d9c00e4a8 100644 --- a/src/types/weakref/proxy.rs +++ b/src/types/weakref/proxy.rs @@ -180,11 +180,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()) }), } } } @@ -256,7 +256,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); @@ -458,7 +458,7 @@ mod tests { mod pyo3_pyclass { use super::*; use crate::{pyclass, Py}; - use std::ptr; + use core::ptr; #[pyclass(weakref, crate = "crate")] struct WeakrefablePyClass {} @@ -614,7 +614,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); @@ -775,7 +775,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 793c9378023..13f1f6ecd0b 100644 --- a/src/types/weakref/reference.rs +++ b/src/types/weakref/reference.rs @@ -186,11 +186,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()) }), } } } @@ -247,7 +247,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)?; @@ -398,7 +398,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 ac674c5b96f..82fb2aaf7b1 100644 --- a/src/version.rs +++ b/src/version.rs @@ -84,13 +84,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) } } From 7414afe587748af4a3e3ca0dab3200c86117a5a9 Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Tue, 12 May 2026 22:05:28 +0100 Subject: [PATCH 3/3] fixup nightly doctest --- src/marker.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/marker.rs b/src/marker.rs index 83c3f7a7078..817d945649e 100644 --- a/src/marker.rs +++ b/src/marker.rs @@ -257,7 +257,7 @@ mod nightly { /// /// ```rust /// # use pyo3::prelude::*; - /// use alloc::rc::Rc; + /// use std::rc::Rc; /// /// Python::attach(|py| { /// let rc = Rc::new(42);