rustpython-vm 0.6.0

RustPython virtual machine.
Documentation
//! Implementation in line with the python `weakref` module.
//!
//! See also:
//! - [python weakref module](https://docs.python.org/3/library/weakref.html)
//! - [rust weak struct](https://doc.rust-lang.org/std/rc/struct.Weak.html)
//!
pub(crate) use _weakref::module_def;

#[pymodule]
mod _weakref {
    use crate::{
        PyObjectRef, PyResult, VirtualMachine,
        builtins::{PyDictRef, PyTypeRef, PyWeak},
    };

    #[pyattr(name = "ref")]
    fn ref_(vm: &VirtualMachine) -> PyTypeRef {
        vm.ctx.types.weakref_type.to_owned()
    }

    #[pyfunction]
    fn proxy(args: crate::builtins::WeakProxyNewArgs, vm: &VirtualMachine) -> PyResult {
        crate::builtins::PyWeakProxy::from_new_args(args, vm).map(Into::into)
    }

    #[pyattr(name = "ReferenceType")]
    fn reference_type(vm: &VirtualMachine) -> PyTypeRef {
        vm.ctx.types.weakref_type.to_owned()
    }

    #[pyattr(name = "ProxyType")]
    fn proxy_type(vm: &VirtualMachine) -> PyTypeRef {
        vm.ctx.types.weakproxy_type.to_owned()
    }

    #[pyattr(name = "CallableProxyType")]
    fn callable_proxy_type(vm: &VirtualMachine) -> PyTypeRef {
        vm.ctx.types.weakcallableproxy_type.to_owned()
    }

    #[pyfunction]
    fn getweakrefcount(object: PyObjectRef) -> usize {
        object.weak_count().unwrap_or(0)
    }

    #[pyfunction]
    fn getweakrefs(object: PyObjectRef) -> Vec<PyObjectRef> {
        object
            .get_weak_references()
            .map_or_else(Vec::new, |v| v.into_iter().map(Into::into).collect())
    }

    #[pyfunction]
    fn _remove_dead_weakref(dct: PyDictRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
        dct._as_dict_inner()
            .delete_if(vm, &*key, |wr| {
                let wr = wr
                    .downcast_ref::<PyWeak>()
                    .ok_or_else(|| vm.new_type_error("not a weakref"))?;
                Ok(wr.is_dead())
            })
            .map(drop)
    }
}