Show More
@@ -1,716 +1,705 | |||||
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::{exc, PyClone, PyErr, PyObject, PyResult, Python}; |
|
26 | use cpython::{exc, PyClone, PyErr, PyObject, PyResult, Python}; | |
27 | use std::cell::{Cell, Ref, RefCell, RefMut}; |
|
27 | use std::cell::{Cell, Ref, RefCell, RefMut}; | |
28 | use std::ops::{Deref, DerefMut}; |
|
28 | use std::ops::{Deref, DerefMut}; | |
29 | use std::sync::atomic::{AtomicUsize, Ordering}; |
|
29 | use std::sync::atomic::{AtomicUsize, Ordering}; | |
30 |
|
30 | |||
31 | /// Manages the shared state between Python and Rust |
|
31 | /// Manages the shared state between Python and Rust | |
32 | /// |
|
32 | /// | |
33 | /// `PySharedState` is owned by `PySharedRefCell`, and is shared across its |
|
33 | /// `PySharedState` is owned by `PySharedRefCell`, and is shared across its | |
34 | /// derived references. The consistency of these references are guaranteed |
|
34 | /// derived references. The consistency of these references are guaranteed | |
35 | /// as follows: |
|
35 | /// as follows: | |
36 | /// |
|
36 | /// | |
37 | /// - The immutability of `py_class!` object fields. Any mutation of |
|
37 | /// - The immutability of `py_class!` object fields. Any mutation of | |
38 | /// `PySharedRefCell` is allowed only through its `borrow_mut()`. |
|
38 | /// `PySharedRefCell` is allowed only through its `borrow_mut()`. | |
39 | /// - The `py: Python<'_>` token, which makes sure that any data access is |
|
39 | /// - The `py: Python<'_>` token, which makes sure that any data access is | |
40 | /// synchronized by the GIL. |
|
40 | /// synchronized by the GIL. | |
41 | /// - The `borrow_count`, which is the number of references borrowed from |
|
41 | /// - The `borrow_count`, which is the number of references borrowed from | |
42 | /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked` |
|
42 | /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked` | |
43 | /// is borrowed. |
|
43 | /// is borrowed. | |
44 | /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked` |
|
44 | /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked` | |
45 | /// reference is valid only if the `current_generation()` equals to the |
|
45 | /// reference is valid only if the `current_generation()` equals to the | |
46 | /// `generation` at the time of `leak_immutable()`. |
|
46 | /// `generation` at the time of `leak_immutable()`. | |
47 | #[derive(Debug, Default)] |
|
47 | #[derive(Debug, Default)] | |
48 | struct PySharedState { |
|
48 | struct PySharedState { | |
49 | mutably_borrowed: Cell<bool>, |
|
49 | mutably_borrowed: Cell<bool>, | |
50 | // The counter variable could be Cell<usize> since any operation on |
|
50 | // The counter variable could be Cell<usize> since any operation on | |
51 | // PySharedState is synchronized by the GIL, but being "atomic" makes |
|
51 | // PySharedState is synchronized by the GIL, but being "atomic" makes | |
52 | // PySharedState inherently Sync. The ordering requirement doesn't |
|
52 | // PySharedState inherently Sync. The ordering requirement doesn't | |
53 | // matter thanks to the GIL. |
|
53 | // matter thanks to the GIL. | |
54 | borrow_count: AtomicUsize, |
|
54 | borrow_count: AtomicUsize, | |
55 | generation: AtomicUsize, |
|
55 | generation: AtomicUsize, | |
56 | } |
|
56 | } | |
57 |
|
57 | |||
58 | // &PySharedState can be Send because any access to inner cells is |
|
58 | // &PySharedState can be Send because any access to inner cells is | |
59 | // synchronized by the GIL. |
|
59 | // synchronized by the GIL. | |
60 | unsafe impl Sync for PySharedState {} |
|
60 | unsafe impl Sync for PySharedState {} | |
61 |
|
61 | |||
62 | impl PySharedState { |
|
62 | impl PySharedState { | |
63 | fn borrow_mut<'a, T>( |
|
63 | fn borrow_mut<'a, T>( | |
64 | &'a self, |
|
64 | &'a self, | |
65 | py: Python<'a>, |
|
65 | py: Python<'a>, | |
66 | pyrefmut: RefMut<'a, T>, |
|
66 | pyrefmut: RefMut<'a, T>, | |
67 | ) -> PyResult<PyRefMut<'a, T>> { |
|
67 | ) -> PyResult<PyRefMut<'a, T>> { | |
68 | if self.mutably_borrowed.get() { |
|
68 | if self.mutably_borrowed.get() { | |
69 | return Err(AlreadyBorrowed::new( |
|
69 | return Err(AlreadyBorrowed::new( | |
70 | py, |
|
70 | py, | |
71 | "Cannot borrow mutably while there exists another \ |
|
71 | "Cannot borrow mutably while there exists another \ | |
72 | mutable reference in a Python object", |
|
72 | mutable reference in a Python object", | |
73 | )); |
|
73 | )); | |
74 | } |
|
74 | } | |
75 | match self.current_borrow_count(py) { |
|
75 | match self.current_borrow_count(py) { | |
76 | 0 => { |
|
76 | 0 => { | |
77 | self.mutably_borrowed.replace(true); |
|
77 | self.mutably_borrowed.replace(true); | |
78 | // Note that this wraps around to the same value if mutably |
|
78 | // Note that this wraps around to the same value if mutably | |
79 | // borrowed more than usize::MAX times, which wouldn't happen |
|
79 | // borrowed more than usize::MAX times, which wouldn't happen | |
80 | // in practice. |
|
80 | // in practice. | |
81 | self.generation.fetch_add(1, Ordering::Relaxed); |
|
81 | self.generation.fetch_add(1, Ordering::Relaxed); | |
82 | Ok(PyRefMut::new(py, pyrefmut, self)) |
|
82 | Ok(PyRefMut::new(py, pyrefmut, self)) | |
83 | } |
|
83 | } | |
84 | _ => Err(AlreadyBorrowed::new( |
|
84 | _ => Err(AlreadyBorrowed::new( | |
85 | py, |
|
85 | py, | |
86 | "Cannot borrow mutably while immutably borrowed", |
|
86 | "Cannot borrow mutably while immutably borrowed", | |
87 | )), |
|
87 | )), | |
88 | } |
|
88 | } | |
89 | } |
|
89 | } | |
90 |
|
90 | |||
91 | /// Return a reference to the wrapped data and its state with an |
|
91 | /// Return a reference to the wrapped data and its state with an | |
92 | /// artificial static lifetime. |
|
92 | /// artificial static lifetime. | |
93 | /// We need to be protected by the GIL for thread-safety. |
|
93 | /// We need to be protected by the GIL for thread-safety. | |
94 | /// |
|
94 | /// | |
95 | /// # Safety |
|
95 | /// # Safety | |
96 | /// |
|
96 | /// | |
97 | /// This is highly unsafe since the lifetime of the given data can be |
|
97 | /// This is highly unsafe since the lifetime of the given data can be | |
98 | /// extended. Do not call this function directly. |
|
98 | /// extended. Do not call this function directly. | |
99 | unsafe fn leak_immutable<T>( |
|
99 | unsafe fn leak_immutable<T>( | |
100 | &self, |
|
100 | &self, | |
101 | py: Python, |
|
101 | py: Python, | |
102 | data: &PySharedRefCell<T>, |
|
102 | data: &PySharedRefCell<T>, | |
103 | ) -> PyResult<(&'static T, &'static PySharedState)> { |
|
103 | ) -> PyResult<(&'static T, &'static PySharedState)> { | |
104 | if self.mutably_borrowed.get() { |
|
104 | if self.mutably_borrowed.get() { | |
105 | return Err(AlreadyBorrowed::new( |
|
105 | return Err(AlreadyBorrowed::new( | |
106 | py, |
|
106 | py, | |
107 | "Cannot borrow immutably while there is a \ |
|
107 | "Cannot borrow immutably while there is a \ | |
108 | mutable reference in Python objects", |
|
108 | mutable reference in Python objects", | |
109 | )); |
|
109 | )); | |
110 | } |
|
110 | } | |
111 | // TODO: it's weird that self is data.py_shared_state. Maybe we |
|
111 | // TODO: it's weird that self is data.py_shared_state. Maybe we | |
112 | // can move stuff to PySharedRefCell? |
|
112 | // can move stuff to PySharedRefCell? | |
113 | let ptr = data.as_ptr(); |
|
113 | let ptr = data.as_ptr(); | |
114 | let state_ptr: *const PySharedState = &data.py_shared_state; |
|
114 | let state_ptr: *const PySharedState = &data.py_shared_state; | |
115 | Ok((&*ptr, &*state_ptr)) |
|
115 | Ok((&*ptr, &*state_ptr)) | |
116 | } |
|
116 | } | |
117 |
|
117 | |||
118 | fn current_borrow_count(&self, _py: Python) -> usize { |
|
118 | fn current_borrow_count(&self, _py: Python) -> usize { | |
119 | self.borrow_count.load(Ordering::Relaxed) |
|
119 | self.borrow_count.load(Ordering::Relaxed) | |
120 | } |
|
120 | } | |
121 |
|
121 | |||
122 | fn increase_borrow_count(&self, _py: Python) { |
|
122 | fn increase_borrow_count(&self, _py: Python) { | |
123 | // Note that this wraps around if there are more than usize::MAX |
|
123 | // Note that this wraps around if there are more than usize::MAX | |
124 | // borrowed references, which shouldn't happen due to memory limit. |
|
124 | // borrowed references, which shouldn't happen due to memory limit. | |
125 | self.borrow_count.fetch_add(1, Ordering::Relaxed); |
|
125 | self.borrow_count.fetch_add(1, Ordering::Relaxed); | |
126 | } |
|
126 | } | |
127 |
|
127 | |||
128 | fn decrease_borrow_count(&self, _py: Python) { |
|
128 | fn decrease_borrow_count(&self, _py: Python) { | |
129 | let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed); |
|
129 | let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed); | |
130 | assert!(prev_count > 0); |
|
130 | assert!(prev_count > 0); | |
131 | } |
|
131 | } | |
132 |
|
132 | |||
133 | /// # Safety |
|
133 | /// # Safety | |
134 | /// |
|
134 | /// | |
135 | /// It's up to you to make sure the reference is about to be deleted |
|
135 | /// It's up to you to make sure the reference is about to be deleted | |
136 | /// when updating the leak count. |
|
136 | /// when updating the leak count. | |
137 | fn decrease_leak_count(&self, py: Python, mutable: bool) { |
|
137 | fn decrease_leak_count(&self, py: Python, mutable: bool) { | |
138 | if mutable { |
|
138 | if mutable { | |
139 | assert_eq!(self.current_borrow_count(py), 0); |
|
139 | assert_eq!(self.current_borrow_count(py), 0); | |
140 | assert!(self.mutably_borrowed.get()); |
|
140 | assert!(self.mutably_borrowed.get()); | |
141 | self.mutably_borrowed.replace(false); |
|
141 | self.mutably_borrowed.replace(false); | |
142 | } else { |
|
142 | } else { | |
143 | unimplemented!(); |
|
143 | unimplemented!(); | |
144 | } |
|
144 | } | |
145 | } |
|
145 | } | |
146 |
|
146 | |||
147 | fn current_generation(&self, _py: Python) -> usize { |
|
147 | fn current_generation(&self, _py: Python) -> usize { | |
148 | self.generation.load(Ordering::Relaxed) |
|
148 | self.generation.load(Ordering::Relaxed) | |
149 | } |
|
149 | } | |
150 | } |
|
150 | } | |
151 |
|
151 | |||
152 | /// Helper to keep the borrow count updated while the shared object is |
|
152 | /// Helper to keep the borrow count updated while the shared object is | |
153 | /// immutably borrowed without using the `RefCell` interface. |
|
153 | /// immutably borrowed without using the `RefCell` interface. | |
154 | struct BorrowPyShared<'a> { |
|
154 | struct BorrowPyShared<'a> { | |
155 | py: Python<'a>, |
|
155 | py: Python<'a>, | |
156 | py_shared_state: &'a PySharedState, |
|
156 | py_shared_state: &'a PySharedState, | |
157 | } |
|
157 | } | |
158 |
|
158 | |||
159 | impl<'a> BorrowPyShared<'a> { |
|
159 | impl<'a> BorrowPyShared<'a> { | |
160 | fn new( |
|
160 | fn new( | |
161 | py: Python<'a>, |
|
161 | py: Python<'a>, | |
162 | py_shared_state: &'a PySharedState, |
|
162 | py_shared_state: &'a PySharedState, | |
163 | ) -> BorrowPyShared<'a> { |
|
163 | ) -> BorrowPyShared<'a> { | |
164 | py_shared_state.increase_borrow_count(py); |
|
164 | py_shared_state.increase_borrow_count(py); | |
165 | BorrowPyShared { |
|
165 | BorrowPyShared { | |
166 | py, |
|
166 | py, | |
167 | py_shared_state, |
|
167 | py_shared_state, | |
168 | } |
|
168 | } | |
169 | } |
|
169 | } | |
170 | } |
|
170 | } | |
171 |
|
171 | |||
172 | impl Drop for BorrowPyShared<'_> { |
|
172 | impl Drop for BorrowPyShared<'_> { | |
173 | fn drop(&mut self) { |
|
173 | fn drop(&mut self) { | |
174 | self.py_shared_state.decrease_borrow_count(self.py); |
|
174 | self.py_shared_state.decrease_borrow_count(self.py); | |
175 | } |
|
175 | } | |
176 | } |
|
176 | } | |
177 |
|
177 | |||
178 | /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`. |
|
178 | /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`. | |
179 | /// |
|
179 | /// | |
180 | /// This object can be stored in a `py_class!` object as a data field. Any |
|
180 | /// This object can be stored in a `py_class!` object as a data field. Any | |
181 | /// operation is allowed through the `PySharedRef` interface. |
|
181 | /// operation is allowed through the `PySharedRef` interface. | |
182 | #[derive(Debug)] |
|
182 | #[derive(Debug)] | |
183 | pub struct PySharedRefCell<T> { |
|
183 | pub struct PySharedRefCell<T> { | |
184 | inner: RefCell<T>, |
|
184 | inner: RefCell<T>, | |
185 | py_shared_state: PySharedState, |
|
185 | py_shared_state: PySharedState, | |
186 | } |
|
186 | } | |
187 |
|
187 | |||
188 | impl<T> PySharedRefCell<T> { |
|
188 | impl<T> PySharedRefCell<T> { | |
189 | pub fn new(value: T) -> PySharedRefCell<T> { |
|
189 | pub fn new(value: T) -> PySharedRefCell<T> { | |
190 | Self { |
|
190 | Self { | |
191 | inner: RefCell::new(value), |
|
191 | inner: RefCell::new(value), | |
192 | py_shared_state: PySharedState::default(), |
|
192 | py_shared_state: PySharedState::default(), | |
193 | } |
|
193 | } | |
194 | } |
|
194 | } | |
195 |
|
195 | |||
196 | fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> { |
|
196 | fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> { | |
197 | // py_shared_state isn't involved since |
|
197 | // py_shared_state isn't involved since | |
198 | // - inner.borrow() would fail if self is mutably borrowed, |
|
198 | // - inner.borrow() would fail if self is mutably borrowed, | |
199 | // - and inner.borrow_mut() would fail while self is borrowed. |
|
199 | // - and inner.borrow_mut() would fail while self is borrowed. | |
200 | self.inner.borrow() |
|
200 | self.inner.borrow() | |
201 | } |
|
201 | } | |
202 |
|
202 | |||
203 | fn as_ptr(&self) -> *mut T { |
|
203 | fn as_ptr(&self) -> *mut T { | |
204 | self.inner.as_ptr() |
|
204 | self.inner.as_ptr() | |
205 | } |
|
205 | } | |
206 |
|
206 | |||
207 | // TODO: maybe this should be named as try_borrow_mut(), and use |
|
207 | // TODO: maybe this should be named as try_borrow_mut(), and use | |
208 | // inner.try_borrow_mut(). The current implementation panics if |
|
208 | // inner.try_borrow_mut(). The current implementation panics if | |
209 | // self.inner has been borrowed, but returns error if py_shared_state |
|
209 | // self.inner has been borrowed, but returns error if py_shared_state | |
210 | // refuses to borrow. |
|
210 | // refuses to borrow. | |
211 | fn borrow_mut<'a>(&'a self, py: Python<'a>) -> PyResult<PyRefMut<'a, T>> { |
|
211 | fn borrow_mut<'a>(&'a self, py: Python<'a>) -> PyResult<PyRefMut<'a, T>> { | |
212 | self.py_shared_state.borrow_mut(py, self.inner.borrow_mut()) |
|
212 | self.py_shared_state.borrow_mut(py, self.inner.borrow_mut()) | |
213 | } |
|
213 | } | |
214 | } |
|
214 | } | |
215 |
|
215 | |||
216 | /// Sharable data member of type `T` borrowed from the `PyObject`. |
|
216 | /// Sharable data member of type `T` borrowed from the `PyObject`. | |
217 | pub struct PySharedRef<'a, T> { |
|
217 | pub struct PySharedRef<'a, T> { | |
218 | py: Python<'a>, |
|
218 | py: Python<'a>, | |
219 | owner: &'a PyObject, |
|
219 | owner: &'a PyObject, | |
220 | data: &'a PySharedRefCell<T>, |
|
220 | data: &'a PySharedRefCell<T>, | |
221 | } |
|
221 | } | |
222 |
|
222 | |||
223 | impl<'a, T> PySharedRef<'a, T> { |
|
223 | impl<'a, T> PySharedRef<'a, T> { | |
224 | /// # Safety |
|
224 | /// # Safety | |
225 | /// |
|
225 | /// | |
226 | /// The `data` must be owned by the `owner`. Otherwise, the leak count |
|
226 | /// The `data` must be owned by the `owner`. Otherwise, the leak count | |
227 | /// would get wrong. |
|
227 | /// would get wrong. | |
228 | pub unsafe fn new( |
|
228 | pub unsafe fn new( | |
229 | py: Python<'a>, |
|
229 | py: Python<'a>, | |
230 | owner: &'a PyObject, |
|
230 | owner: &'a PyObject, | |
231 | data: &'a PySharedRefCell<T>, |
|
231 | data: &'a PySharedRefCell<T>, | |
232 | ) -> Self { |
|
232 | ) -> Self { | |
233 | Self { py, owner, data } |
|
233 | Self { py, owner, data } | |
234 | } |
|
234 | } | |
235 |
|
235 | |||
236 | pub fn borrow(&self) -> Ref<'a, T> { |
|
236 | pub fn borrow(&self) -> Ref<'a, T> { | |
237 | self.data.borrow(self.py) |
|
237 | self.data.borrow(self.py) | |
238 | } |
|
238 | } | |
239 |
|
239 | |||
240 | pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> { |
|
240 | pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> { | |
241 | self.data.borrow_mut(self.py) |
|
241 | self.data.borrow_mut(self.py) | |
242 | } |
|
242 | } | |
243 |
|
243 | |||
244 | /// Returns a leaked reference. |
|
244 | /// Returns a leaked reference. | |
245 | pub fn leak_immutable(&self) -> PyResult<PyLeaked<&'static T>> { |
|
245 | pub fn leak_immutable(&self) -> PyResult<PyLeaked<&'static T>> { | |
246 | let state = &self.data.py_shared_state; |
|
246 | let state = &self.data.py_shared_state; | |
247 | unsafe { |
|
247 | unsafe { | |
248 | let (static_ref, static_state_ref) = |
|
248 | let (static_ref, static_state_ref) = | |
249 | state.leak_immutable(self.py, self.data)?; |
|
249 | state.leak_immutable(self.py, self.data)?; | |
250 | Ok(PyLeaked::new( |
|
250 | Ok(PyLeaked::new( | |
251 | self.py, |
|
251 | self.py, | |
252 | self.owner, |
|
252 | self.owner, | |
253 | static_ref, |
|
253 | static_ref, | |
254 | static_state_ref, |
|
254 | static_state_ref, | |
255 | )) |
|
255 | )) | |
256 | } |
|
256 | } | |
257 | } |
|
257 | } | |
258 | } |
|
258 | } | |
259 |
|
259 | |||
260 | /// Holds a mutable reference to data shared between Python and Rust. |
|
260 | /// Holds a mutable reference to data shared between Python and Rust. | |
261 | pub struct PyRefMut<'a, T> { |
|
261 | pub struct PyRefMut<'a, T> { | |
262 | py: Python<'a>, |
|
262 | py: Python<'a>, | |
263 | inner: RefMut<'a, T>, |
|
263 | inner: RefMut<'a, T>, | |
264 | py_shared_state: &'a PySharedState, |
|
264 | py_shared_state: &'a PySharedState, | |
265 | } |
|
265 | } | |
266 |
|
266 | |||
267 | impl<'a, T> PyRefMut<'a, T> { |
|
267 | impl<'a, T> PyRefMut<'a, T> { | |
268 | // Must be constructed by PySharedState after checking its leak_count. |
|
268 | // Must be constructed by PySharedState after checking its leak_count. | |
269 | // Otherwise, drop() would incorrectly update the state. |
|
269 | // Otherwise, drop() would incorrectly update the state. | |
270 | fn new( |
|
270 | fn new( | |
271 | py: Python<'a>, |
|
271 | py: Python<'a>, | |
272 | inner: RefMut<'a, T>, |
|
272 | inner: RefMut<'a, T>, | |
273 | py_shared_state: &'a PySharedState, |
|
273 | py_shared_state: &'a PySharedState, | |
274 | ) -> Self { |
|
274 | ) -> Self { | |
275 | Self { |
|
275 | Self { | |
276 | py, |
|
276 | py, | |
277 | inner, |
|
277 | inner, | |
278 | py_shared_state, |
|
278 | py_shared_state, | |
279 | } |
|
279 | } | |
280 | } |
|
280 | } | |
281 | } |
|
281 | } | |
282 |
|
282 | |||
283 | impl<'a, T> std::ops::Deref for PyRefMut<'a, T> { |
|
283 | impl<'a, T> std::ops::Deref for PyRefMut<'a, T> { | |
284 | type Target = RefMut<'a, T>; |
|
284 | type Target = RefMut<'a, T>; | |
285 |
|
285 | |||
286 | fn deref(&self) -> &Self::Target { |
|
286 | fn deref(&self) -> &Self::Target { | |
287 | &self.inner |
|
287 | &self.inner | |
288 | } |
|
288 | } | |
289 | } |
|
289 | } | |
290 | impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> { |
|
290 | impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> { | |
291 | fn deref_mut(&mut self) -> &mut Self::Target { |
|
291 | fn deref_mut(&mut self) -> &mut Self::Target { | |
292 | &mut self.inner |
|
292 | &mut self.inner | |
293 | } |
|
293 | } | |
294 | } |
|
294 | } | |
295 |
|
295 | |||
296 | impl<'a, T> Drop for PyRefMut<'a, T> { |
|
296 | impl<'a, T> Drop for PyRefMut<'a, T> { | |
297 | fn drop(&mut self) { |
|
297 | fn drop(&mut self) { | |
298 | self.py_shared_state.decrease_leak_count(self.py, true); |
|
298 | self.py_shared_state.decrease_leak_count(self.py, true); | |
299 | } |
|
299 | } | |
300 | } |
|
300 | } | |
301 |
|
301 | |||
302 | /// Allows a `py_class!` generated struct to share references to one of its |
|
302 | /// Allows a `py_class!` generated struct to share references to one of its | |
303 | /// data members with Python. |
|
303 | /// data members with Python. | |
304 | /// |
|
304 | /// | |
305 | /// # Parameters |
|
305 | /// # Parameters | |
306 | /// |
|
306 | /// | |
307 | /// * `$name` is the same identifier used in for `py_class!` macro call. |
|
307 | /// * `$name` is the same identifier used in for `py_class!` macro call. | |
308 | /// * `$inner_struct` is the identifier of the underlying Rust struct |
|
308 | /// * `$inner_struct` is the identifier of the underlying Rust struct | |
309 | /// * `$data_member` is the identifier of the data member of `$inner_struct` |
|
309 | /// * `$data_member` is the identifier of the data member of `$inner_struct` | |
310 | /// that will be shared. |
|
310 | /// that will be shared. | |
311 | /// * `$shared_accessor` is the function name to be generated, which allows |
|
311 | /// * `$shared_accessor` is the function name to be generated, which allows | |
312 | /// safe access to the data member. |
|
312 | /// safe access to the data member. | |
313 | /// |
|
313 | /// | |
314 | /// # Safety |
|
314 | /// # Safety | |
315 | /// |
|
315 | /// | |
316 | /// `$data_member` must persist while the `$name` object is alive. In other |
|
316 | /// `$data_member` must persist while the `$name` object is alive. In other | |
317 | /// words, it must be an accessor to a data field of the Python object. |
|
317 | /// words, it must be an accessor to a data field of the Python object. | |
318 | /// |
|
318 | /// | |
319 | /// # Example |
|
319 | /// # Example | |
320 | /// |
|
320 | /// | |
321 | /// ``` |
|
321 | /// ``` | |
322 | /// struct MyStruct { |
|
322 | /// struct MyStruct { | |
323 | /// inner: Vec<u32>; |
|
323 | /// inner: Vec<u32>; | |
324 | /// } |
|
324 | /// } | |
325 | /// |
|
325 | /// | |
326 | /// py_class!(pub class MyType |py| { |
|
326 | /// py_class!(pub class MyType |py| { | |
327 | /// data inner: PySharedRefCell<MyStruct>; |
|
327 | /// data inner: PySharedRefCell<MyStruct>; | |
328 | /// }); |
|
328 | /// }); | |
329 | /// |
|
329 | /// | |
330 | /// py_shared_ref!(MyType, MyStruct, inner, inner_shared); |
|
330 | /// py_shared_ref!(MyType, MyStruct, inner, inner_shared); | |
331 | /// ``` |
|
331 | /// ``` | |
332 | macro_rules! py_shared_ref { |
|
332 | macro_rules! py_shared_ref { | |
333 | ( |
|
333 | ( | |
334 | $name: ident, |
|
334 | $name: ident, | |
335 | $inner_struct: ident, |
|
335 | $inner_struct: ident, | |
336 | $data_member: ident, |
|
336 | $data_member: ident, | |
337 | $shared_accessor: ident |
|
337 | $shared_accessor: ident | |
338 | ) => { |
|
338 | ) => { | |
339 | impl $name { |
|
339 | impl $name { | |
340 | /// Returns a safe reference to the shared `$data_member`. |
|
340 | /// Returns a safe reference to the shared `$data_member`. | |
341 | /// |
|
341 | /// | |
342 | /// This function guarantees that `PySharedRef` is created with |
|
342 | /// This function guarantees that `PySharedRef` is created with | |
343 | /// the valid `self` and `self.$data_member(py)` pair. |
|
343 | /// the valid `self` and `self.$data_member(py)` pair. | |
344 | fn $shared_accessor<'a>( |
|
344 | fn $shared_accessor<'a>( | |
345 | &'a self, |
|
345 | &'a self, | |
346 | py: Python<'a>, |
|
346 | py: Python<'a>, | |
347 | ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> { |
|
347 | ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> { | |
348 | use cpython::PythonObject; |
|
348 | use cpython::PythonObject; | |
349 | use $crate::ref_sharing::PySharedRef; |
|
349 | use $crate::ref_sharing::PySharedRef; | |
350 | let owner = self.as_object(); |
|
350 | let owner = self.as_object(); | |
351 | let data = self.$data_member(py); |
|
351 | let data = self.$data_member(py); | |
352 | unsafe { PySharedRef::new(py, owner, data) } |
|
352 | unsafe { PySharedRef::new(py, owner, data) } | |
353 | } |
|
353 | } | |
354 | } |
|
354 | } | |
355 | }; |
|
355 | }; | |
356 | } |
|
356 | } | |
357 |
|
357 | |||
358 | /// Manage immutable references to `PyObject` leaked into Python iterators. |
|
358 | /// Manage immutable references to `PyObject` leaked into Python iterators. | |
359 | /// |
|
359 | /// | |
360 | /// This reference will be invalidated once the original value is mutably |
|
360 | /// This reference will be invalidated once the original value is mutably | |
361 | /// borrowed. |
|
361 | /// borrowed. | |
362 | pub struct PyLeaked<T> { |
|
362 | pub struct PyLeaked<T> { | |
363 | inner: PyObject, |
|
363 | inner: PyObject, | |
364 | data: Option<T>, |
|
364 | data: Option<T>, | |
365 | py_shared_state: &'static PySharedState, |
|
365 | py_shared_state: &'static PySharedState, | |
366 | /// Generation counter of data `T` captured when PyLeaked is created. |
|
366 | /// Generation counter of data `T` captured when PyLeaked is created. | |
367 | generation: usize, |
|
367 | generation: usize, | |
368 | } |
|
368 | } | |
369 |
|
369 | |||
370 | // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked |
|
370 | // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked | |
371 | // without taking Python GIL wouldn't be safe. Also, the underling reference |
|
371 | // without taking Python GIL wouldn't be safe. Also, the underling reference | |
372 | // is invalid if generation != py_shared_state.generation. |
|
372 | // is invalid if generation != py_shared_state.generation. | |
373 |
|
373 | |||
374 | impl<T> PyLeaked<T> { |
|
374 | impl<T> PyLeaked<T> { | |
375 | /// # Safety |
|
375 | /// # Safety | |
376 | /// |
|
376 | /// | |
377 | /// The `py_shared_state` must be owned by the `inner` Python object. |
|
377 | /// The `py_shared_state` must be owned by the `inner` Python object. | |
378 | fn new( |
|
378 | fn new( | |
379 | py: Python, |
|
379 | py: Python, | |
380 | inner: &PyObject, |
|
380 | inner: &PyObject, | |
381 | data: T, |
|
381 | data: T, | |
382 | py_shared_state: &'static PySharedState, |
|
382 | py_shared_state: &'static PySharedState, | |
383 | ) -> Self { |
|
383 | ) -> Self { | |
384 | Self { |
|
384 | Self { | |
385 | inner: inner.clone_ref(py), |
|
385 | inner: inner.clone_ref(py), | |
386 | data: Some(data), |
|
386 | data: Some(data), | |
387 | py_shared_state, |
|
387 | py_shared_state, | |
388 | generation: py_shared_state.current_generation(py), |
|
388 | generation: py_shared_state.current_generation(py), | |
389 | } |
|
389 | } | |
390 | } |
|
390 | } | |
391 |
|
391 | |||
392 | /// Immutably borrows the wrapped value. |
|
392 | /// Immutably borrows the wrapped value. | |
393 | /// |
|
393 | /// | |
394 | /// Borrowing fails if the underlying reference has been invalidated. |
|
394 | /// Borrowing fails if the underlying reference has been invalidated. | |
395 | pub fn try_borrow<'a>( |
|
395 | pub fn try_borrow<'a>( | |
396 | &'a self, |
|
396 | &'a self, | |
397 | py: Python<'a>, |
|
397 | py: Python<'a>, | |
398 | ) -> PyResult<PyLeakedRef<'a, T>> { |
|
398 | ) -> PyResult<PyLeakedRef<'a, T>> { | |
399 | self.validate_generation(py)?; |
|
399 | self.validate_generation(py)?; | |
400 | Ok(PyLeakedRef { |
|
400 | Ok(PyLeakedRef { | |
401 | _borrow: BorrowPyShared::new(py, self.py_shared_state), |
|
401 | _borrow: BorrowPyShared::new(py, self.py_shared_state), | |
402 | data: self.data.as_ref().unwrap(), |
|
402 | data: self.data.as_ref().unwrap(), | |
403 | }) |
|
403 | }) | |
404 | } |
|
404 | } | |
405 |
|
405 | |||
406 | /// Mutably borrows the wrapped value. |
|
406 | /// Mutably borrows the wrapped value. | |
407 | /// |
|
407 | /// | |
408 | /// Borrowing fails if the underlying reference has been invalidated. |
|
408 | /// Borrowing fails if the underlying reference has been invalidated. | |
409 | /// |
|
409 | /// | |
410 | /// Typically `T` is an iterator. If `T` is an immutable reference, |
|
410 | /// Typically `T` is an iterator. If `T` is an immutable reference, | |
411 | /// `get_mut()` is useless since the inner value can't be mutated. |
|
411 | /// `get_mut()` is useless since the inner value can't be mutated. | |
412 | pub fn try_borrow_mut<'a>( |
|
412 | pub fn try_borrow_mut<'a>( | |
413 | &'a mut self, |
|
413 | &'a mut self, | |
414 | py: Python<'a>, |
|
414 | py: Python<'a>, | |
415 | ) -> PyResult<PyLeakedRefMut<'a, T>> { |
|
415 | ) -> PyResult<PyLeakedRefMut<'a, T>> { | |
416 | self.validate_generation(py)?; |
|
416 | self.validate_generation(py)?; | |
417 | Ok(PyLeakedRefMut { |
|
417 | Ok(PyLeakedRefMut { | |
418 | _borrow: BorrowPyShared::new(py, self.py_shared_state), |
|
418 | _borrow: BorrowPyShared::new(py, self.py_shared_state), | |
419 | data: self.data.as_mut().unwrap(), |
|
419 | data: self.data.as_mut().unwrap(), | |
420 | }) |
|
420 | }) | |
421 | } |
|
421 | } | |
422 |
|
422 | |||
423 | /// Converts the inner value by the given function. |
|
423 | /// Converts the inner value by the given function. | |
424 | /// |
|
424 | /// | |
425 | /// Typically `T` is a static reference to a container, and `U` is an |
|
425 | /// Typically `T` is a static reference to a container, and `U` is an | |
426 | /// iterator of that container. |
|
426 | /// iterator of that container. | |
427 | /// |
|
427 | /// | |
428 | /// # Panics |
|
428 | /// # Panics | |
429 | /// |
|
429 | /// | |
430 | /// Panics if the underlying reference has been invalidated. |
|
430 | /// Panics if the underlying reference has been invalidated. | |
431 | /// |
|
431 | /// | |
432 | /// This is typically called immediately after the `PyLeaked` is obtained. |
|
432 | /// This is typically called immediately after the `PyLeaked` is obtained. | |
433 | /// In which case, the reference must be valid and no panic would occur. |
|
433 | /// In which case, the reference must be valid and no panic would occur. | |
434 | /// |
|
434 | /// | |
435 | /// # Safety |
|
435 | /// # Safety | |
436 | /// |
|
436 | /// | |
437 | /// The lifetime of the object passed in to the function `f` is cheated. |
|
437 | /// The lifetime of the object passed in to the function `f` is cheated. | |
438 | /// It's typically a static reference, but is valid only while the |
|
438 | /// It's typically a static reference, but is valid only while the | |
439 | /// corresponding `PyLeaked` is alive. Do not copy it out of the |
|
439 | /// corresponding `PyLeaked` is alive. Do not copy it out of the | |
440 | /// function call. |
|
440 | /// function call. | |
441 | pub unsafe fn map<U>( |
|
441 | pub unsafe fn map<U>( | |
442 | mut self, |
|
442 | mut self, | |
443 | py: Python, |
|
443 | py: Python, | |
444 | f: impl FnOnce(T) -> U, |
|
444 | f: impl FnOnce(T) -> U, | |
445 | ) -> PyLeaked<U> { |
|
445 | ) -> PyLeaked<U> { | |
446 | // Needs to test the generation value to make sure self.data reference |
|
446 | // Needs to test the generation value to make sure self.data reference | |
447 | // is still intact. |
|
447 | // is still intact. | |
448 | self.validate_generation(py) |
|
448 | self.validate_generation(py) | |
449 | .expect("map() over invalidated leaked reference"); |
|
449 | .expect("map() over invalidated leaked reference"); | |
450 |
|
450 | |||
451 | // f() could make the self.data outlive. That's why map() is unsafe. |
|
451 | // f() could make the self.data outlive. That's why map() is unsafe. | |
452 | // In order to make this function safe, maybe we'll need a way to |
|
452 | // In order to make this function safe, maybe we'll need a way to | |
453 | // temporarily restrict the lifetime of self.data and translate the |
|
453 | // temporarily restrict the lifetime of self.data and translate the | |
454 | // returned object back to Something<'static>. |
|
454 | // returned object back to Something<'static>. | |
455 | let new_data = f(self.data.take().unwrap()); |
|
455 | let new_data = f(self.data.take().unwrap()); | |
456 | PyLeaked { |
|
456 | PyLeaked { | |
457 | inner: self.inner.clone_ref(py), |
|
457 | inner: self.inner.clone_ref(py), | |
458 | data: Some(new_data), |
|
458 | data: Some(new_data), | |
459 | py_shared_state: self.py_shared_state, |
|
459 | py_shared_state: self.py_shared_state, | |
460 | generation: self.generation, |
|
460 | generation: self.generation, | |
461 | } |
|
461 | } | |
462 | } |
|
462 | } | |
463 |
|
463 | |||
464 | fn validate_generation(&self, py: Python) -> PyResult<()> { |
|
464 | fn validate_generation(&self, py: Python) -> PyResult<()> { | |
465 | if self.py_shared_state.current_generation(py) == self.generation { |
|
465 | if self.py_shared_state.current_generation(py) == self.generation { | |
466 | Ok(()) |
|
466 | Ok(()) | |
467 | } else { |
|
467 | } else { | |
468 | Err(PyErr::new::<exc::RuntimeError, _>( |
|
468 | Err(PyErr::new::<exc::RuntimeError, _>( | |
469 | py, |
|
469 | py, | |
470 | "Cannot access to leaked reference after mutation", |
|
470 | "Cannot access to leaked reference after mutation", | |
471 | )) |
|
471 | )) | |
472 | } |
|
472 | } | |
473 | } |
|
473 | } | |
474 | } |
|
474 | } | |
475 |
|
475 | |||
476 | /// Immutably borrowed reference to a leaked value. |
|
476 | /// Immutably borrowed reference to a leaked value. | |
477 | pub struct PyLeakedRef<'a, T> { |
|
477 | pub struct PyLeakedRef<'a, T> { | |
478 | _borrow: BorrowPyShared<'a>, |
|
478 | _borrow: BorrowPyShared<'a>, | |
479 | data: &'a T, |
|
479 | data: &'a T, | |
480 | } |
|
480 | } | |
481 |
|
481 | |||
482 | impl<T> Deref for PyLeakedRef<'_, T> { |
|
482 | impl<T> Deref for PyLeakedRef<'_, T> { | |
483 | type Target = T; |
|
483 | type Target = T; | |
484 |
|
484 | |||
485 | fn deref(&self) -> &T { |
|
485 | fn deref(&self) -> &T { | |
486 | self.data |
|
486 | self.data | |
487 | } |
|
487 | } | |
488 | } |
|
488 | } | |
489 |
|
489 | |||
490 | /// Mutably borrowed reference to a leaked value. |
|
490 | /// Mutably borrowed reference to a leaked value. | |
491 | pub struct PyLeakedRefMut<'a, T> { |
|
491 | pub struct PyLeakedRefMut<'a, T> { | |
492 | _borrow: BorrowPyShared<'a>, |
|
492 | _borrow: BorrowPyShared<'a>, | |
493 | data: &'a mut T, |
|
493 | data: &'a mut T, | |
494 | } |
|
494 | } | |
495 |
|
495 | |||
496 | impl<T> Deref for PyLeakedRefMut<'_, T> { |
|
496 | impl<T> Deref for PyLeakedRefMut<'_, T> { | |
497 | type Target = T; |
|
497 | type Target = T; | |
498 |
|
498 | |||
499 | fn deref(&self) -> &T { |
|
499 | fn deref(&self) -> &T { | |
500 | self.data |
|
500 | self.data | |
501 | } |
|
501 | } | |
502 | } |
|
502 | } | |
503 |
|
503 | |||
504 | impl<T> DerefMut for PyLeakedRefMut<'_, T> { |
|
504 | impl<T> DerefMut for PyLeakedRefMut<'_, T> { | |
505 | fn deref_mut(&mut self) -> &mut T { |
|
505 | fn deref_mut(&mut self) -> &mut T { | |
506 | self.data |
|
506 | self.data | |
507 | } |
|
507 | } | |
508 | } |
|
508 | } | |
509 |
|
509 | |||
510 | /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator. |
|
510 | /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator. | |
511 | /// |
|
511 | /// | |
512 | /// TODO: this is a bit awkward to use, and a better (more complicated) |
|
512 | /// TODO: this is a bit awkward to use, and a better (more complicated) | |
513 | /// procedural macro would simplify the interface a lot. |
|
513 | /// procedural macro would simplify the interface a lot. | |
514 | /// |
|
514 | /// | |
515 | /// # Parameters |
|
515 | /// # Parameters | |
516 | /// |
|
516 | /// | |
517 | /// * `$name` is the identifier to give to the resulting Rust struct. |
|
517 | /// * `$name` is the identifier to give to the resulting Rust struct. | |
518 | /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call. |
|
518 | /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call. | |
519 | /// * `$iterator_type` is the type of the Rust iterator. |
|
519 | /// * `$iterator_type` is the type of the Rust iterator. | |
520 | /// * `$success_func` is a function for processing the Rust `(key, value)` |
|
520 | /// * `$success_func` is a function for processing the Rust `(key, value)` | |
521 | /// tuple on iteration success, turning it into something Python understands. |
|
521 | /// tuple on iteration success, turning it into something Python understands. | |
522 | /// * `$success_func` is the return type of `$success_func` |
|
522 | /// * `$success_func` is the return type of `$success_func` | |
523 | /// |
|
523 | /// | |
524 | /// # Example |
|
524 | /// # Example | |
525 | /// |
|
525 | /// | |
526 | /// ``` |
|
526 | /// ``` | |
527 | /// struct MyStruct { |
|
527 | /// struct MyStruct { | |
528 | /// inner: HashMap<Vec<u8>, Vec<u8>>; |
|
528 | /// inner: HashMap<Vec<u8>, Vec<u8>>; | |
529 | /// } |
|
529 | /// } | |
530 | /// |
|
530 | /// | |
531 | /// py_class!(pub class MyType |py| { |
|
531 | /// py_class!(pub class MyType |py| { | |
532 | /// data inner: PySharedRefCell<MyStruct>; |
|
532 | /// data inner: PySharedRefCell<MyStruct>; | |
533 | /// |
|
533 | /// | |
534 | /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> { |
|
534 | /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> { | |
535 | /// let leaked_ref = self.inner_shared(py).leak_immutable()?; |
|
535 | /// let leaked_ref = self.inner_shared(py).leak_immutable()?; | |
536 | /// MyTypeItemsIterator::from_inner( |
|
536 | /// MyTypeItemsIterator::from_inner( | |
537 | /// py, |
|
537 | /// py, | |
538 | /// unsafe { leaked_ref.map(py, |o| o.iter()) }, |
|
538 | /// unsafe { leaked_ref.map(py, |o| o.iter()) }, | |
539 | /// ) |
|
539 | /// ) | |
540 | /// } |
|
540 | /// } | |
541 | /// }); |
|
541 | /// }); | |
542 | /// |
|
542 | /// | |
543 | /// impl MyType { |
|
543 | /// impl MyType { | |
544 | /// fn translate_key_value( |
|
544 | /// fn translate_key_value( | |
545 | /// py: Python, |
|
545 | /// py: Python, | |
546 | /// res: (&Vec<u8>, &Vec<u8>), |
|
546 | /// res: (&Vec<u8>, &Vec<u8>), | |
547 | /// ) -> PyResult<Option<(PyBytes, PyBytes)>> { |
|
547 | /// ) -> PyResult<Option<(PyBytes, PyBytes)>> { | |
548 | /// let (f, entry) = res; |
|
548 | /// let (f, entry) = res; | |
549 | /// Ok(Some(( |
|
549 | /// Ok(Some(( | |
550 | /// PyBytes::new(py, f), |
|
550 | /// PyBytes::new(py, f), | |
551 | /// PyBytes::new(py, entry), |
|
551 | /// PyBytes::new(py, entry), | |
552 | /// ))) |
|
552 | /// ))) | |
553 | /// } |
|
553 | /// } | |
554 | /// } |
|
554 | /// } | |
555 | /// |
|
555 | /// | |
556 | /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef); |
|
556 | /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef); | |
557 | /// |
|
557 | /// | |
558 | /// py_shared_iterator!( |
|
558 | /// py_shared_iterator!( | |
559 | /// MyTypeItemsIterator, |
|
559 | /// MyTypeItemsIterator, | |
560 | /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>, |
|
560 | /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>, | |
561 | /// MyType::translate_key_value, |
|
561 | /// MyType::translate_key_value, | |
562 | /// Option<(PyBytes, PyBytes)> |
|
562 | /// Option<(PyBytes, PyBytes)> | |
563 | /// ); |
|
563 | /// ); | |
564 | /// ``` |
|
564 | /// ``` | |
565 | macro_rules! py_shared_iterator { |
|
565 | macro_rules! py_shared_iterator { | |
566 | ( |
|
566 | ( | |
567 | $name: ident, |
|
567 | $name: ident, | |
568 | $leaked: ty, |
|
568 | $leaked: ty, | |
569 | $success_func: expr, |
|
569 | $success_func: expr, | |
570 | $success_type: ty |
|
570 | $success_type: ty | |
571 | ) => { |
|
571 | ) => { | |
572 | py_class!(pub class $name |py| { |
|
572 | py_class!(pub class $name |py| { | |
573 |
data inner: RefCell< |
|
573 | data inner: RefCell<$leaked>; | |
574 |
|
574 | |||
575 | def __next__(&self) -> PyResult<$success_type> { |
|
575 | def __next__(&self) -> PyResult<$success_type> { | |
576 |
let mut |
|
576 | let mut leaked = self.inner(py).borrow_mut(); | |
577 |
|
|
577 | let mut iter = leaked.try_borrow_mut(py)?; | |
578 | let mut iter = leaked.try_borrow_mut(py)?; |
|
578 | match iter.next() { | |
579 |
|
|
579 | None => Ok(None), | |
580 | None => { |
|
580 | Some(res) => $success_func(py, res), | |
581 | drop(iter); |
|
|||
582 | // replace Some(inner) by None, drop $leaked |
|
|||
583 | inner_opt.take(); |
|
|||
584 | Ok(None) |
|
|||
585 | } |
|
|||
586 | Some(res) => { |
|
|||
587 | $success_func(py, res) |
|
|||
588 | } |
|
|||
589 | } |
|
|||
590 | } else { |
|
|||
591 | Ok(None) |
|
|||
592 | } |
|
581 | } | |
593 | } |
|
582 | } | |
594 |
|
583 | |||
595 | def __iter__(&self) -> PyResult<Self> { |
|
584 | def __iter__(&self) -> PyResult<Self> { | |
596 | Ok(self.clone_ref(py)) |
|
585 | Ok(self.clone_ref(py)) | |
597 | } |
|
586 | } | |
598 | }); |
|
587 | }); | |
599 |
|
588 | |||
600 | impl $name { |
|
589 | impl $name { | |
601 | pub fn from_inner( |
|
590 | pub fn from_inner( | |
602 | py: Python, |
|
591 | py: Python, | |
603 | leaked: $leaked, |
|
592 | leaked: $leaked, | |
604 | ) -> PyResult<Self> { |
|
593 | ) -> PyResult<Self> { | |
605 | Self::create_instance( |
|
594 | Self::create_instance( | |
606 | py, |
|
595 | py, | |
607 |
RefCell::new( |
|
596 | RefCell::new(leaked), | |
608 | ) |
|
597 | ) | |
609 | } |
|
598 | } | |
610 | } |
|
599 | } | |
611 | }; |
|
600 | }; | |
612 | } |
|
601 | } | |
613 |
|
602 | |||
614 | #[cfg(test)] |
|
603 | #[cfg(test)] | |
615 | #[cfg(any(feature = "python27-bin", feature = "python3-bin"))] |
|
604 | #[cfg(any(feature = "python27-bin", feature = "python3-bin"))] | |
616 | mod test { |
|
605 | mod test { | |
617 | use super::*; |
|
606 | use super::*; | |
618 | use cpython::{GILGuard, Python}; |
|
607 | use cpython::{GILGuard, Python}; | |
619 |
|
608 | |||
620 | py_class!(class Owner |py| { |
|
609 | py_class!(class Owner |py| { | |
621 | data string: PySharedRefCell<String>; |
|
610 | data string: PySharedRefCell<String>; | |
622 | }); |
|
611 | }); | |
623 | py_shared_ref!(Owner, String, string, string_shared); |
|
612 | py_shared_ref!(Owner, String, string, string_shared); | |
624 |
|
613 | |||
625 | fn prepare_env() -> (GILGuard, Owner) { |
|
614 | fn prepare_env() -> (GILGuard, Owner) { | |
626 | let gil = Python::acquire_gil(); |
|
615 | let gil = Python::acquire_gil(); | |
627 | let py = gil.python(); |
|
616 | let py = gil.python(); | |
628 | let owner = |
|
617 | let owner = | |
629 | Owner::create_instance(py, PySharedRefCell::new("new".to_owned())) |
|
618 | Owner::create_instance(py, PySharedRefCell::new("new".to_owned())) | |
630 | .unwrap(); |
|
619 | .unwrap(); | |
631 | (gil, owner) |
|
620 | (gil, owner) | |
632 | } |
|
621 | } | |
633 |
|
622 | |||
634 | #[test] |
|
623 | #[test] | |
635 | fn test_leaked_borrow() { |
|
624 | fn test_leaked_borrow() { | |
636 | let (gil, owner) = prepare_env(); |
|
625 | let (gil, owner) = prepare_env(); | |
637 | let py = gil.python(); |
|
626 | let py = gil.python(); | |
638 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
627 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
639 | let leaked_ref = leaked.try_borrow(py).unwrap(); |
|
628 | let leaked_ref = leaked.try_borrow(py).unwrap(); | |
640 | assert_eq!(*leaked_ref, "new"); |
|
629 | assert_eq!(*leaked_ref, "new"); | |
641 | } |
|
630 | } | |
642 |
|
631 | |||
643 | #[test] |
|
632 | #[test] | |
644 | fn test_leaked_borrow_mut() { |
|
633 | fn test_leaked_borrow_mut() { | |
645 | let (gil, owner) = prepare_env(); |
|
634 | let (gil, owner) = prepare_env(); | |
646 | let py = gil.python(); |
|
635 | let py = gil.python(); | |
647 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
636 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
648 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; |
|
637 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; | |
649 | let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap(); |
|
638 | let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap(); | |
650 | assert_eq!(leaked_ref.next(), Some('n')); |
|
639 | assert_eq!(leaked_ref.next(), Some('n')); | |
651 | assert_eq!(leaked_ref.next(), Some('e')); |
|
640 | assert_eq!(leaked_ref.next(), Some('e')); | |
652 | assert_eq!(leaked_ref.next(), Some('w')); |
|
641 | assert_eq!(leaked_ref.next(), Some('w')); | |
653 | assert_eq!(leaked_ref.next(), None); |
|
642 | assert_eq!(leaked_ref.next(), None); | |
654 | } |
|
643 | } | |
655 |
|
644 | |||
656 | #[test] |
|
645 | #[test] | |
657 | fn test_leaked_borrow_after_mut() { |
|
646 | fn test_leaked_borrow_after_mut() { | |
658 | let (gil, owner) = prepare_env(); |
|
647 | let (gil, owner) = prepare_env(); | |
659 | let py = gil.python(); |
|
648 | let py = gil.python(); | |
660 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
649 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
661 | owner.string_shared(py).borrow_mut().unwrap().clear(); |
|
650 | owner.string_shared(py).borrow_mut().unwrap().clear(); | |
662 | assert!(leaked.try_borrow(py).is_err()); |
|
651 | assert!(leaked.try_borrow(py).is_err()); | |
663 | } |
|
652 | } | |
664 |
|
653 | |||
665 | #[test] |
|
654 | #[test] | |
666 | fn test_leaked_borrow_mut_after_mut() { |
|
655 | fn test_leaked_borrow_mut_after_mut() { | |
667 | let (gil, owner) = prepare_env(); |
|
656 | let (gil, owner) = prepare_env(); | |
668 | let py = gil.python(); |
|
657 | let py = gil.python(); | |
669 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
658 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
670 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; |
|
659 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; | |
671 | owner.string_shared(py).borrow_mut().unwrap().clear(); |
|
660 | owner.string_shared(py).borrow_mut().unwrap().clear(); | |
672 | assert!(leaked_iter.try_borrow_mut(py).is_err()); |
|
661 | assert!(leaked_iter.try_borrow_mut(py).is_err()); | |
673 | } |
|
662 | } | |
674 |
|
663 | |||
675 | #[test] |
|
664 | #[test] | |
676 | #[should_panic(expected = "map() over invalidated leaked reference")] |
|
665 | #[should_panic(expected = "map() over invalidated leaked reference")] | |
677 | fn test_leaked_map_after_mut() { |
|
666 | fn test_leaked_map_after_mut() { | |
678 | let (gil, owner) = prepare_env(); |
|
667 | let (gil, owner) = prepare_env(); | |
679 | let py = gil.python(); |
|
668 | let py = gil.python(); | |
680 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
669 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
681 | owner.string_shared(py).borrow_mut().unwrap().clear(); |
|
670 | owner.string_shared(py).borrow_mut().unwrap().clear(); | |
682 | let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; |
|
671 | let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; | |
683 | } |
|
672 | } | |
684 |
|
673 | |||
685 | #[test] |
|
674 | #[test] | |
686 | fn test_borrow_mut_while_leaked_ref() { |
|
675 | fn test_borrow_mut_while_leaked_ref() { | |
687 | let (gil, owner) = prepare_env(); |
|
676 | let (gil, owner) = prepare_env(); | |
688 | let py = gil.python(); |
|
677 | let py = gil.python(); | |
689 | assert!(owner.string_shared(py).borrow_mut().is_ok()); |
|
678 | assert!(owner.string_shared(py).borrow_mut().is_ok()); | |
690 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
679 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
691 | { |
|
680 | { | |
692 | let _leaked_ref = leaked.try_borrow(py).unwrap(); |
|
681 | let _leaked_ref = leaked.try_borrow(py).unwrap(); | |
693 | assert!(owner.string_shared(py).borrow_mut().is_err()); |
|
682 | assert!(owner.string_shared(py).borrow_mut().is_err()); | |
694 | { |
|
683 | { | |
695 | let _leaked_ref2 = leaked.try_borrow(py).unwrap(); |
|
684 | let _leaked_ref2 = leaked.try_borrow(py).unwrap(); | |
696 | assert!(owner.string_shared(py).borrow_mut().is_err()); |
|
685 | assert!(owner.string_shared(py).borrow_mut().is_err()); | |
697 | } |
|
686 | } | |
698 | assert!(owner.string_shared(py).borrow_mut().is_err()); |
|
687 | assert!(owner.string_shared(py).borrow_mut().is_err()); | |
699 | } |
|
688 | } | |
700 | assert!(owner.string_shared(py).borrow_mut().is_ok()); |
|
689 | assert!(owner.string_shared(py).borrow_mut().is_ok()); | |
701 | } |
|
690 | } | |
702 |
|
691 | |||
703 | #[test] |
|
692 | #[test] | |
704 | fn test_borrow_mut_while_leaked_ref_mut() { |
|
693 | fn test_borrow_mut_while_leaked_ref_mut() { | |
705 | let (gil, owner) = prepare_env(); |
|
694 | let (gil, owner) = prepare_env(); | |
706 | let py = gil.python(); |
|
695 | let py = gil.python(); | |
707 | assert!(owner.string_shared(py).borrow_mut().is_ok()); |
|
696 | assert!(owner.string_shared(py).borrow_mut().is_ok()); | |
708 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); |
|
697 | let leaked = owner.string_shared(py).leak_immutable().unwrap(); | |
709 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; |
|
698 | let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) }; | |
710 | { |
|
699 | { | |
711 | let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap(); |
|
700 | let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap(); | |
712 | assert!(owner.string_shared(py).borrow_mut().is_err()); |
|
701 | assert!(owner.string_shared(py).borrow_mut().is_err()); | |
713 | } |
|
702 | } | |
714 | assert!(owner.string_shared(py).borrow_mut().is_ok()); |
|
703 | assert!(owner.string_shared(py).borrow_mut().is_ok()); | |
715 | } |
|
704 | } | |
716 | } |
|
705 | } |
General Comments 0
You need to be logged in to leave comments.
Login now