pyo3/
internal_tricks.rs

1use crate::ffi::{self, Py_ssize_t, PY_SSIZE_T_MAX};
2
3macro_rules! pyo3_exception {
4    ($doc: expr, $name: ident, $base: ty) => {
5        #[doc = $doc]
6        #[repr(transparent)]
7        #[allow(non_camel_case_types)]
8        pub struct $name($crate::PyAny);
9
10        $crate::impl_exception_boilerplate!($name);
11
12        $crate::create_exception_type_object!(pyo3_runtime, $name, $base, Some($doc));
13    };
14}
15
16/// Convert an usize index into a Py_ssize_t index, clamping overflow to
17/// PY_SSIZE_T_MAX.
18pub(crate) fn get_ssize_index(index: usize) -> Py_ssize_t {
19    index.min(PY_SSIZE_T_MAX as usize) as Py_ssize_t
20}
21
22// TODO: use ptr::from_ref on MSRV 1.76
23#[inline]
24pub(crate) const fn ptr_from_ref<T>(t: &T) -> *const T {
25    t as *const T
26}
27
28// TODO: use ptr::from_mut on MSRV 1.76
29#[inline]
30pub(crate) fn ptr_from_mut<T>(t: &mut T) -> *mut T {
31    t as *mut T
32}
33
34// TODO: use ptr::fn_addr_eq on MSRV 1.85
35pub(crate) fn clear_eq(f: Option<ffi::inquiry>, g: ffi::inquiry) -> bool {
36    #[cfg(fn_ptr_eq)]
37    {
38        let Some(f) = f else { return false };
39        std::ptr::fn_addr_eq(f, g)
40    }
41
42    #[cfg(not(fn_ptr_eq))]
43    {
44        f == Some(g)
45    }
46}
47
48// TODO: use ptr::fn_addr_eq on MSRV 1.85
49pub(crate) fn traverse_eq(f: Option<ffi::traverseproc>, g: ffi::traverseproc) -> bool {
50    #[cfg(fn_ptr_eq)]
51    {
52        let Some(f) = f else { return false };
53        std::ptr::fn_addr_eq(f, g)
54    }
55
56    #[cfg(not(fn_ptr_eq))]
57    {
58        f == Some(g)
59    }
60}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here