pyo3/pyclass/
gc.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::{
    marker::PhantomData,
    os::raw::{c_int, c_void},
};

use crate::{ffi, AsPyPointer};

/// Error returned by a `__traverse__` visitor implementation.
#[repr(transparent)]
pub struct PyTraverseError(NonZeroCInt);

impl PyTraverseError {
    /// Returns the error code.
    pub(crate) fn into_inner(self) -> c_int {
        self.0.into()
    }
}

/// Object visitor for GC.
#[derive(Clone)]
pub struct PyVisit<'a> {
    pub(crate) visit: ffi::visitproc,
    pub(crate) arg: *mut c_void,
    /// Prevents the `PyVisit` from outliving the `__traverse__` call.
    pub(crate) _guard: PhantomData<&'a ()>,
}

impl PyVisit<'_> {
    /// Visit `obj`.
    pub fn call<T>(&self, obj: &T) -> Result<(), PyTraverseError>
    where
        T: AsPyPointer,
    {
        let ptr = obj.as_ptr();
        if !ptr.is_null() {
            match NonZeroCInt::new(unsafe { (self.visit)(ptr, self.arg) }) {
                None => Ok(()),
                Some(r) => Err(PyTraverseError(r)),
            }
        } else {
            Ok(())
        }
    }
}

/// Workaround for `NonZero<c_int>` not being available until MSRV 1.79
mod get_nonzero_c_int {
    pub struct GetNonZeroCInt<const WIDTH: usize>();

    pub trait NonZeroCIntType {
        type Type;
    }
    impl NonZeroCIntType for GetNonZeroCInt<16> {
        type Type = std::num::NonZeroI16;
    }
    impl NonZeroCIntType for GetNonZeroCInt<32> {
        type Type = std::num::NonZeroI32;
    }

    pub type Type =
        <GetNonZeroCInt<{ std::mem::size_of::<std::os::raw::c_int>() * 8 }> as NonZeroCIntType>::Type;
}

use get_nonzero_c_int::Type as NonZeroCInt;

#[cfg(test)]
mod tests {
    use super::PyVisit;
    use static_assertions::assert_not_impl_any;

    #[test]
    fn py_visit_not_send_sync() {
        assert_not_impl_any!(PyVisit<'_>: Send, Sync);
    }
}