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