Skip to main content

rustpython_capi/
objimpl.rs

1use crate::PyObject;
2use crate::pymem::{PyMem_Calloc, PyMem_Free, PyMem_Malloc, PyMem_Realloc};
3use crate::pystate::with_vm;
4use crate::util::FfiPtrExt;
5use core::ffi::{c_int, c_void};
6use rustpython_vm::gc_state;
7
8#[unsafe(no_mangle)]
9pub unsafe extern "C" fn PyObject_GC_Track(op: *mut PyObject) {
10    with_vm(|_vm| {
11        let obj = unsafe { op.assume_borrowed() };
12        if !obj.is_gc_tracked() {
13            unsafe { gc_state::gc_state().track_object(obj.into(), gc_state::current_owner()) };
14        }
15    })
16}
17
18#[unsafe(no_mangle)]
19pub unsafe extern "C" fn PyObject_GC_UnTrack(op: *mut PyObject) {
20    with_vm(|_vm| {
21        let obj = unsafe { op.assume_borrowed() };
22        if obj.is_gc_tracked() {
23            unsafe { gc_state::gc_state().untrack_object(obj.into()) };
24        }
25    })
26}
27
28#[unsafe(no_mangle)]
29pub unsafe extern "C" fn PyObject_GC_IsTracked(op: *mut PyObject) -> c_int {
30    with_vm(|_vm| unsafe { op.assume_borrowed() }.is_gc_tracked())
31}
32
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn PyObject_GC_IsFinalized(op: *mut PyObject) -> c_int {
35    with_vm(|_vm| unsafe { op.assume_borrowed() }.gc_finalized())
36}
37
38#[unsafe(no_mangle)]
39pub extern "C" fn PyGC_Collect() -> isize {
40    with_vm(|vm| {
41        let result = vm.state.gc.collect(2);
42        (result.collected + result.uncollectable) as isize
43    })
44}
45
46#[unsafe(no_mangle)]
47pub extern "C" fn PyGC_Enable() -> c_int {
48    with_vm(|vm| {
49        let was_enabled: c_int = vm.state.gc.is_enabled().into();
50        vm.state.gc.enable();
51        was_enabled
52    })
53}
54
55#[unsafe(no_mangle)]
56pub extern "C" fn PyGC_Disable() -> c_int {
57    with_vm(|vm| {
58        let was_enabled: c_int = vm.state.gc.is_enabled().into();
59        vm.state.gc.disable();
60        was_enabled
61    })
62}
63
64#[unsafe(no_mangle)]
65pub extern "C" fn PyGC_IsEnabled() -> c_int {
66    with_vm(|vm| -> c_int { vm.state.gc.is_enabled().into() })
67}
68
69#[unsafe(no_mangle)]
70pub unsafe extern "C" fn PyObject_Malloc(size: usize) -> *mut c_void {
71    unsafe { PyMem_Malloc(size) }
72}
73
74#[unsafe(no_mangle)]
75pub unsafe extern "C" fn PyObject_Calloc(nelem: usize, elsize: usize) -> *mut c_void {
76    unsafe { PyMem_Calloc(nelem, elsize) }
77}
78
79#[unsafe(no_mangle)]
80pub unsafe extern "C" fn PyObject_Realloc(ptr: *mut c_void, new_size: usize) -> *mut c_void {
81    unsafe { PyMem_Realloc(ptr, new_size) }
82}
83
84#[unsafe(no_mangle)]
85pub unsafe extern "C" fn PyObject_Free(ptr: *mut c_void) {
86    unsafe { PyMem_Free(ptr) }
87}