##// END OF EJS Templates
rust-cpython: move borrow_mut() to PySharedRefCell...
Yuya Nishihara -
r43444:1c675c5f default
parent child Browse files
Show More
@@ -1,405 +1,411 b''
1 // ref_sharing.rs
1 // ref_sharing.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to
6 // of this software and associated documentation files (the "Software"), to
7 // deal in the Software without restriction, including without limitation the
7 // deal in the Software without restriction, including without limitation the
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 // sell copies of the Software, and to permit persons to whom the Software is
9 // sell copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
10 // furnished to do so, subject to the following conditions:
11 //
11 //
12 // The above copyright notice and this permission notice shall be included in
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
13 // all copies or substantial portions of the Software.
14 //
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 // IN THE SOFTWARE.
21 // IN THE SOFTWARE.
22
22
23 //! Macros for use in the `hg-cpython` bridge library.
23 //! Macros for use in the `hg-cpython` bridge library.
24
24
25 use crate::exceptions::AlreadyBorrowed;
25 use crate::exceptions::AlreadyBorrowed;
26 use cpython::{PyResult, Python};
26 use cpython::{PyResult, Python};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
28
28
29 /// Manages the shared state between Python and Rust
29 /// Manages the shared state between Python and Rust
30 #[derive(Debug, Default)]
30 #[derive(Debug, Default)]
31 pub struct PySharedState {
31 pub struct PySharedState {
32 leak_count: Cell<usize>,
32 leak_count: Cell<usize>,
33 mutably_borrowed: Cell<bool>,
33 mutably_borrowed: Cell<bool>,
34 }
34 }
35
35
36 impl PySharedState {
36 impl PySharedState {
37 pub fn borrow_mut<'a, T>(
37 pub fn borrow_mut<'a, T>(
38 &'a self,
38 &'a self,
39 py: Python<'a>,
39 py: Python<'a>,
40 pyrefmut: RefMut<'a, T>,
40 pyrefmut: RefMut<'a, T>,
41 ) -> PyResult<PyRefMut<'a, T>> {
41 ) -> PyResult<PyRefMut<'a, T>> {
42 if self.mutably_borrowed.get() {
42 if self.mutably_borrowed.get() {
43 return Err(AlreadyBorrowed::new(
43 return Err(AlreadyBorrowed::new(
44 py,
44 py,
45 "Cannot borrow mutably while there exists another \
45 "Cannot borrow mutably while there exists another \
46 mutable reference in a Python object",
46 mutable reference in a Python object",
47 ));
47 ));
48 }
48 }
49 match self.leak_count.get() {
49 match self.leak_count.get() {
50 0 => {
50 0 => {
51 self.mutably_borrowed.replace(true);
51 self.mutably_borrowed.replace(true);
52 Ok(PyRefMut::new(py, pyrefmut, self))
52 Ok(PyRefMut::new(py, pyrefmut, self))
53 }
53 }
54 // TODO
54 // TODO
55 // For now, this works differently than Python references
55 // For now, this works differently than Python references
56 // in the case of iterators.
56 // in the case of iterators.
57 // Python does not complain when the data an iterator
57 // Python does not complain when the data an iterator
58 // points to is modified if the iterator is never used
58 // points to is modified if the iterator is never used
59 // afterwards.
59 // afterwards.
60 // Here, we are stricter than this by refusing to give a
60 // Here, we are stricter than this by refusing to give a
61 // mutable reference if it is already borrowed.
61 // mutable reference if it is already borrowed.
62 // While the additional safety might be argued for, it
62 // While the additional safety might be argued for, it
63 // breaks valid programming patterns in Python and we need
63 // breaks valid programming patterns in Python and we need
64 // to fix this issue down the line.
64 // to fix this issue down the line.
65 _ => Err(AlreadyBorrowed::new(
65 _ => Err(AlreadyBorrowed::new(
66 py,
66 py,
67 "Cannot borrow mutably while there are \
67 "Cannot borrow mutably while there are \
68 immutable references in Python objects",
68 immutable references in Python objects",
69 )),
69 )),
70 }
70 }
71 }
71 }
72
72
73 /// Return a reference to the wrapped data with an artificial static
73 /// Return a reference to the wrapped data with an artificial static
74 /// lifetime.
74 /// lifetime.
75 /// We need to be protected by the GIL for thread-safety.
75 /// We need to be protected by the GIL for thread-safety.
76 ///
76 ///
77 /// # Safety
77 /// # Safety
78 ///
78 ///
79 /// This is highly unsafe since the lifetime of the given data can be
79 /// This is highly unsafe since the lifetime of the given data can be
80 /// extended. Do not call this function directly.
80 /// extended. Do not call this function directly.
81 pub unsafe fn leak_immutable<T>(
81 pub unsafe fn leak_immutable<T>(
82 &self,
82 &self,
83 py: Python,
83 py: Python,
84 data: &PySharedRefCell<T>,
84 data: &PySharedRefCell<T>,
85 ) -> PyResult<&'static T> {
85 ) -> PyResult<&'static T> {
86 if self.mutably_borrowed.get() {
86 if self.mutably_borrowed.get() {
87 return Err(AlreadyBorrowed::new(
87 return Err(AlreadyBorrowed::new(
88 py,
88 py,
89 "Cannot borrow immutably while there is a \
89 "Cannot borrow immutably while there is a \
90 mutable reference in Python objects",
90 mutable reference in Python objects",
91 ));
91 ));
92 }
92 }
93 let ptr = data.as_ptr();
93 let ptr = data.as_ptr();
94 self.leak_count.replace(self.leak_count.get() + 1);
94 self.leak_count.replace(self.leak_count.get() + 1);
95 Ok(&*ptr)
95 Ok(&*ptr)
96 }
96 }
97
97
98 /// # Safety
98 /// # Safety
99 ///
99 ///
100 /// It's unsafe to update the reference count without knowing the
100 /// It's unsafe to update the reference count without knowing the
101 /// reference is deleted. Do not call this function directly.
101 /// reference is deleted. Do not call this function directly.
102 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
102 pub unsafe fn decrease_leak_count(&self, _py: Python, mutable: bool) {
103 if mutable {
103 if mutable {
104 assert_eq!(self.leak_count.get(), 0);
104 assert_eq!(self.leak_count.get(), 0);
105 assert!(self.mutably_borrowed.get());
105 assert!(self.mutably_borrowed.get());
106 self.mutably_borrowed.replace(false);
106 self.mutably_borrowed.replace(false);
107 } else {
107 } else {
108 let count = self.leak_count.get();
108 let count = self.leak_count.get();
109 assert!(count > 0);
109 assert!(count > 0);
110 self.leak_count.replace(count - 1);
110 self.leak_count.replace(count - 1);
111 }
111 }
112 }
112 }
113 }
113 }
114
114
115 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
115 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
116 ///
116 ///
117 /// Only immutable operation is allowed through this interface.
117 /// Only immutable operation is allowed through this interface.
118 #[derive(Debug)]
118 #[derive(Debug)]
119 pub struct PySharedRefCell<T> {
119 pub struct PySharedRefCell<T> {
120 inner: RefCell<T>,
120 inner: RefCell<T>,
121 pub py_shared_state: PySharedState, // TODO: remove pub
121 pub py_shared_state: PySharedState, // TODO: remove pub
122 }
122 }
123
123
124 impl<T> PySharedRefCell<T> {
124 impl<T> PySharedRefCell<T> {
125 pub fn new(value: T) -> PySharedRefCell<T> {
125 pub fn new(value: T) -> PySharedRefCell<T> {
126 Self {
126 Self {
127 inner: RefCell::new(value),
127 inner: RefCell::new(value),
128 py_shared_state: PySharedState::default(),
128 py_shared_state: PySharedState::default(),
129 }
129 }
130 }
130 }
131
131
132 pub fn borrow(&self) -> Ref<T> {
132 pub fn borrow(&self) -> Ref<T> {
133 // py_shared_state isn't involved since
133 // py_shared_state isn't involved since
134 // - inner.borrow() would fail if self is mutably borrowed,
134 // - inner.borrow() would fail if self is mutably borrowed,
135 // - and inner.borrow_mut() would fail while self is borrowed.
135 // - and inner.borrow_mut() would fail while self is borrowed.
136 self.inner.borrow()
136 self.inner.borrow()
137 }
137 }
138
138
139 pub fn as_ptr(&self) -> *mut T {
139 pub fn as_ptr(&self) -> *mut T {
140 self.inner.as_ptr()
140 self.inner.as_ptr()
141 }
141 }
142
142
143 pub unsafe fn borrow_mut(&self) -> RefMut<T> {
143 // TODO: maybe this should be named as try_borrow_mut(), and use
144 // must be borrowed by self.py_shared_state(py).borrow_mut().
144 // inner.try_borrow_mut(). The current implementation panics if
145 self.inner.borrow_mut()
145 // self.inner has been borrowed, but returns error if py_shared_state
146 // refuses to borrow.
147 pub fn borrow_mut<'a>(
148 &'a self,
149 py: Python<'a>,
150 ) -> PyResult<PyRefMut<'a, T>> {
151 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
146 }
152 }
147 }
153 }
148
154
149 /// Holds a mutable reference to data shared between Python and Rust.
155 /// Holds a mutable reference to data shared between Python and Rust.
150 pub struct PyRefMut<'a, T> {
156 pub struct PyRefMut<'a, T> {
151 inner: RefMut<'a, T>,
157 inner: RefMut<'a, T>,
152 py_shared_state: &'a PySharedState,
158 py_shared_state: &'a PySharedState,
153 }
159 }
154
160
155 impl<'a, T> PyRefMut<'a, T> {
161 impl<'a, T> PyRefMut<'a, T> {
156 // Must be constructed by PySharedState after checking its leak_count.
162 // Must be constructed by PySharedState after checking its leak_count.
157 // Otherwise, drop() would incorrectly update the state.
163 // Otherwise, drop() would incorrectly update the state.
158 fn new(
164 fn new(
159 _py: Python<'a>,
165 _py: Python<'a>,
160 inner: RefMut<'a, T>,
166 inner: RefMut<'a, T>,
161 py_shared_state: &'a PySharedState,
167 py_shared_state: &'a PySharedState,
162 ) -> Self {
168 ) -> Self {
163 Self {
169 Self {
164 inner,
170 inner,
165 py_shared_state,
171 py_shared_state,
166 }
172 }
167 }
173 }
168 }
174 }
169
175
170 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
176 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
171 type Target = RefMut<'a, T>;
177 type Target = RefMut<'a, T>;
172
178
173 fn deref(&self) -> &Self::Target {
179 fn deref(&self) -> &Self::Target {
174 &self.inner
180 &self.inner
175 }
181 }
176 }
182 }
177 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
183 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
178 fn deref_mut(&mut self) -> &mut Self::Target {
184 fn deref_mut(&mut self) -> &mut Self::Target {
179 &mut self.inner
185 &mut self.inner
180 }
186 }
181 }
187 }
182
188
183 impl<'a, T> Drop for PyRefMut<'a, T> {
189 impl<'a, T> Drop for PyRefMut<'a, T> {
184 fn drop(&mut self) {
190 fn drop(&mut self) {
185 let gil = Python::acquire_gil();
191 let gil = Python::acquire_gil();
186 let py = gil.python();
192 let py = gil.python();
187 unsafe {
193 unsafe {
188 self.py_shared_state.decrease_leak_count(py, true);
194 self.py_shared_state.decrease_leak_count(py, true);
189 }
195 }
190 }
196 }
191 }
197 }
192
198
193 /// Allows a `py_class!` generated struct to share references to one of its
199 /// Allows a `py_class!` generated struct to share references to one of its
194 /// data members with Python.
200 /// data members with Python.
195 ///
201 ///
196 /// # Warning
202 /// # Warning
197 ///
203 ///
198 /// TODO allow Python container types: for now, integration with the garbage
204 /// TODO allow Python container types: for now, integration with the garbage
199 /// collector does not extend to Rust structs holding references to Python
205 /// collector does not extend to Rust structs holding references to Python
200 /// objects. Should the need surface, `__traverse__` and `__clear__` will
206 /// objects. Should the need surface, `__traverse__` and `__clear__` will
201 /// need to be written as per the `rust-cpython` docs on GC integration.
207 /// need to be written as per the `rust-cpython` docs on GC integration.
202 ///
208 ///
203 /// # Parameters
209 /// # Parameters
204 ///
210 ///
205 /// * `$name` is the same identifier used in for `py_class!` macro call.
211 /// * `$name` is the same identifier used in for `py_class!` macro call.
206 /// * `$inner_struct` is the identifier of the underlying Rust struct
212 /// * `$inner_struct` is the identifier of the underlying Rust struct
207 /// * `$data_member` is the identifier of the data member of `$inner_struct`
213 /// * `$data_member` is the identifier of the data member of `$inner_struct`
208 /// that will be shared.
214 /// that will be shared.
209 /// * `$leaked` is the identifier to give to the struct that will manage
215 /// * `$leaked` is the identifier to give to the struct that will manage
210 /// references to `$name`, to be used for example in other macros like
216 /// references to `$name`, to be used for example in other macros like
211 /// `py_shared_iterator`.
217 /// `py_shared_iterator`.
212 ///
218 ///
213 /// # Example
219 /// # Example
214 ///
220 ///
215 /// ```
221 /// ```
216 /// struct MyStruct {
222 /// struct MyStruct {
217 /// inner: Vec<u32>;
223 /// inner: Vec<u32>;
218 /// }
224 /// }
219 ///
225 ///
220 /// py_class!(pub class MyType |py| {
226 /// py_class!(pub class MyType |py| {
221 /// data inner: PySharedRefCell<MyStruct>;
227 /// data inner: PySharedRefCell<MyStruct>;
222 /// });
228 /// });
223 ///
229 ///
224 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
230 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
225 /// ```
231 /// ```
226 macro_rules! py_shared_ref {
232 macro_rules! py_shared_ref {
227 (
233 (
228 $name: ident,
234 $name: ident,
229 $inner_struct: ident,
235 $inner_struct: ident,
230 $data_member: ident,
236 $data_member: ident,
231 $leaked: ident,
237 $leaked: ident,
232 ) => {
238 ) => {
233 impl $name {
239 impl $name {
240 // TODO: remove this function in favor of inner(py).borrow_mut()
234 fn borrow_mut<'a>(
241 fn borrow_mut<'a>(
235 &'a self,
242 &'a self,
236 py: Python<'a>,
243 py: Python<'a>,
237 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
244 ) -> PyResult<crate::ref_sharing::PyRefMut<'a, $inner_struct>>
238 {
245 {
239 // assert $data_member type
246 // assert $data_member type
240 use crate::ref_sharing::PySharedRefCell;
247 use crate::ref_sharing::PySharedRefCell;
241 let data: &PySharedRefCell<_> = self.$data_member(py);
248 let data: &PySharedRefCell<_> = self.$data_member(py);
242 data.py_shared_state
249 data.borrow_mut(py)
243 .borrow_mut(py, unsafe { data.borrow_mut() })
244 }
250 }
245
251
246 /// Returns a leaked reference and its management object.
252 /// Returns a leaked reference and its management object.
247 ///
253 ///
248 /// # Safety
254 /// # Safety
249 ///
255 ///
250 /// It's up to you to make sure that the management object lives
256 /// It's up to you to make sure that the management object lives
251 /// longer than the leaked reference. Otherwise, you'll get a
257 /// longer than the leaked reference. Otherwise, you'll get a
252 /// dangling reference.
258 /// dangling reference.
253 unsafe fn leak_immutable<'a>(
259 unsafe fn leak_immutable<'a>(
254 &'a self,
260 &'a self,
255 py: Python<'a>,
261 py: Python<'a>,
256 ) -> PyResult<($leaked, &'static $inner_struct)> {
262 ) -> PyResult<($leaked, &'static $inner_struct)> {
257 // assert $data_member type
263 // assert $data_member type
258 use crate::ref_sharing::PySharedRefCell;
264 use crate::ref_sharing::PySharedRefCell;
259 let data: &PySharedRefCell<_> = self.$data_member(py);
265 let data: &PySharedRefCell<_> = self.$data_member(py);
260 let static_ref =
266 let static_ref =
261 data.py_shared_state.leak_immutable(py, data)?;
267 data.py_shared_state.leak_immutable(py, data)?;
262 let leak_handle = $leaked::new(py, self);
268 let leak_handle = $leaked::new(py, self);
263 Ok((leak_handle, static_ref))
269 Ok((leak_handle, static_ref))
264 }
270 }
265 }
271 }
266
272
267 /// Manage immutable references to `$name` leaked into Python
273 /// Manage immutable references to `$name` leaked into Python
268 /// iterators.
274 /// iterators.
269 ///
275 ///
270 /// In truth, this does not represent leaked references themselves;
276 /// In truth, this does not represent leaked references themselves;
271 /// it is instead useful alongside them to manage them.
277 /// it is instead useful alongside them to manage them.
272 pub struct $leaked {
278 pub struct $leaked {
273 inner: $name,
279 inner: $name,
274 }
280 }
275
281
276 impl $leaked {
282 impl $leaked {
277 // Marked as unsafe so client code wouldn't construct $leaked
283 // Marked as unsafe so client code wouldn't construct $leaked
278 // struct by mistake. Its drop() is unsafe.
284 // struct by mistake. Its drop() is unsafe.
279 unsafe fn new(py: Python, inner: &$name) -> Self {
285 unsafe fn new(py: Python, inner: &$name) -> Self {
280 Self {
286 Self {
281 inner: inner.clone_ref(py),
287 inner: inner.clone_ref(py),
282 }
288 }
283 }
289 }
284 }
290 }
285
291
286 impl Drop for $leaked {
292 impl Drop for $leaked {
287 fn drop(&mut self) {
293 fn drop(&mut self) {
288 let gil = Python::acquire_gil();
294 let gil = Python::acquire_gil();
289 let py = gil.python();
295 let py = gil.python();
290 let state = &self.inner.$data_member(py).py_shared_state;
296 let state = &self.inner.$data_member(py).py_shared_state;
291 unsafe {
297 unsafe {
292 state.decrease_leak_count(py, false);
298 state.decrease_leak_count(py, false);
293 }
299 }
294 }
300 }
295 }
301 }
296 };
302 };
297 }
303 }
298
304
299 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
305 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
300 ///
306 ///
301 /// TODO: this is a bit awkward to use, and a better (more complicated)
307 /// TODO: this is a bit awkward to use, and a better (more complicated)
302 /// procedural macro would simplify the interface a lot.
308 /// procedural macro would simplify the interface a lot.
303 ///
309 ///
304 /// # Parameters
310 /// # Parameters
305 ///
311 ///
306 /// * `$name` is the identifier to give to the resulting Rust struct.
312 /// * `$name` is the identifier to give to the resulting Rust struct.
307 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
313 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
308 /// * `$iterator_type` is the type of the Rust iterator.
314 /// * `$iterator_type` is the type of the Rust iterator.
309 /// * `$success_func` is a function for processing the Rust `(key, value)`
315 /// * `$success_func` is a function for processing the Rust `(key, value)`
310 /// tuple on iteration success, turning it into something Python understands.
316 /// tuple on iteration success, turning it into something Python understands.
311 /// * `$success_func` is the return type of `$success_func`
317 /// * `$success_func` is the return type of `$success_func`
312 ///
318 ///
313 /// # Example
319 /// # Example
314 ///
320 ///
315 /// ```
321 /// ```
316 /// struct MyStruct {
322 /// struct MyStruct {
317 /// inner: HashMap<Vec<u8>, Vec<u8>>;
323 /// inner: HashMap<Vec<u8>, Vec<u8>>;
318 /// }
324 /// }
319 ///
325 ///
320 /// py_class!(pub class MyType |py| {
326 /// py_class!(pub class MyType |py| {
321 /// data inner: PySharedRefCell<MyStruct>;
327 /// data inner: PySharedRefCell<MyStruct>;
322 ///
328 ///
323 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
329 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
324 /// let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
330 /// let (leak_handle, leaked_ref) = unsafe { self.leak_immutable(py)? };
325 /// MyTypeItemsIterator::from_inner(
331 /// MyTypeItemsIterator::from_inner(
326 /// py,
332 /// py,
327 /// leak_handle,
333 /// leak_handle,
328 /// leaked_ref.iter(),
334 /// leaked_ref.iter(),
329 /// )
335 /// )
330 /// }
336 /// }
331 /// });
337 /// });
332 ///
338 ///
333 /// impl MyType {
339 /// impl MyType {
334 /// fn translate_key_value(
340 /// fn translate_key_value(
335 /// py: Python,
341 /// py: Python,
336 /// res: (&Vec<u8>, &Vec<u8>),
342 /// res: (&Vec<u8>, &Vec<u8>),
337 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
343 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
338 /// let (f, entry) = res;
344 /// let (f, entry) = res;
339 /// Ok(Some((
345 /// Ok(Some((
340 /// PyBytes::new(py, f),
346 /// PyBytes::new(py, f),
341 /// PyBytes::new(py, entry),
347 /// PyBytes::new(py, entry),
342 /// )))
348 /// )))
343 /// }
349 /// }
344 /// }
350 /// }
345 ///
351 ///
346 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
352 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
347 ///
353 ///
348 /// py_shared_iterator!(
354 /// py_shared_iterator!(
349 /// MyTypeItemsIterator,
355 /// MyTypeItemsIterator,
350 /// MyTypeLeakedRef,
356 /// MyTypeLeakedRef,
351 /// HashMap<'static, Vec<u8>, Vec<u8>>,
357 /// HashMap<'static, Vec<u8>, Vec<u8>>,
352 /// MyType::translate_key_value,
358 /// MyType::translate_key_value,
353 /// Option<(PyBytes, PyBytes)>
359 /// Option<(PyBytes, PyBytes)>
354 /// );
360 /// );
355 /// ```
361 /// ```
356 macro_rules! py_shared_iterator {
362 macro_rules! py_shared_iterator {
357 (
363 (
358 $name: ident,
364 $name: ident,
359 $leaked: ident,
365 $leaked: ident,
360 $iterator_type: ty,
366 $iterator_type: ty,
361 $success_func: expr,
367 $success_func: expr,
362 $success_type: ty
368 $success_type: ty
363 ) => {
369 ) => {
364 py_class!(pub class $name |py| {
370 py_class!(pub class $name |py| {
365 data inner: RefCell<Option<$leaked>>;
371 data inner: RefCell<Option<$leaked>>;
366 data it: RefCell<$iterator_type>;
372 data it: RefCell<$iterator_type>;
367
373
368 def __next__(&self) -> PyResult<$success_type> {
374 def __next__(&self) -> PyResult<$success_type> {
369 let mut inner_opt = self.inner(py).borrow_mut();
375 let mut inner_opt = self.inner(py).borrow_mut();
370 if inner_opt.is_some() {
376 if inner_opt.is_some() {
371 match self.it(py).borrow_mut().next() {
377 match self.it(py).borrow_mut().next() {
372 None => {
378 None => {
373 // replace Some(inner) by None, drop $leaked
379 // replace Some(inner) by None, drop $leaked
374 inner_opt.take();
380 inner_opt.take();
375 Ok(None)
381 Ok(None)
376 }
382 }
377 Some(res) => {
383 Some(res) => {
378 $success_func(py, res)
384 $success_func(py, res)
379 }
385 }
380 }
386 }
381 } else {
387 } else {
382 Ok(None)
388 Ok(None)
383 }
389 }
384 }
390 }
385
391
386 def __iter__(&self) -> PyResult<Self> {
392 def __iter__(&self) -> PyResult<Self> {
387 Ok(self.clone_ref(py))
393 Ok(self.clone_ref(py))
388 }
394 }
389 });
395 });
390
396
391 impl $name {
397 impl $name {
392 pub fn from_inner(
398 pub fn from_inner(
393 py: Python,
399 py: Python,
394 leaked: $leaked,
400 leaked: $leaked,
395 it: $iterator_type
401 it: $iterator_type
396 ) -> PyResult<Self> {
402 ) -> PyResult<Self> {
397 Self::create_instance(
403 Self::create_instance(
398 py,
404 py,
399 RefCell::new(Some(leaked)),
405 RefCell::new(Some(leaked)),
400 RefCell::new(it)
406 RefCell::new(it)
401 )
407 )
402 }
408 }
403 }
409 }
404 };
410 };
405 }
411 }
General Comments 0
You need to be logged in to leave comments. Login now