@@ -2,8 +2,8 @@ use super::{PyStrRef, PyType, PyTypeRef, PyWeak};
2
2
use crate :: {
3
3
class:: PyClassImpl ,
4
4
function:: OptionalArg ,
5
- protocol:: { PySequence , PySequenceMethods } ,
6
- types:: { AsSequence , Constructor , GetAttr , SetAttr } ,
5
+ protocol:: { PyMappingMethods , PySequence , PySequenceMethods } ,
6
+ types:: { AsMapping , AsSequence , Constructor , GetAttr , SetAttr } ,
7
7
Context , Py , PyObjectRef , PyPayload , PyRef , PyResult , VirtualMachine ,
8
8
} ;
9
9
@@ -58,7 +58,7 @@ crate::common::static_cell! {
58
58
static WEAK_SUBCLASS : PyTypeRef ;
59
59
}
60
60
61
- #[ pyimpl( with( GetAttr , SetAttr , Constructor , AsSequence ) ) ]
61
+ #[ pyimpl( with( GetAttr , SetAttr , Constructor , AsSequence , AsMapping ) ) ]
62
62
impl PyWeakProxy {
63
63
#[ pymethod( magic) ]
64
64
fn str ( & self , vm : & VirtualMachine ) -> PyResult < PyStrRef > {
@@ -81,6 +81,32 @@ impl PyWeakProxy {
81
81
None => Err ( new_reference_error ( vm) ) ,
82
82
}
83
83
}
84
+
85
+ fn getitem ( & self , needle : PyObjectRef , vm : & VirtualMachine ) -> PyResult {
86
+ match self . weak . upgrade ( ) {
87
+ Some ( obj) => obj. get_item ( & * needle, vm) ,
88
+ None => Err ( new_reference_error ( vm) ) ,
89
+ }
90
+ }
91
+
92
+ fn setitem (
93
+ & self ,
94
+ needle : PyObjectRef ,
95
+ value : PyObjectRef ,
96
+ vm : & VirtualMachine ,
97
+ ) -> PyResult < ( ) > {
98
+ match self . weak . upgrade ( ) {
99
+ Some ( obj) => obj. set_item ( & * needle, value, vm) ,
100
+ None => Err ( new_reference_error ( vm) ) ,
101
+ }
102
+ }
103
+
104
+ fn delitem ( & self , needle : PyObjectRef , vm : & VirtualMachine ) -> PyResult < ( ) > {
105
+ match self . weak . upgrade ( ) {
106
+ Some ( obj) => obj. del_item ( & * needle, vm) ,
107
+ None => Err ( new_reference_error ( vm) ) ,
108
+ }
109
+ }
84
110
}
85
111
86
112
fn new_reference_error ( vm : & VirtualMachine ) -> PyRef < super :: PyBaseException > {
@@ -125,6 +151,23 @@ impl AsSequence for PyWeakProxy {
125
151
} ;
126
152
}
127
153
154
+ impl AsMapping for PyWeakProxy {
155
+ const AS_MAPPING : PyMappingMethods = PyMappingMethods {
156
+ length : Some ( |mapping, vm| Self :: mapping_downcast ( mapping) . len ( vm) ) ,
157
+ subscript : Some ( |mapping, needle, vm| {
158
+ Self :: mapping_downcast ( mapping) . getitem ( needle. to_owned ( ) , vm)
159
+ } ) ,
160
+ ass_subscript : Some ( |mapping, needle, value, vm| {
161
+ let zelf = Self :: mapping_downcast ( mapping) ;
162
+ if let Some ( value) = value {
163
+ zelf. setitem ( needle. to_owned ( ) , value, vm)
164
+ } else {
165
+ zelf. delitem ( needle. to_owned ( ) , vm)
166
+ }
167
+ } ) ,
168
+ } ;
169
+ }
170
+
128
171
pub fn init ( context : & Context ) {
129
172
PyWeakProxy :: extend_class ( context, context. types . weakproxy_type ) ;
130
173
}
0 commit comments