-
Notifications
You must be signed in to change notification settings - Fork 677
/
pyclass_slots.rs
92 lines (83 loc) · 2.46 KB
/
pyclass_slots.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! This module contains additional fields for `#[pyclass]`..
//! Mainly used by our proc-macro codes.
use crate::{ffi, Python};
/// Represents `__dict__` field for `#[pyclass]`.
pub trait PyClassDict {
/// Whether this `__dict__` field is capable of holding a dictionary.
const IS_DUMMY: bool = true;
/// Initializes a [PyObject](crate::ffi::PyObject) `__dict__` reference.
fn new() -> Self;
/// Empties the dictionary of its key-value pairs.
#[inline]
fn clear_dict(&mut self, _py: Python) {}
private_decl! {}
}
/// Represents `__weakref__` field for `#[pyclass]`.
pub trait PyClassWeakRef {
/// Whether this `weakref` type is capable of holding weak references.
const IS_DUMMY: bool = true;
/// Initializes a `weakref` instance.
fn new() -> Self;
/// Clears the weak references to the given object.
///
/// # Safety
/// - `_obj` must be a pointer to the pyclass instance which contains `self`.
/// - The GIL must be held.
#[inline]
unsafe fn clear_weakrefs(&mut self, _obj: *mut ffi::PyObject, _py: Python) {}
private_decl! {}
}
/// Zero-sized dummy field.
pub struct PyClassDummySlot;
impl PyClassDict for PyClassDummySlot {
private_impl! {}
#[inline]
fn new() -> Self {
PyClassDummySlot
}
}
impl PyClassWeakRef for PyClassDummySlot {
private_impl! {}
#[inline]
fn new() -> Self {
PyClassDummySlot
}
}
/// Actual dict field, which holds the pointer to `__dict__`.
///
/// `#[pyclass(dict)]` automatically adds this.
#[repr(transparent)]
pub struct PyClassDictSlot(*mut ffi::PyObject);
impl PyClassDict for PyClassDictSlot {
private_impl! {}
const IS_DUMMY: bool = false;
#[inline]
fn new() -> Self {
Self(std::ptr::null_mut())
}
#[inline]
fn clear_dict(&mut self, _py: Python) {
if !self.0.is_null() {
unsafe { ffi::PyDict_Clear(self.0) }
}
}
}
/// Actual weakref field, which holds the pointer to `__weakref__`.
///
/// `#[pyclass(weakref)]` automatically adds this.
#[repr(transparent)]
pub struct PyClassWeakRefSlot(*mut ffi::PyObject);
impl PyClassWeakRef for PyClassWeakRefSlot {
private_impl! {}
const IS_DUMMY: bool = false;
#[inline]
fn new() -> Self {
Self(std::ptr::null_mut())
}
#[inline]
unsafe fn clear_weakrefs(&mut self, obj: *mut ffi::PyObject, _py: Python) {
if !self.0.is_null() {
ffi::PyObject_ClearWeakRefs(obj)
}
}
}