Skip to main content

PyStackRef

Struct PyStackRef 

Source
pub struct PyStackRef { /* private fields */ }
Expand description

A tagged stack reference to a Python object.

Uses the lowest bit of the pointer to distinguish owned vs borrowed:

  • bit 0 = 0 → owned: refcount was incremented; Drop will decrement.
  • bit 0 = 1 → borrowed: no refcount change; Drop is a no-op.

Same size as PyObjectRef (one pointer-width). PyObject is at least 8-byte aligned, so the low bit is always available for tagging.

Uses NonZeroUsize so that Option<PyStackRef> has the same size as PyStackRef via niche optimization (matching Option<PyObjectRef>).

Implementations§

Source§

impl PyStackRef

Source

pub fn new_owned(obj: PyObjectRef) -> Self

Create an owned stack reference, consuming the PyObjectRef. Refcount is NOT incremented — ownership is transferred.

Source

pub unsafe fn new_borrowed(obj: &PyObject) -> Self

Create a borrowed stack reference from a &PyObject.

§Safety

The caller must guarantee that the pointed-to object lives at least as long as this PyStackRef. In practice the compiler guarantees that borrowed refs are consumed within the same basic block, before any STORE_FAST/DELETE_FAST could overwrite the source slot.

Source

pub fn is_borrowed(&self) -> bool

Whether this is a borrowed (non-owning) reference.

Source

pub fn as_object(&self) -> &PyObject

Get a &PyObject reference. Works for both owned and borrowed.

Source

pub fn to_pyobj(self) -> PyObjectRef

Convert to an owned PyObjectRef.

  • If borrowed → increments refcount, forgets self.
  • If owned → reconstructs PyObjectRef from the raw pointer, forgets self.
Source

pub fn promote(&mut self)

Promote a borrowed ref to owned in place (increments refcount, clears the borrow tag). No-op if already owned.

Methods from Deref<Target = PyObject>§

Source

pub fn try_to_value<'a, T>(&'a self, vm: &VirtualMachine) -> PyResult<T>
where T: 'a + TryFromBorrowedObject<'a>,

Source

pub fn try_to_ref<'a, T>(&'a self, vm: &VirtualMachine) -> PyResult<&'a Py<T>>
where T: 'a + PyPayload,

Source

pub fn try_value_with<T, F, R>(&self, f: F, vm: &VirtualMachine) -> PyResult<R>
where T: PyPayload, F: Fn(&T) -> PyResult<R>,

Source

pub fn try_bytes_like<R>( &self, vm: &VirtualMachine, f: impl FnOnce(&[u8]) -> R, ) -> PyResult<R>

Source

pub fn try_rw_bytes_like<R>( &self, vm: &VirtualMachine, f: impl FnOnce(&mut [u8]) -> R, ) -> PyResult<R>

Source

pub fn as_interned_str( &self, vm: &VirtualMachine, ) -> Option<&'static PyStrInterned>

Source

pub fn try_to_owned(&self) -> Option<PyObjectRef>

Atomically try to create a strong reference. Returns None if the strong count is already 0 (object being destroyed). Uses CAS to prevent the TOCTOU race between checking strong_count and incrementing it.

Source

pub fn downgrade( &self, callback: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<PyWeak>>

Source

pub fn get_weak_references(&self) -> Option<Vec<PyRef<PyWeak>>>

Source

pub fn payload_is<T: PyPayload>(&self) -> bool

👎Deprecated:

use downcastable instead

Source

pub unsafe fn payload_unchecked<T: PyPayload>(&self) -> &T

👎Deprecated:

use downcast_unchecked_ref instead

Force to return payload as T.

§Safety

The actual payload type must be T.

Source

pub fn payload<T: PyPayload>(&self) -> Option<&T>

👎Deprecated:

use downcast_ref instead

Source

pub fn class(&self) -> &Py<PyType>

Source

pub fn set_class(&self, typ: PyTypeRef, vm: &VirtualMachine)

Source

pub fn payload_if_exact<T: PyPayload>(&self, vm: &VirtualMachine) -> Option<&T>

👎Deprecated:

use downcast_ref_if_exact instead

Source

pub fn dict(&self) -> Option<PyDictRef>

Source

pub fn set_dict(&self, dict: PyDictRef) -> Result<(), PyDictRef>

Set the dict field. Returns Err(dict) if this object does not have a dict field in the first place.

Source

pub fn payload_if_subclass<T: PyPayload>( &self, vm: &VirtualMachine, ) -> Option<&T>

👎Deprecated:

use downcast_ref instead

Source

pub fn downcastable<T: PyPayload>(&self) -> bool

Check if this object can be downcast to T.

Source

pub fn try_downcast_ref<'a, T: PyPayload>( &'a self, vm: &VirtualMachine, ) -> PyResult<&'a Py<T>>

Attempt to downcast this reference to a subclass.

Source

pub fn downcast_ref<T: PyPayload>(&self) -> Option<&Py<T>>

Attempt to downcast this reference to a subclass.

Source

pub fn downcast_ref_if_exact<T: PyPayload>( &self, vm: &VirtualMachine, ) -> Option<&Py<T>>

Source

pub unsafe fn downcast_unchecked_ref<T: PyPayload>(&self) -> &Py<T>

§Safety

T must be the exact payload type

Source

pub fn strong_count(&self) -> usize

Source

pub fn weak_count(&self) -> Option<usize>

Source

pub fn as_raw(&self) -> *const Self

Source

pub fn is_gc_tracked(&self) -> bool

_PyObject_GC_IS_TRACKED

Source

pub fn gc_get_referents(&self) -> Vec<PyObjectRef>

Get the referents (objects directly referenced) of this object. Uses the full traverse including dict and slots.

Source

pub fn try_call_finalizer(&self)

Call del if present, without triggering object deallocation. Used by GC to call finalizers before breaking cycles. This allows proper resurrection detection. PyObject_CallFinalizerFromDealloc

Source

pub fn gc_clear_weakrefs_collect_callbacks( &self, ) -> Vec<(PyRef<PyWeak>, PyObjectRef)>

Clear weakrefs but collect callbacks instead of calling them. This is used by GC to ensure ALL weakrefs are cleared BEFORE any callbacks run. Returns collected callbacks as (PyRef, callback) pairs.

Source

pub unsafe fn gc_get_referent_ptrs(&self) -> Vec<NonNull<PyObject>>

Get raw pointers to referents without incrementing reference counts. This is used during GC to avoid reference count manipulation. tp_traverse visits objects without incref

§Safety

The returned pointers are only valid as long as the object is alive and its contents haven’t been modified.

Source

pub unsafe fn gc_clear(&self) -> Vec<PyObjectRef>

Clear this object for cycle breaking (tp_clear). This version takes &self but should only be called during GC when exclusive access is guaranteed.

§Safety
  • The caller must guarantee exclusive access (no other references exist)
  • This is only safe during GC when the object is unreachable
Source

pub fn gc_has_clear(&self) -> bool

Check if this object has clear capability (tp_clear)

Source

pub fn to_callable(&self) -> Option<PyCallable<'_>>

Source

pub fn is_callable(&self) -> bool

Source

pub fn call(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult

PyObject_CallArg series

Source

pub fn call_with_args(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult

PyObject_Call

Source

pub fn vectorcall( &self, args: Vec<PyObjectRef>, nargs: usize, kwnames: Option<&[PyObjectRef]>, vm: &VirtualMachine, ) -> PyResult

Vectorcall: call with owned positional args + optional kwnames. Falls back to FuncArgs-based call if no vectorcall slot.

Source

pub fn mapping_unchecked(&self) -> PyMapping<'_>

Source

pub fn try_mapping(&self, vm: &VirtualMachine) -> PyResult<PyMapping<'_>>

Source

pub fn number(&self) -> PyNumber<'_>

Source

pub fn try_index_opt(&self, vm: &VirtualMachine) -> Option<PyResult<PyIntRef>>

Source

pub fn try_index(&self, vm: &VirtualMachine) -> PyResult<PyIntRef>

Source

pub fn try_int(&self, vm: &VirtualMachine) -> PyResult<PyIntRef>

Source

pub fn try_float_opt( &self, vm: &VirtualMachine, ) -> Option<PyResult<PyRef<PyFloat>>>

Source

pub fn try_float(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyFloat>>

Source

pub fn get_iter(&self, vm: &VirtualMachine) -> PyResult<PyIter>

Takes an object and returns an iterator for it. This is typically a new iterator but if the argument is an iterator, this returns itself.

Source

pub fn get_aiter(&self, vm: &VirtualMachine) -> PyResult

Source

pub fn has_attr<'a>( &self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine, ) -> PyResult<bool>

Source

pub fn get_attr<'a>( &self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine, ) -> PyResult

Get an attribute by name. attr_name can be a &str, String, or PyStrRef.

Source

pub fn call_set_attr( &self, vm: &VirtualMachine, attr_name: &Py<PyStr>, attr_value: PySetterValue, ) -> PyResult<()>

Source

pub fn set_attr<'a>( &self, attr_name: impl AsPyStr<'a>, attr_value: impl Into<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()>

Source

pub fn generic_setattr( &self, attr_name: &Py<PyStr>, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()>

Source

pub fn generic_getattr(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult

Source

pub fn generic_getattr_opt( &self, name_str: &Py<PyStr>, dict: Option<PyDictRef>, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>>

CPython _PyObject_GenericGetAttrWithDict

Source

pub fn del_attr<'a>( &self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine, ) -> PyResult<()>

Source

pub fn rich_compare_bool( &self, other: &Self, op_id: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<bool>

Source

pub fn repr_utf8(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyUtf8Str>>

Source

pub fn repr(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>>

Source

pub fn ascii(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>>

Source

pub fn str_utf8(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyUtf8Str>>

Source

pub fn str(&self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>>

Source

pub fn real_is_subclass( &self, cls: &Self, vm: &VirtualMachine, ) -> PyResult<bool>

Real issubclass check without going through subclasscheck This is equivalent to CPython’s _PyObject_RealIsSubclass which just calls recursive_issubclass

Source

pub fn is_subclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool>

Determines if self is a subclass of cls, either directly, indirectly or virtually via the subclasscheck magic method. PyObject_IsSubclass/object_issubclass

Source

pub fn is_instance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool>

Determines if self is an instance of cls, either directly, indirectly or virtually via the instancecheck magic method.

Source

pub fn hash(&self, vm: &VirtualMachine) -> PyResult<PyHash>

Source

pub fn obj_type(&self) -> PyObjectRef

Source

pub fn type_check(&self, typ: &Py<PyType>) -> bool

Source

pub fn length_opt(&self, vm: &VirtualMachine) -> Option<PyResult<usize>>

Source

pub fn length(&self, vm: &VirtualMachine) -> PyResult<usize>

Source

pub fn get_item<K: DictKey + ?Sized>( &self, needle: &K, vm: &VirtualMachine, ) -> PyResult

Source

pub fn set_item<K: DictKey + ?Sized>( &self, needle: &K, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()>

Source

pub fn del_item<K: DictKey + ?Sized>( &self, needle: &K, vm: &VirtualMachine, ) -> PyResult<()>

Source

pub fn lookup_special( &self, attr: &Py<PyStr>, vm: &VirtualMachine, ) -> Option<PyObjectRef>

Equivalent to CPython’s _PyObject_LookupSpecial Looks up a special method in the type’s MRO without checking instance dict. Returns None if not found (masking AttributeError like CPython).

Source

pub fn sequence_unchecked(&self) -> PySequence<'_>

Source

pub fn try_sequence(&self, vm: &VirtualMachine) -> PyResult<PySequence<'_>>

Trait Implementations§

Source§

impl Clone for PyStackRef

Source§

fn clone(&self) -> Self

Cloning always produces an owned reference (increments refcount).

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PyStackRef

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for PyStackRef

Source§

type Target = PyObject

The resulting type after dereferencing.
Source§

fn deref(&self) -> &PyObject

Dereferences the value.
Source§

impl Drop for PyStackRef

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Traverse for PyStackRef

Source§

fn traverse(&self, traverse_fn: &mut TraverseFn<'_>)

impl traverse() with caution! Following those guideline so traverse doesn’t cause memory error!: Read more
Source§

fn clear(&mut self, _out: &mut Vec<PyObjectRef>)

Extract all owned child PyObjectRefs for circular reference resolution (tp_clear). Called just before object deallocation to break circular references. Default implementation does nothing.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T, U> ExactFrom<T> for U
where U: TryFrom<T>,

Source§

fn exact_from(value: T) -> U

Source§

impl<T, U> ExactInto<U> for T
where U: ExactFrom<T>,

Source§

fn exact_into(self) -> U

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> OverflowingInto<U> for T
where U: OverflowingFrom<T>,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> RoundingInto<U> for T
where U: RoundingFrom<T>,

Source§

impl<T, U> SaturatingInto<U> for T
where U: SaturatingFrom<T>,

Source§

impl<T> ToDebugString for T
where T: Debug,

Source§

fn to_debug_string(&self) -> String

Returns the String produced by Ts Debug implementation.

§Examples
use malachite_base::strings::ToDebugString;

assert_eq!([1, 2, 3].to_debug_string(), "[1, 2, 3]");
assert_eq!(
    [vec![2, 3], vec![], vec![4]].to_debug_string(),
    "[[2, 3], [], [4]]"
);
assert_eq!(Some(5).to_debug_string(), "Some(5)");
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> WrappingInto<U> for T
where U: WrappingFrom<T>,

Source§

fn wrapping_into(self) -> U

Source§

impl<T> PyThreadingConstraint for T